code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
package cert
import (
"context"
"crypto/rand"
"net/http"
"golang.org/x/net/http2"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"fmt"
"io"
"io/ioutil"
"math/big"
"net"
"os"
"reflect"
"testing"
"time"
cleanhttp "github.com/hashicorp/go-cleanhttp"
log "github.com/hashicorp/go-hclog"
"github.com/hashicorp/vault/api"
vaulthttp "github.com/hashicorp/vault/http"
"github.com/hashicorp/go-rootcerts"
"github.com/hashicorp/vault/builtin/logical/pki"
"github.com/hashicorp/vault/helper/certutil"
"github.com/hashicorp/vault/logical"
"github.com/hashicorp/vault/logical/framework"
logicaltest "github.com/hashicorp/vault/logical/testing"
"github.com/hashicorp/vault/vault"
"github.com/mitchellh/mapstructure"
)
const (
serverCertPath = "test-fixtures/cacert.pem"
serverKeyPath = "test-fixtures/cakey.pem"
serverCAPath = serverCertPath
testRootCACertPath1 = "test-fixtures/testcacert1.pem"
testRootCAKeyPath1 = "test-fixtures/testcakey1.pem"
testCertPath1 = "test-fixtures/testissuedcert4.pem"
testKeyPath1 = "test-fixtures/testissuedkey4.pem"
testIssuedCertCRL = "test-fixtures/issuedcertcrl"
testRootCACertPath2 = "test-fixtures/testcacert2.pem"
testRootCAKeyPath2 = "test-fixtures/testcakey2.pem"
testRootCertCRL = "test-fixtures/cacert2crl"
)
// Unlike testConnState, this method does not use the same 'tls.Config' objects for
// both dialing and listening. Instead, it runs the server without specifying its CA.
// But the client, presents the CA cert of the server to trust the server.
// The client can present a cert and key which is completely independent of server's CA.
// The connection state returned will contain the certificate presented by the client.
func connectionState(serverCAPath, serverCertPath, serverKeyPath, clientCertPath, clientKeyPath string) (tls.ConnectionState, error) {
serverKeyPair, err := tls.LoadX509KeyPair(serverCertPath, serverKeyPath)
if err != nil {
return tls.ConnectionState{}, err
}
// Prepare the listener configuration with server's key pair
listenConf := &tls.Config{
Certificates: []tls.Certificate{serverKeyPair},
ClientAuth: tls.RequestClientCert,
}
clientKeyPair, err := tls.LoadX509KeyPair(clientCertPath, clientKeyPath)
if err != nil {
return tls.ConnectionState{}, err
}
// Load the CA cert required by the client to authenticate the server.
rootConfig := &rootcerts.Config{
CAFile: serverCAPath,
}
serverCAs, err := rootcerts.LoadCACerts(rootConfig)
if err != nil {
return tls.ConnectionState{}, err
}
// Prepare the dial configuration that the client uses to establish the connection.
dialConf := &tls.Config{
Certificates: []tls.Certificate{clientKeyPair},
RootCAs: serverCAs,
}
// Start the server.
list, err := tls.Listen("tcp", "127.0.0.1:0", listenConf)
if err != nil {
return tls.ConnectionState{}, err
}
defer list.Close()
// Accept connections.
serverErrors := make(chan error, 1)
connState := make(chan tls.ConnectionState)
go func() {
defer close(connState)
serverConn, err := list.Accept()
if err != nil {
serverErrors <- err
close(serverErrors)
return
}
defer serverConn.Close()
// Read the ping
buf := make([]byte, 4)
_, err = serverConn.Read(buf)
if (err != nil) && (err != io.EOF) {
serverErrors <- err
close(serverErrors)
return
}
close(serverErrors)
connState <- serverConn.(*tls.Conn).ConnectionState()
}()
// Establish a connection from the client side and write a few bytes.
clientErrors := make(chan error, 1)
go func() {
addr := list.Addr().String()
conn, err := tls.Dial("tcp", addr, dialConf)
if err != nil {
clientErrors <- err
close(clientErrors)
return
}
defer conn.Close()
// Write ping
_, err = conn.Write([]byte("ping"))
if err != nil {
clientErrors <- err
}
close(clientErrors)
}()
for err = range clientErrors {
if err != nil {
return tls.ConnectionState{}, fmt.Errorf("error in client goroutine:%v", err)
}
}
for err = range serverErrors {
if err != nil {
return tls.ConnectionState{}, fmt.Errorf("error in server goroutine:%v", err)
}
}
// Grab the current state
return <-connState, nil
}
func TestBackend_PermittedDNSDomainsIntermediateCA(t *testing.T) {
// Enable PKI secret engine and Cert auth method
coreConfig := &vault.CoreConfig{
DisableMlock: true,
DisableCache: true,
Logger: log.NewNullLogger(),
CredentialBackends: map[string]logical.Factory{
"cert": Factory,
},
LogicalBackends: map[string]logical.Factory{
"pki": pki.Factory,
},
}
cluster := vault.NewTestCluster(t, coreConfig, &vault.TestClusterOptions{
HandlerFunc: vaulthttp.Handler,
})
cluster.Start()
defer cluster.Cleanup()
cores := cluster.Cores
vault.TestWaitActive(t, cores[0].Core)
client := cores[0].Client
var err error
// Mount /pki as a root CA
err = client.Sys().Mount("pki", &api.MountInput{
Type: "pki",
Config: api.MountConfigInput{
DefaultLeaseTTL: "16h",
MaxLeaseTTL: "32h",
},
})
if err != nil {
t.Fatal(err)
}
// Set the cluster's certificate as the root CA in /pki
pemBundleRootCA := string(cluster.CACertPEM) + string(cluster.CAKeyPEM)
_, err = client.Logical().Write("pki/config/ca", map[string]interface{}{
"pem_bundle": pemBundleRootCA,
})
if err != nil {
t.Fatal(err)
}
// Mount /pki2 to operate as an intermediate CA
err = client.Sys().Mount("pki2", &api.MountInput{
Type: "pki",
Config: api.MountConfigInput{
DefaultLeaseTTL: "16h",
MaxLeaseTTL: "32h",
},
})
if err != nil {
t.Fatal(err)
}
// Create a CSR for the intermediate CA
secret, err := client.Logical().Write("pki2/intermediate/generate/internal", nil)
if err != nil {
t.Fatal(err)
}
intermediateCSR := secret.Data["csr"].(string)
// Sign the intermediate CSR using /pki
secret, err = client.Logical().Write("pki/root/sign-intermediate", map[string]interface{}{
"permitted_dns_domains": ".myvault.com",
"csr": intermediateCSR,
})
if err != nil {
t.Fatal(err)
}
intermediateCertPEM := secret.Data["certificate"].(string)
// Configure the intermediate cert as the CA in /pki2
_, err = client.Logical().Write("pki2/intermediate/set-signed", map[string]interface{}{
"certificate": intermediateCertPEM,
})
if err != nil {
t.Fatal(err)
}
// Create a role on the intermediate CA mount
_, err = client.Logical().Write("pki2/roles/myvault-dot-com", map[string]interface{}{
"allowed_domains": "myvault.com",
"allow_subdomains": "true",
"max_ttl": "5m",
})
if err != nil {
t.Fatal(err)
}
// Issue a leaf cert using the intermediate CA
secret, err = client.Logical().Write("pki2/issue/myvault-dot-com", map[string]interface{}{
"common_name": "cert.myvault.com",
"format": "pem",
"ip_sans": "127.0.0.1",
})
if err != nil {
t.Fatal(err)
}
leafCertPEM := secret.Data["certificate"].(string)
leafCertKeyPEM := secret.Data["private_key"].(string)
// Enable the cert auth method
err = client.Sys().EnableAuthWithOptions("cert", &api.EnableAuthOptions{
Type: "cert",
})
if err != nil {
t.Fatal(err)
}
// Set the intermediate CA cert as a trusted certificate in the backend
_, err = client.Logical().Write("auth/cert/certs/myvault-dot-com", map[string]interface{}{
"display_name": "myvault.com",
"policies": "default",
"certificate": intermediateCertPEM,
})
if err != nil {
t.Fatal(err)
}
// Create temporary files for CA cert, client cert and client cert key.
// This is used to configure TLS in the api client.
caCertFile, err := ioutil.TempFile("", "caCert")
if err != nil {
t.Fatal(err)
}
defer os.Remove(caCertFile.Name())
if _, err := caCertFile.Write([]byte(cluster.CACertPEM)); err != nil {
t.Fatal(err)
}
if err := caCertFile.Close(); err != nil {
t.Fatal(err)
}
leafCertFile, err := ioutil.TempFile("", "leafCert")
if err != nil {
t.Fatal(err)
}
defer os.Remove(leafCertFile.Name())
if _, err := leafCertFile.Write([]byte(leafCertPEM)); err != nil {
t.Fatal(err)
}
if err := leafCertFile.Close(); err != nil {
t.Fatal(err)
}
leafCertKeyFile, err := ioutil.TempFile("", "leafCertKey")
if err != nil {
t.Fatal(err)
}
defer os.Remove(leafCertKeyFile.Name())
if _, err := leafCertKeyFile.Write([]byte(leafCertKeyPEM)); err != nil {
t.Fatal(err)
}
if err := leafCertKeyFile.Close(); err != nil {
t.Fatal(err)
}
// This function is a copy-pasta from the NewTestCluster, with the
// modification to reconfigure the TLS on the api client with the leaf
// certificate generated above.
getAPIClient := func(port int, tlsConfig *tls.Config) *api.Client {
transport := cleanhttp.DefaultPooledTransport()
transport.TLSClientConfig = tlsConfig.Clone()
if err := http2.ConfigureTransport(transport); err != nil {
t.Fatal(err)
}
client := &http.Client{
Transport: transport,
CheckRedirect: func(*http.Request, []*http.Request) error {
// This can of course be overridden per-test by using its own client
return fmt.Errorf("redirects not allowed in these tests")
},
}
config := api.DefaultConfig()
if config.Error != nil {
t.Fatal(config.Error)
}
config.Address = fmt.Sprintf("https://127.0.0.1:%d", port)
config.HttpClient = client
// Set the above issued certificates as the client certificates
config.ConfigureTLS(&api.TLSConfig{
CACert: caCertFile.Name(),
ClientCert: leafCertFile.Name(),
ClientKey: leafCertKeyFile.Name(),
})
apiClient, err := api.NewClient(config)
if err != nil {
t.Fatal(err)
}
return apiClient
}
// Create a new api client with the desired TLS configuration
newClient := getAPIClient(cores[0].Listeners[0].Address.Port, cores[0].TLSConfig)
// Set the intermediate CA cert as a trusted certificate in the backend
secret, err = newClient.Logical().Write("auth/cert/login", map[string]interface{}{
"name": "myvault-dot-com",
})
if err != nil {
t.Fatal(err)
}
if secret.Auth == nil || secret.Auth.ClientToken == "" {
t.Fatalf("expected a successful authentication")
}
}
func TestBackend_NonCAExpiry(t *testing.T) {
var resp *logical.Response
var err error
// Create a self-signed certificate and issue a leaf certificate using the
// CA cert
template := &x509.Certificate{
SerialNumber: big.NewInt(1234),
Subject: pkix.Name{
CommonName: "localhost",
Organization: []string{"hashicorp"},
OrganizationalUnit: []string{"vault"},
},
BasicConstraintsValid: true,
NotBefore: time.Now().Add(-30 * time.Second),
NotAfter: time.Now().Add(50 * time.Second),
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
KeyUsage: x509.KeyUsage(x509.KeyUsageCertSign | x509.KeyUsageCRLSign),
}
// Set IP SAN
parsedIP := net.ParseIP("127.0.0.1")
if parsedIP == nil {
t.Fatalf("failed to create parsed IP")
}
template.IPAddresses = []net.IP{parsedIP}
// Private key for CA cert
caPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatal(err)
}
// Marshalling to be able to create PEM file
caPrivateKeyBytes := x509.MarshalPKCS1PrivateKey(caPrivateKey)
caPublicKey := &caPrivateKey.PublicKey
template.IsCA = true
caCertBytes, err := x509.CreateCertificate(rand.Reader, template, template, caPublicKey, caPrivateKey)
if err != nil {
t.Fatal(err)
}
caCert, err := x509.ParseCertificate(caCertBytes)
if err != nil {
t.Fatal(err)
}
parsedCaBundle := &certutil.ParsedCertBundle{
Certificate: caCert,
CertificateBytes: caCertBytes,
PrivateKeyBytes: caPrivateKeyBytes,
PrivateKeyType: certutil.RSAPrivateKey,
}
caCertBundle, err := parsedCaBundle.ToCertBundle()
if err != nil {
t.Fatal(err)
}
caCertFile, err := ioutil.TempFile("", "caCert")
if err != nil {
t.Fatal(err)
}
defer os.Remove(caCertFile.Name())
if _, err := caCertFile.Write([]byte(caCertBundle.Certificate)); err != nil {
t.Fatal(err)
}
if err := caCertFile.Close(); err != nil {
t.Fatal(err)
}
caKeyFile, err := ioutil.TempFile("", "caKey")
if err != nil {
t.Fatal(err)
}
defer os.Remove(caKeyFile.Name())
if _, err := caKeyFile.Write([]byte(caCertBundle.PrivateKey)); err != nil {
t.Fatal(err)
}
if err := caKeyFile.Close(); err != nil {
t.Fatal(err)
}
// Prepare template for non-CA cert
template.IsCA = false
template.SerialNumber = big.NewInt(5678)
template.KeyUsage = x509.KeyUsage(x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign)
issuedPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatal(err)
}
issuedPrivateKeyBytes := x509.MarshalPKCS1PrivateKey(issuedPrivateKey)
issuedPublicKey := &issuedPrivateKey.PublicKey
// Keep a short certificate lifetime so logins can be tested both when
// cert is valid and when it gets expired
template.NotBefore = time.Now().Add(-2 * time.Second)
template.NotAfter = time.Now().Add(3 * time.Second)
issuedCertBytes, err := x509.CreateCertificate(rand.Reader, template, caCert, issuedPublicKey, caPrivateKey)
if err != nil {
t.Fatal(err)
}
issuedCert, err := x509.ParseCertificate(issuedCertBytes)
if err != nil {
t.Fatal(err)
}
parsedIssuedBundle := &certutil.ParsedCertBundle{
Certificate: issuedCert,
CertificateBytes: issuedCertBytes,
PrivateKeyBytes: issuedPrivateKeyBytes,
PrivateKeyType: certutil.RSAPrivateKey,
}
issuedCertBundle, err := parsedIssuedBundle.ToCertBundle()
if err != nil {
t.Fatal(err)
}
issuedCertFile, err := ioutil.TempFile("", "issuedCert")
if err != nil {
t.Fatal(err)
}
defer os.Remove(issuedCertFile.Name())
if _, err := issuedCertFile.Write([]byte(issuedCertBundle.Certificate)); err != nil {
t.Fatal(err)
}
if err := issuedCertFile.Close(); err != nil {
t.Fatal(err)
}
issuedKeyFile, err := ioutil.TempFile("", "issuedKey")
if err != nil {
t.Fatal(err)
}
defer os.Remove(issuedKeyFile.Name())
if _, err := issuedKeyFile.Write([]byte(issuedCertBundle.PrivateKey)); err != nil {
t.Fatal(err)
}
if err := issuedKeyFile.Close(); err != nil {
t.Fatal(err)
}
config := logical.TestBackendConfig()
storage := &logical.InmemStorage{}
config.StorageView = storage
b, err := Factory(context.Background(), config)
if err != nil {
t.Fatal(err)
}
// Register the Non-CA certificate of the client key pair
certData := map[string]interface{}{
"certificate": issuedCertBundle.Certificate,
"policies": "abc",
"display_name": "cert1",
"ttl": 10000,
}
certReq := &logical.Request{
Operation: logical.UpdateOperation,
Path: "certs/cert1",
Storage: storage,
Data: certData,
}
resp, err = b.HandleRequest(context.Background(), certReq)
if err != nil || (resp != nil && resp.IsError()) {
t.Fatalf("err:%v resp:%#v", err, resp)
}
// Create connection state using the certificates generated
connState, err := connectionState(caCertFile.Name(), caCertFile.Name(), caKeyFile.Name(), issuedCertFile.Name(), issuedKeyFile.Name())
if err != nil {
t.Fatalf("error testing connection state:%v", err)
}
loginReq := &logical.Request{
Operation: logical.UpdateOperation,
Storage: storage,
Path: "login",
Connection: &logical.Connection{
ConnState: &connState,
},
}
// Login when the certificate is still valid. Login should succeed.
resp, err = b.HandleRequest(context.Background(), loginReq)
if err != nil || (resp != nil && resp.IsError()) {
t.Fatalf("err:%v resp:%#v", err, resp)
}
// Wait until the certificate expires
time.Sleep(5 * time.Second)
// Login attempt after certificate expiry should fail
resp, err = b.HandleRequest(context.Background(), loginReq)
if err == nil {
t.Fatalf("expected error due to expired certificate")
}
}
func TestBackend_RegisteredNonCA_CRL(t *testing.T) {
config := logical.TestBackendConfig()
storage := &logical.InmemStorage{}
config.StorageView = storage
b, err := Factory(context.Background(), config)
if err != nil {
t.Fatal(err)
}
nonCACert, err := ioutil.ReadFile(testCertPath1)
if err != nil {
t.Fatal(err)
}
// Register the Non-CA certificate of the client key pair
certData := map[string]interface{}{
"certificate": nonCACert,
"policies": "abc",
"display_name": "cert1",
"ttl": 10000,
}
certReq := &logical.Request{
Operation: logical.UpdateOperation,
Path: "certs/cert1",
Storage: storage,
Data: certData,
}
resp, err := b.HandleRequest(context.Background(), certReq)
if err != nil || (resp != nil && resp.IsError()) {
t.Fatalf("err:%v resp:%#v", err, resp)
}
// Connection state is presenting the client Non-CA cert and its key.
// This is exactly what is registered at the backend.
connState, err := connectionState(serverCAPath, serverCertPath, serverKeyPath, testCertPath1, testKeyPath1)
if err != nil {
t.Fatalf("error testing connection state:%v", err)
}
loginReq := &logical.Request{
Operation: logical.UpdateOperation,
Storage: storage,
Path: "login",
Connection: &logical.Connection{
ConnState: &connState,
},
}
// Login should succeed.
resp, err = b.HandleRequest(context.Background(), loginReq)
if err != nil || (resp != nil && resp.IsError()) {
t.Fatalf("err:%v resp:%#v", err, resp)
}
// Register a CRL containing the issued client certificate used above.
issuedCRL, err := ioutil.ReadFile(testIssuedCertCRL)
if err != nil {
t.Fatal(err)
}
crlData := map[string]interface{}{
"crl": issuedCRL,
}
crlReq := &logical.Request{
Operation: logical.UpdateOperation,
Storage: storage,
Path: "crls/issuedcrl",
Data: crlData,
}
resp, err = b.HandleRequest(context.Background(), crlReq)
if err != nil || (resp != nil && resp.IsError()) {
t.Fatalf("err:%v resp:%#v", err, resp)
}
// Attempt login with the same connection state but with the CRL registered
resp, err = b.HandleRequest(context.Background(), loginReq)
if err != nil {
t.Fatal(err)
}
if resp == nil || !resp.IsError() {
t.Fatalf("expected failure due to revoked certificate")
}
}
func TestBackend_CRLs(t *testing.T) {
config := logical.TestBackendConfig()
storage := &logical.InmemStorage{}
config.StorageView = storage
b, err := Factory(context.Background(), config)
if err != nil {
t.Fatal(err)
}
clientCA1, err := ioutil.ReadFile(testRootCACertPath1)
if err != nil {
t.Fatal(err)
}
// Register the CA certificate of the client key pair
certData := map[string]interface{}{
"certificate": clientCA1,
"policies": "abc",
"display_name": "cert1",
"ttl": 10000,
}
certReq := &logical.Request{
Operation: logical.UpdateOperation,
Path: "certs/cert1",
Storage: storage,
Data: certData,
}
resp, err := b.HandleRequest(context.Background(), certReq)
if err != nil || (resp != nil && resp.IsError()) {
t.Fatalf("err:%v resp:%#v", err, resp)
}
// Connection state is presenting the client CA cert and its key.
// This is exactly what is registered at the backend.
connState, err := connectionState(serverCAPath, serverCertPath, serverKeyPath, testRootCACertPath1, testRootCAKeyPath1)
if err != nil {
t.Fatalf("error testing connection state:%v", err)
}
loginReq := &logical.Request{
Operation: logical.UpdateOperation,
Storage: storage,
Path: "login",
Connection: &logical.Connection{
ConnState: &connState,
},
}
resp, err = b.HandleRequest(context.Background(), loginReq)
if err != nil || (resp != nil && resp.IsError()) {
t.Fatalf("err:%v resp:%#v", err, resp)
}
// Now, without changing the registered client CA cert, present from
// the client side, a cert issued using the registered CA.
connState, err = connectionState(serverCAPath, serverCertPath, serverKeyPath, testCertPath1, testKeyPath1)
if err != nil {
t.Fatalf("error testing connection state: %v", err)
}
loginReq.Connection.ConnState = &connState
// Attempt login with the updated connection
resp, err = b.HandleRequest(context.Background(), loginReq)
if err != nil || (resp != nil && resp.IsError()) {
t.Fatalf("err:%v resp:%#v", err, resp)
}
// Register a CRL containing the issued client certificate used above.
issuedCRL, err := ioutil.ReadFile(testIssuedCertCRL)
if err != nil {
t.Fatal(err)
}
crlData := map[string]interface{}{
"crl": issuedCRL,
}
crlReq := &logical.Request{
Operation: logical.UpdateOperation,
Storage: storage,
Path: "crls/issuedcrl",
Data: crlData,
}
resp, err = b.HandleRequest(context.Background(), crlReq)
if err != nil || (resp != nil && resp.IsError()) {
t.Fatalf("err:%v resp:%#v", err, resp)
}
// Attempt login with the revoked certificate.
resp, err = b.HandleRequest(context.Background(), loginReq)
if err != nil {
t.Fatal(err)
}
if resp == nil || !resp.IsError() {
t.Fatalf("expected failure due to revoked certificate")
}
// Register a different client CA certificate.
clientCA2, err := ioutil.ReadFile(testRootCACertPath2)
if err != nil {
t.Fatal(err)
}
certData["certificate"] = clientCA2
resp, err = b.HandleRequest(context.Background(), certReq)
if err != nil || (resp != nil && resp.IsError()) {
t.Fatalf("err:%v resp:%#v", err, resp)
}
// Test login using a different client CA cert pair.
connState, err = connectionState(serverCAPath, serverCertPath, serverKeyPath, testRootCACertPath2, testRootCAKeyPath2)
if err != nil {
t.Fatalf("error testing connection state: %v", err)
}
loginReq.Connection.ConnState = &connState
// Attempt login with the updated connection
resp, err = b.HandleRequest(context.Background(), loginReq)
if err != nil || (resp != nil && resp.IsError()) {
t.Fatalf("err:%v resp:%#v", err, resp)
}
// Register a CRL containing the root CA certificate used above.
rootCRL, err := ioutil.ReadFile(testRootCertCRL)
if err != nil {
t.Fatal(err)
}
crlData["crl"] = rootCRL
resp, err = b.HandleRequest(context.Background(), crlReq)
if err != nil || (resp != nil && resp.IsError()) {
t.Fatalf("err:%v resp:%#v", err, resp)
}
// Attempt login with the same connection state but with the CRL registered
resp, err = b.HandleRequest(context.Background(), loginReq)
if err != nil {
t.Fatal(err)
}
if resp == nil || !resp.IsError() {
t.Fatalf("expected failure due to revoked certificate")
}
}
func testFactory(t *testing.T) logical.Backend {
b, err := Factory(context.Background(), &logical.BackendConfig{
System: &logical.StaticSystemView{
DefaultLeaseTTLVal: 1000 * time.Second,
MaxLeaseTTLVal: 1800 * time.Second,
},
StorageView: &logical.InmemStorage{},
})
if err != nil {
t.Fatalf("error: %s", err)
}
return b
}
// Test the certificates being registered to the backend
func TestBackend_CertWrites(t *testing.T) {
// CA cert
ca1, err := ioutil.ReadFile("test-fixtures/root/rootcacert.pem")
if err != nil {
t.Fatalf("err: %v", err)
}
// Non CA Cert
ca2, err := ioutil.ReadFile("test-fixtures/keys/cert.pem")
if err != nil {
t.Fatalf("err: %v", err)
}
// Non CA cert without TLS web client authentication
ca3, err := ioutil.ReadFile("test-fixtures/noclientauthcert.pem")
if err != nil {
t.Fatalf("err: %v", err)
}
tc := logicaltest.TestCase{
Backend: testFactory(t),
Steps: []logicaltest.TestStep{
testAccStepCert(t, "aaa", ca1, "foo", allowed{}, false),
testAccStepCert(t, "bbb", ca2, "foo", allowed{}, false),
testAccStepCert(t, "ccc", ca3, "foo", allowed{}, true),
},
}
tc.Steps = append(tc.Steps, testAccStepListCerts(t, []string{"aaa", "bbb"})...)
logicaltest.Test(t, tc)
}
// Test a client trusted by a CA
func TestBackend_basic_CA(t *testing.T) {
connState, err := testConnState("test-fixtures/keys/cert.pem",
"test-fixtures/keys/key.pem", "test-fixtures/root/rootcacert.pem")
if err != nil {
t.Fatalf("error testing connection state: %v", err)
}
ca, err := ioutil.ReadFile("test-fixtures/root/rootcacert.pem")
if err != nil {
t.Fatalf("err: %v", err)
}
logicaltest.Test(t, logicaltest.TestCase{
Backend: testFactory(t),
Steps: []logicaltest.TestStep{
testAccStepCert(t, "web", ca, "foo", allowed{}, false),
testAccStepLogin(t, connState),
testAccStepCertLease(t, "web", ca, "foo"),
testAccStepCertTTL(t, "web", ca, "foo"),
testAccStepLogin(t, connState),
testAccStepCertMaxTTL(t, "web", ca, "foo"),
testAccStepLogin(t, connState),
testAccStepCertNoLease(t, "web", ca, "foo"),
testAccStepLoginDefaultLease(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{names: "*.example.com"}, false),
testAccStepLogin(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{names: "*.invalid.com"}, false),
testAccStepLoginInvalid(t, connState),
},
})
}
// Test CRL behavior
func TestBackend_Basic_CRLs(t *testing.T) {
connState, err := testConnState("test-fixtures/keys/cert.pem",
"test-fixtures/keys/key.pem", "test-fixtures/root/rootcacert.pem")
if err != nil {
t.Fatalf("error testing connection state: %v", err)
}
ca, err := ioutil.ReadFile("test-fixtures/root/rootcacert.pem")
if err != nil {
t.Fatalf("err: %v", err)
}
crl, err := ioutil.ReadFile("test-fixtures/root/root.crl")
if err != nil {
t.Fatalf("err: %v", err)
}
logicaltest.Test(t, logicaltest.TestCase{
Backend: testFactory(t),
Steps: []logicaltest.TestStep{
testAccStepCertNoLease(t, "web", ca, "foo"),
testAccStepLoginDefaultLease(t, connState),
testAccStepAddCRL(t, crl, connState),
testAccStepReadCRL(t, connState),
testAccStepLoginInvalid(t, connState),
testAccStepDeleteCRL(t, connState),
testAccStepLoginDefaultLease(t, connState),
},
})
}
// Test a self-signed client (root CA) that is trusted
func TestBackend_basic_singleCert(t *testing.T) {
connState, err := testConnState("test-fixtures/root/rootcacert.pem",
"test-fixtures/root/rootcakey.pem", "test-fixtures/root/rootcacert.pem")
if err != nil {
t.Fatalf("error testing connection state: %v", err)
}
ca, err := ioutil.ReadFile("test-fixtures/root/rootcacert.pem")
if err != nil {
t.Fatalf("err: %v", err)
}
logicaltest.Test(t, logicaltest.TestCase{
Backend: testFactory(t),
Steps: []logicaltest.TestStep{
testAccStepCert(t, "web", ca, "foo", allowed{}, false),
testAccStepLogin(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{names: "example.com"}, false),
testAccStepLogin(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{names: "invalid"}, false),
testAccStepLoginInvalid(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{ext: "1.2.3.4:invalid"}, false),
testAccStepLoginInvalid(t, connState),
},
})
}
func TestBackend_common_name_singleCert(t *testing.T) {
connState, err := testConnState("test-fixtures/root/rootcacert.pem",
"test-fixtures/root/rootcakey.pem", "test-fixtures/root/rootcacert.pem")
if err != nil {
t.Fatalf("error testing connection state: %v", err)
}
ca, err := ioutil.ReadFile("test-fixtures/root/rootcacert.pem")
if err != nil {
t.Fatalf("err: %v", err)
}
logicaltest.Test(t, logicaltest.TestCase{
Backend: testFactory(t),
Steps: []logicaltest.TestStep{
testAccStepCert(t, "web", ca, "foo", allowed{}, false),
testAccStepLogin(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{common_names: "example.com"}, false),
testAccStepLogin(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{common_names: "invalid"}, false),
testAccStepLoginInvalid(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{ext: "1.2.3.4:invalid"}, false),
testAccStepLoginInvalid(t, connState),
},
})
}
// Test a self-signed client with custom ext (root CA) that is trusted
func TestBackend_ext_singleCert(t *testing.T) {
connState, err := testConnState(
"test-fixtures/root/rootcawextcert.pem",
"test-fixtures/root/rootcawextkey.pem",
"test-fixtures/root/rootcacert.pem",
)
if err != nil {
t.Fatalf("error testing connection state: %v", err)
}
ca, err := ioutil.ReadFile("test-fixtures/root/rootcacert.pem")
if err != nil {
t.Fatalf("err: %v", err)
}
logicaltest.Test(t, logicaltest.TestCase{
Backend: testFactory(t),
Steps: []logicaltest.TestStep{
testAccStepCert(t, "web", ca, "foo", allowed{ext: "2.1.1.1:A UTF8String Extension"}, false),
testAccStepLogin(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{ext: "2.1.1.1:*,2.1.1.2:A UTF8*"}, false),
testAccStepLogin(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{ext: "1.2.3.45:*"}, false),
testAccStepLoginInvalid(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{ext: "2.1.1.1:The Wrong Value"}, false),
testAccStepLoginInvalid(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{ext: "2.1.1.1:*,2.1.1.2:The Wrong Value"}, false),
testAccStepLoginInvalid(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{ext: "2.1.1.1:"}, false),
testAccStepLoginInvalid(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{ext: "2.1.1.1:,2.1.1.2:*"}, false),
testAccStepLoginInvalid(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{names: "example.com", ext: "2.1.1.1:A UTF8String Extension"}, false),
testAccStepLogin(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{names: "example.com", ext: "2.1.1.1:*,2.1.1.2:A UTF8*"}, false),
testAccStepLogin(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{names: "example.com", ext: "1.2.3.45:*"}, false),
testAccStepLoginInvalid(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{names: "example.com", ext: "2.1.1.1:The Wrong Value"}, false),
testAccStepLoginInvalid(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{names: "example.com", ext: "2.1.1.1:*,2.1.1.2:The Wrong Value"}, false),
testAccStepLoginInvalid(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{names: "invalid", ext: "2.1.1.1:A UTF8String Extension"}, false),
testAccStepLoginInvalid(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{names: "invalid", ext: "2.1.1.1:*,2.1.1.2:A UTF8*"}, false),
testAccStepLoginInvalid(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{names: "invalid", ext: "1.2.3.45:*"}, false),
testAccStepLoginInvalid(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{names: "invalid", ext: "2.1.1.1:The Wrong Value"}, false),
testAccStepLoginInvalid(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{names: "invalid", ext: "2.1.1.1:*,2.1.1.2:The Wrong Value"}, false),
testAccStepLoginInvalid(t, connState),
},
})
}
// Test a self-signed client with URI alt names (root CA) that is trusted
func TestBackend_dns_singleCert(t *testing.T) {
connState, err := testConnState(
"test-fixtures/root/rootcawdnscert.pem",
"test-fixtures/root/rootcawdnskey.pem",
"test-fixtures/root/rootcacert.pem",
)
if err != nil {
t.Fatalf("error testing connection state: %v", err)
}
ca, err := ioutil.ReadFile("test-fixtures/root/rootcacert.pem")
if err != nil {
t.Fatalf("err: %v", err)
}
logicaltest.Test(t, logicaltest.TestCase{
Backend: testFactory(t),
Steps: []logicaltest.TestStep{
testAccStepCert(t, "web", ca, "foo", allowed{dns: "example.com"}, false),
testAccStepLogin(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{dns: "*ample.com"}, false),
testAccStepLogin(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{dns: "notincert.com"}, false),
testAccStepLoginInvalid(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{dns: "abc"}, false),
testAccStepLoginInvalid(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{dns: "*.example.com"}, false),
testAccStepLoginInvalid(t, connState),
},
})
}
// Test a self-signed client with URI alt names (root CA) that is trusted
func TestBackend_email_singleCert(t *testing.T) {
connState, err := testConnState(
"test-fixtures/root/rootcawemailcert.pem",
"test-fixtures/root/rootcawemailkey.pem",
"test-fixtures/root/rootcacert.pem",
)
if err != nil {
t.Fatalf("error testing connection state: %v", err)
}
ca, err := ioutil.ReadFile("test-fixtures/root/rootcacert.pem")
if err != nil {
t.Fatalf("err: %v", err)
}
logicaltest.Test(t, logicaltest.TestCase{
Backend: testFactory(t),
Steps: []logicaltest.TestStep{
testAccStepCert(t, "web", ca, "foo", allowed{emails: "valid@example.com"}, false),
testAccStepLogin(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{emails: "*@example.com"}, false),
testAccStepLogin(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{emails: "invalid@notincert.com"}, false),
testAccStepLoginInvalid(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{emails: "abc"}, false),
testAccStepLoginInvalid(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{emails: "*.example.com"}, false),
testAccStepLoginInvalid(t, connState),
},
})
}
// Test a self-signed client with URI alt names (root CA) that is trusted
func TestBackend_uri_singleCert(t *testing.T) {
connState, err := testConnState(
"test-fixtures/root/rootcawuricert.pem",
"test-fixtures/root/rootcawurikey.pem",
"test-fixtures/root/rootcacert.pem",
)
if err != nil {
t.Fatalf("error testing connection state: %v", err)
}
ca, err := ioutil.ReadFile("test-fixtures/root/rootcacert.pem")
if err != nil {
t.Fatalf("err: %v", err)
}
logicaltest.Test(t, logicaltest.TestCase{
Backend: testFactory(t),
Steps: []logicaltest.TestStep{
testAccStepCert(t, "web", ca, "foo", allowed{uris: "spiffe://example.com/*"}, false),
testAccStepLogin(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{uris: "spiffe://example.com/host"}, false),
testAccStepLogin(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{uris: "spiffe://example.com/invalid"}, false),
testAccStepLoginInvalid(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{uris: "abc"}, false),
testAccStepLoginInvalid(t, connState),
testAccStepCert(t, "web", ca, "foo", allowed{uris: "http://www.google.com"}, false),
testAccStepLoginInvalid(t, connState),
},
})
}
// Test against a collection of matching and non-matching rules
func TestBackend_mixed_constraints(t *testing.T) {
connState, err := testConnState("test-fixtures/keys/cert.pem",
"test-fixtures/keys/key.pem", "test-fixtures/root/rootcacert.pem")
if err != nil {
t.Fatalf("error testing connection state: %v", err)
}
ca, err := ioutil.ReadFile("test-fixtures/root/rootcacert.pem")
if err != nil {
t.Fatalf("err: %v", err)
}
logicaltest.Test(t, logicaltest.TestCase{
Backend: testFactory(t),
Steps: []logicaltest.TestStep{
testAccStepCert(t, "1unconstrained", ca, "foo", allowed{}, false),
testAccStepCert(t, "2matching", ca, "foo", allowed{names: "*.example.com,whatever"}, false),
testAccStepCert(t, "3invalid", ca, "foo", allowed{names: "invalid"}, false),
testAccStepLogin(t, connState),
// Assumes CertEntries are processed in alphabetical order (due to store.List), so we only match 2matching if 1unconstrained doesn't match
testAccStepLoginWithName(t, connState, "2matching"),
testAccStepLoginWithNameInvalid(t, connState, "3invalid"),
},
})
}
// Test an untrusted client
func TestBackend_untrusted(t *testing.T) {
connState, err := testConnState("test-fixtures/keys/cert.pem",
"test-fixtures/keys/key.pem", "test-fixtures/root/rootcacert.pem")
if err != nil {
t.Fatalf("error testing connection state: %v", err)
}
logicaltest.Test(t, logicaltest.TestCase{
Backend: testFactory(t),
Steps: []logicaltest.TestStep{
testAccStepLoginInvalid(t, connState),
},
})
}
func TestBackend_validCIDR(t *testing.T) {
config := logical.TestBackendConfig()
storage := &logical.InmemStorage{}
config.StorageView = storage
b, err := Factory(context.Background(), config)
if err != nil {
t.Fatal(err)
}
connState, err := testConnState("test-fixtures/keys/cert.pem",
"test-fixtures/keys/key.pem", "test-fixtures/root/rootcacert.pem")
if err != nil {
t.Fatalf("error testing connection state: %v", err)
}
ca, err := ioutil.ReadFile("test-fixtures/root/rootcacert.pem")
if err != nil {
t.Fatalf("err: %v", err)
}
name := "web"
addCertReq := &logical.Request{
Operation: logical.UpdateOperation,
Path: "certs/" + name,
Data: map[string]interface{}{
"certificate": string(ca),
"policies": "foo",
"display_name": name,
"allowed_names": "",
"required_extensions": "",
"lease": 1000,
"bound_cidrs": []string{"127.0.0.1/32", "128.252.0.0/16"},
},
Storage: storage,
Connection: &logical.Connection{ConnState: &connState},
}
_, err = b.HandleRequest(context.Background(), addCertReq)
if err != nil {
t.Fatal(err)
}
loginReq := &logical.Request{
Operation: logical.UpdateOperation,
Path: "login",
Unauthenticated: true,
Data: map[string]interface{}{
"name": name,
},
Storage: storage,
Connection: &logical.Connection{ConnState: &connState},
}
// override the remote address with an IPV4 that is authorized
loginReq.Connection.RemoteAddr = "127.0.0.1/32"
_, err = b.HandleRequest(context.Background(), loginReq)
if err != nil {
t.Fatal(err.Error())
}
}
func TestBackend_invalidCIDR(t *testing.T) {
config := logical.TestBackendConfig()
storage := &logical.InmemStorage{}
config.StorageView = storage
b, err := Factory(context.Background(), config)
if err != nil {
t.Fatal(err)
}
connState, err := testConnState("test-fixtures/keys/cert.pem",
"test-fixtures/keys/key.pem", "test-fixtures/root/rootcacert.pem")
if err != nil {
t.Fatalf("error testing connection state: %v", err)
}
ca, err := ioutil.ReadFile("test-fixtures/root/rootcacert.pem")
if err != nil {
t.Fatalf("err: %v", err)
}
name := "web"
addCertReq := &logical.Request{
Operation: logical.UpdateOperation,
Path: "certs/" + name,
Data: map[string]interface{}{
"certificate": string(ca),
"policies": "foo",
"display_name": name,
"allowed_names": "",
"required_extensions": "",
"lease": 1000,
"bound_cidrs": []string{"127.0.0.1/32", "128.252.0.0/16"},
},
Storage: storage,
Connection: &logical.Connection{ConnState: &connState},
}
_, err = b.HandleRequest(context.Background(), addCertReq)
if err != nil {
t.Fatal(err)
}
loginReq := &logical.Request{
Operation: logical.UpdateOperation,
Path: "login",
Unauthenticated: true,
Data: map[string]interface{}{
"name": name,
},
Storage: storage,
Connection: &logical.Connection{ConnState: &connState},
}
// override the remote address with an IPV4 that isn't authorized
loginReq.Connection.RemoteAddr = "127.0.0.1/8"
_, err = b.HandleRequest(context.Background(), loginReq)
if err == nil {
t.Fatal("expected \"ERROR: permission denied\"")
}
}
func testAccStepAddCRL(t *testing.T, crl []byte, connState tls.ConnectionState) logicaltest.TestStep {
return logicaltest.TestStep{
Operation: logical.UpdateOperation,
Path: "crls/test",
ConnState: &connState,
Data: map[string]interface{}{
"crl": crl,
},
}
}
func testAccStepReadCRL(t *testing.T, connState tls.ConnectionState) logicaltest.TestStep {
return logicaltest.TestStep{
Operation: logical.ReadOperation,
Path: "crls/test",
ConnState: &connState,
Check: func(resp *logical.Response) error {
crlInfo := CRLInfo{}
err := mapstructure.Decode(resp.Data, &crlInfo)
if err != nil {
t.Fatalf("err: %v", err)
}
if len(crlInfo.Serials) != 1 {
t.Fatalf("bad: expected CRL with length 1, got %d", len(crlInfo.Serials))
}
if _, ok := crlInfo.Serials["637101449987587619778072672905061040630001617053"]; !ok {
t.Fatalf("bad: expected serial number not found in CRL")
}
return nil
},
}
}
func testAccStepDeleteCRL(t *testing.T, connState tls.ConnectionState) logicaltest.TestStep {
return logicaltest.TestStep{
Operation: logical.DeleteOperation,
Path: "crls/test",
ConnState: &connState,
}
}
func testAccStepLogin(t *testing.T, connState tls.ConnectionState) logicaltest.TestStep {
return testAccStepLoginWithName(t, connState, "")
}
func testAccStepLoginWithName(t *testing.T, connState tls.ConnectionState, certName string) logicaltest.TestStep {
return logicaltest.TestStep{
Operation: logical.UpdateOperation,
Path: "login",
Unauthenticated: true,
ConnState: &connState,
Check: func(resp *logical.Response) error {
if resp.Auth.TTL != 1000*time.Second {
t.Fatalf("bad lease length: %#v", resp.Auth)
}
if certName != "" && resp.Auth.DisplayName != ("mnt-"+certName) {
t.Fatalf("matched the wrong cert: %#v", resp.Auth.DisplayName)
}
fn := logicaltest.TestCheckAuth([]string{"default", "foo"})
return fn(resp)
},
Data: map[string]interface{}{
"name": certName,
},
}
}
func testAccStepLoginDefaultLease(t *testing.T, connState tls.ConnectionState) logicaltest.TestStep {
return logicaltest.TestStep{
Operation: logical.UpdateOperation,
Path: "login",
Unauthenticated: true,
ConnState: &connState,
Check: func(resp *logical.Response) error {
if resp.Auth.TTL != 1000*time.Second {
t.Fatalf("bad lease length: %#v", resp.Auth)
}
fn := logicaltest.TestCheckAuth([]string{"default", "foo"})
return fn(resp)
},
}
}
func testAccStepLoginInvalid(t *testing.T, connState tls.ConnectionState) logicaltest.TestStep {
return testAccStepLoginWithNameInvalid(t, connState, "")
}
func testAccStepLoginWithNameInvalid(t *testing.T, connState tls.ConnectionState, certName string) logicaltest.TestStep {
return logicaltest.TestStep{
Operation: logical.UpdateOperation,
Path: "login",
Unauthenticated: true,
ConnState: &connState,
Check: func(resp *logical.Response) error {
if resp.Auth != nil {
return fmt.Errorf("should not be authorized: %#v", resp)
}
return nil
},
Data: map[string]interface{}{
"name": certName,
},
ErrorOk: true,
}
}
func testAccStepListCerts(
t *testing.T, certs []string) []logicaltest.TestStep {
return []logicaltest.TestStep{
logicaltest.TestStep{
Operation: logical.ListOperation,
Path: "certs",
Check: func(resp *logical.Response) error {
if resp == nil {
return fmt.Errorf("nil response")
}
if resp.Data == nil {
return fmt.Errorf("nil data")
}
if resp.Data["keys"] == interface{}(nil) {
return fmt.Errorf("nil keys")
}
keys := resp.Data["keys"].([]string)
if !reflect.DeepEqual(keys, certs) {
return fmt.Errorf("mismatch: keys is %#v, certs is %#v", keys, certs)
}
return nil
},
}, logicaltest.TestStep{
Operation: logical.ListOperation,
Path: "certs/",
Check: func(resp *logical.Response) error {
if resp == nil {
return fmt.Errorf("nil response")
}
if resp.Data == nil {
return fmt.Errorf("nil data")
}
if resp.Data["keys"] == interface{}(nil) {
return fmt.Errorf("nil keys")
}
keys := resp.Data["keys"].([]string)
if !reflect.DeepEqual(keys, certs) {
return fmt.Errorf("mismatch: keys is %#v, certs is %#v", keys, certs)
}
return nil
},
},
}
}
type allowed struct {
names string // allowed names in the certificate, looks at common, name, dns, email [depricated]
common_names string // allowed common names in the certificate
dns string // allowed dns names in the SAN extension of the certificate
emails string // allowed email names in SAN extension of the certificate
uris string // allowed uris in SAN extension of the certificate
ext string // required extensions in the certificate
}
func testAccStepCert(
t *testing.T, name string, cert []byte, policies string, testData allowed, expectError bool) logicaltest.TestStep {
return logicaltest.TestStep{
Operation: logical.UpdateOperation,
Path: "certs/" + name,
ErrorOk: expectError,
Data: map[string]interface{}{
"certificate": string(cert),
"policies": policies,
"display_name": name,
"allowed_names": testData.names,
"allowed_common_names": testData.common_names,
"allowed_dns_sans": testData.dns,
"allowed_email_sans": testData.emails,
"allowed_uri_sans": testData.uris,
"required_extensions": testData.ext,
"lease": 1000,
},
Check: func(resp *logical.Response) error {
if resp == nil && expectError {
return fmt.Errorf("expected error but received nil")
}
return nil
},
}
}
func testAccStepCertLease(
t *testing.T, name string, cert []byte, policies string) logicaltest.TestStep {
return logicaltest.TestStep{
Operation: logical.UpdateOperation,
Path: "certs/" + name,
Data: map[string]interface{}{
"certificate": string(cert),
"policies": policies,
"display_name": name,
"lease": 1000,
},
}
}
func testAccStepCertTTL(
t *testing.T, name string, cert []byte, policies string) logicaltest.TestStep {
return logicaltest.TestStep{
Operation: logical.UpdateOperation,
Path: "certs/" + name,
Data: map[string]interface{}{
"certificate": string(cert),
"policies": policies,
"display_name": name,
"ttl": "1000s",
},
}
}
func testAccStepCertMaxTTL(
t *testing.T, name string, cert []byte, policies string) logicaltest.TestStep {
return logicaltest.TestStep{
Operation: logical.UpdateOperation,
Path: "certs/" + name,
Data: map[string]interface{}{
"certificate": string(cert),
"policies": policies,
"display_name": name,
"ttl": "1000s",
"max_ttl": "1200s",
},
}
}
func testAccStepCertNoLease(
t *testing.T, name string, cert []byte, policies string) logicaltest.TestStep {
return logicaltest.TestStep{
Operation: logical.UpdateOperation,
Path: "certs/" + name,
Data: map[string]interface{}{
"certificate": string(cert),
"policies": policies,
"display_name": name,
},
}
}
func testConnState(certPath, keyPath, rootCertPath string) (tls.ConnectionState, error) {
cert, err := tls.LoadX509KeyPair(certPath, keyPath)
if err != nil {
return tls.ConnectionState{}, err
}
rootConfig := &rootcerts.Config{
CAFile: rootCertPath,
}
rootCAs, err := rootcerts.LoadCACerts(rootConfig)
if err != nil {
return tls.ConnectionState{}, err
}
listenConf := &tls.Config{
Certificates: []tls.Certificate{cert},
ClientAuth: tls.RequestClientCert,
InsecureSkipVerify: false,
RootCAs: rootCAs,
}
dialConf := listenConf.Clone()
// start a server
list, err := tls.Listen("tcp", "127.0.0.1:0", listenConf)
if err != nil {
return tls.ConnectionState{}, err
}
defer list.Close()
// Accept connections.
serverErrors := make(chan error, 1)
connState := make(chan tls.ConnectionState)
go func() {
defer close(connState)
serverConn, err := list.Accept()
serverErrors <- err
if err != nil {
close(serverErrors)
return
}
defer serverConn.Close()
// Read the ping
buf := make([]byte, 4)
_, err = serverConn.Read(buf)
if (err != nil) && (err != io.EOF) {
serverErrors <- err
close(serverErrors)
return
} else {
// EOF is a reasonable error condition, so swallow it.
serverErrors <- nil
}
close(serverErrors)
connState <- serverConn.(*tls.Conn).ConnectionState()
}()
// Establish a connection from the client side and write a few bytes.
clientErrors := make(chan error, 1)
go func() {
addr := list.Addr().String()
conn, err := tls.Dial("tcp", addr, dialConf)
clientErrors <- err
if err != nil {
close(clientErrors)
return
}
defer conn.Close()
// Write ping
_, err = conn.Write([]byte("ping"))
clientErrors <- err
close(clientErrors)
}()
for err = range clientErrors {
if err != nil {
return tls.ConnectionState{}, fmt.Errorf("error in client goroutine:%v", err)
}
}
for err = range serverErrors {
if err != nil {
return tls.ConnectionState{}, fmt.Errorf("error in server goroutine:%v", err)
}
}
// Grab the current state
return <-connState, nil
}
func Test_Renew(t *testing.T) {
storage := &logical.InmemStorage{}
lb, err := Factory(context.Background(), &logical.BackendConfig{
System: &logical.StaticSystemView{
DefaultLeaseTTLVal: 300 * time.Second,
MaxLeaseTTLVal: 1800 * time.Second,
},
StorageView: storage,
})
if err != nil {
t.Fatalf("error: %s", err)
}
b := lb.(*backend)
connState, err := testConnState("test-fixtures/keys/cert.pem",
"test-fixtures/keys/key.pem", "test-fixtures/root/rootcacert.pem")
if err != nil {
t.Fatalf("error testing connection state: %v", err)
}
ca, err := ioutil.ReadFile("test-fixtures/root/rootcacert.pem")
if err != nil {
t.Fatal(err)
}
req := &logical.Request{
Connection: &logical.Connection{
ConnState: &connState,
},
Storage: storage,
Auth: &logical.Auth{},
}
fd := &framework.FieldData{
Raw: map[string]interface{}{
"name": "test",
"certificate": ca,
"policies": "foo,bar",
},
Schema: pathCerts(b).Fields,
}
resp, err := b.pathCertWrite(context.Background(), req, fd)
if err != nil {
t.Fatal(err)
}
empty_login_fd := &framework.FieldData{
Raw: map[string]interface{}{},
Schema: pathLogin(b).Fields,
}
resp, err = b.pathLogin(context.Background(), req, empty_login_fd)
if err != nil {
t.Fatal(err)
}
if resp.IsError() {
t.Fatalf("got error: %#v", *resp)
}
req.Auth.InternalData = resp.Auth.InternalData
req.Auth.Metadata = resp.Auth.Metadata
req.Auth.LeaseOptions = resp.Auth.LeaseOptions
req.Auth.Policies = resp.Auth.Policies
req.Auth.Period = resp.Auth.Period
// Normal renewal
resp, err = b.pathLoginRenew(context.Background(), req, empty_login_fd)
if err != nil {
t.Fatal(err)
}
if resp == nil {
t.Fatal("got nil response from renew")
}
if resp.IsError() {
t.Fatalf("got error: %#v", *resp)
}
// Change the policies -- this should fail
fd.Raw["policies"] = "zip,zap"
resp, err = b.pathCertWrite(context.Background(), req, fd)
if err != nil {
t.Fatal(err)
}
resp, err = b.pathLoginRenew(context.Background(), req, empty_login_fd)
if err == nil {
t.Fatal("expected error")
}
// Put the policies back, this should be okay
fd.Raw["policies"] = "bar,foo"
resp, err = b.pathCertWrite(context.Background(), req, fd)
if err != nil {
t.Fatal(err)
}
resp, err = b.pathLoginRenew(context.Background(), req, empty_login_fd)
if err != nil {
t.Fatal(err)
}
if resp == nil {
t.Fatal("got nil response from renew")
}
if resp.IsError() {
t.Fatalf("got error: %#v", *resp)
}
// Add period value to cert entry
period := 350 * time.Second
fd.Raw["period"] = period.String()
resp, err = b.pathCertWrite(context.Background(), req, fd)
if err != nil {
t.Fatal(err)
}
resp, err = b.pathLoginRenew(context.Background(), req, empty_login_fd)
if err != nil {
t.Fatal(err)
}
if resp == nil {
t.Fatal("got nil response from renew")
}
if resp.IsError() {
t.Fatalf("got error: %#v", *resp)
}
if resp.Auth.Period != period {
t.Fatalf("expected a period value of %s in the response, got: %s", period, resp.Auth.Period)
}
// Delete CA, make sure we can't renew
resp, err = b.pathCertDelete(context.Background(), req, fd)
if err != nil {
t.Fatal(err)
}
resp, err = b.pathLoginRenew(context.Background(), req, empty_login_fd)
if err != nil {
t.Fatal(err)
}
if resp == nil {
t.Fatal("got nil response from renew")
}
if !resp.IsError() {
t.Fatal("expected error")
}
}
|
Aloomaio/vault
|
builtin/credential/cert/backend_test.go
|
GO
|
mpl-2.0
| 51,798
|
importScripts('sw-helpers.js');
async function getFetchResult(record) {
response = await record.responseReady;
if (!response)
return Promise.resolve(null);
return {
url: response.url,
status: response.status,
text: await response.text(),
};
}
self.addEventListener('backgroundfetchsuccess', event => {
event.waitUntil(
event.registration.matchAll()
.then(records => Promise.all(records.map(record => getFetchResult(record))))
.then(results => {
const registrationCopy = cloneRegistration(event.registration);
sendMessageToDocument({ type: event.type, eventRegistration: registrationCopy, results })
}));
});
|
SimonSapin/servo
|
tests/wpt/web-platform-tests/background-fetch/service_workers/sw.js
|
JavaScript
|
mpl-2.0
| 676
|
initSidebarItems({"fn":[["DefineDOMInterface",""],["GetProtoObject",""],["Wrap",""]],"mod":[["FileReaderConstants",""]],"static":[["sNativePropertyHooks",""]],"trait":[["FileReaderMethods",""]]});
|
susaing/doc.servo.org
|
servo/script/dom/bindings/codegen/Bindings/FileReaderBinding/sidebar-items.js
|
JavaScript
|
mpl-2.0
| 196
|
package userpass
import (
"fmt"
"reflect"
"testing"
"github.com/hashicorp/vault/api"
"github.com/hashicorp/vault/sdk/helper/policyutil"
"github.com/hashicorp/vault/sdk/testing/stepwise"
dockerEnvironment "github.com/hashicorp/vault/sdk/testing/stepwise/environments/docker"
"github.com/mitchellh/mapstructure"
)
func TestAccBackend_stepwise_UserCrud(t *testing.T) {
customPluginName := "my-userpass"
envOptions := &stepwise.MountOptions{
RegistryName: customPluginName,
PluginType: stepwise.PluginTypeCredential,
PluginName: "userpass",
MountPathPrefix: customPluginName,
}
stepwise.Run(t, stepwise.Case{
Environment: dockerEnvironment.NewEnvironment(customPluginName, envOptions),
Steps: []stepwise.Step{
testAccStepwiseUser(t, "web", "password", "foo"),
testAccStepwiseReadUser(t, "web", "foo"),
testAccStepwiseDeleteUser(t, "web"),
testAccStepwiseReadUser(t, "web", ""),
},
})
}
func testAccStepwiseUser(
t *testing.T, name string, password string, policies string) stepwise.Step {
return stepwise.Step{
Operation: stepwise.UpdateOperation,
Path: "users/" + name,
Data: map[string]interface{}{
"password": password,
"policies": policies,
},
}
}
func testAccStepwiseDeleteUser(t *testing.T, name string) stepwise.Step {
return stepwise.Step{
Operation: stepwise.DeleteOperation,
Path: "users/" + name,
}
}
func testAccStepwiseReadUser(t *testing.T, name string, policies string) stepwise.Step {
return stepwise.Step{
Operation: stepwise.ReadOperation,
Path: "users/" + name,
Assert: func(resp *api.Secret, err error) error {
if resp == nil {
if policies == "" {
return nil
}
return fmt.Errorf("unexpected nil response")
}
var d struct {
Policies []string `mapstructure:"policies"`
}
if err := mapstructure.Decode(resp.Data, &d); err != nil {
return err
}
expectedPolicies := policyutil.ParsePolicies(policies)
if !reflect.DeepEqual(d.Policies, expectedPolicies) {
return fmt.Errorf("Actual policies: %#v\nExpected policies: %#v", d.Policies, expectedPolicies)
}
return nil
},
}
}
|
hartsock/vault
|
builtin/credential/userpass/stepwise_test.go
|
GO
|
mpl-2.0
| 2,151
|
---
layout: "docs"
page_title: "Auth Backend: Token"
sidebar_current: "docs-auth-token"
description: |-
The token store auth backend is used to authenticate using tokens.
---
# Auth Backend: Token
The token backend is the only auth backend that is built-in and
automatically available at `/auth/token` as well as with first-class
built-in CLI methods such as `vault token-create`. It allows users to
authenticate using a token, as well to create new tokens, revoke
secrets by token, and more.
When any other auth backend returns an identity, Vault core invokes the
token backend to create a new unique token for that identity.
The token store can also be used to bypass any other auth backend:
you can create tokens directly, as well as perform a variety of other
operations on tokens such as renewal and revocation.
Please see the [token concepts](/docs/concepts/tokens.html) page dedicated
to tokens.
## Authentication
#### Via the CLI
```
$ vault auth <token>
...
```
#### Via the API
The token is set directly as a header for the HTTP API. The name
of the header should be "X-Vault-Token" and the value should be the token.
## API
### /auth/token/create
### /auth/token/create-orphan
### /auth/token/create/[role_name]
#### POST
<dl class="api">
<dt>Description</dt>
<dd>
Creates a new token. Certain options are only available when called by a
root token. If used via the `/auth/token/create-orphan` endpoint, a root
token is not required to create an orphan token (otherwise set with the
`no_parent` option). If used with a role name in the path, the token will
be created against the specified role name; this may override options set
during this call.
</dd>
<dt>Method</dt>
<dd>POST</dd>
<dt>URLs</dt>
<dd>`/auth/token/create`</dd>
<dd>`/auth/token/create-orphan`</dd>
<dd>`/auth/token/create/<role_name>`</dd>
<dt>Parameters</dt>
<dd>
<ul>
<li>
<span class="param">id</span>
<span class="param-flags">optional</span>
The ID of the client token. Can only be specified by a root token.
Otherwise, the token ID is a randomly generated UUID.
</li>
<li>
<span class="param">policies</span>
<span class="param-flags">optional</span>
A list of policies for the token. This must be a subset of the
policies belonging to the token making the request, unless root.
If not specified, defaults to all the policies of the calling token.
</li>
<li>
<span class="param">meta</span>
<span class="param-flags">optional</span>
A map of string to string valued metadata. This is passed through
to the audit backends.
</li>
<li>
<span class="param">no_parent</span>
<span class="param-flags">optional</span>
If true and set by a root caller, the token will not have the
parent token of the caller. This creates a token with no parent.
</li>
<li>
<span class="param">no_default_policy</span>
<span class="param-flags">optional</span>
If true the `default` policy will not be a part of this token's
policy set.
</li>
<li>
<span class="param">lease</span>
<span class="param-flags">optional</span>
DEPRECATED; use "ttl" instead.
</li>
<li>
<span class="param">ttl</span>
<span class="param-flags">optional</span>
The TTL period of the token, provided as "1h", where hour is
the largest suffix. If not provided, the token is valid for the
[default lease TTL](/docs/config/index.html), or
indefinitely if the root policy is used.
</li>
<li>
<span class="param">display_name</span>
<span class="param-flags">optional</span>
The display name of the token. Defaults to "token".
</li>
<li>
<span class="param">num_uses</span>
<span class="param-flags">optional</span>
The maximum uses for the given token. This can be used to create
a one-time-token or limited use token. Defaults to 0, which has
no limit to the number of uses.
</li>
</ul>
</dd>
<dt>Returns</dt>
<dd>
```javascript
{
"auth": {
"client_token": "ABCD",
"policies": ["web", "stage"],
"metadata": {"user": "armon"},
"lease_duration": 3600,
"renewable": true,
}
}
```
</dd>
</dl>
### /auth/token/lookup-self
#### GET
<dl class="api">
<dt>Description</dt>
<dd>
Returns information about the current client token.
</dd>
<dt>Method</dt>
<dd>GET</dd>
<dt>Parameters</dt>
<dd>
None
</dd>
<dt>Returns</dt>
<dd>
```javascript
{
"data": {
"id": "ClientToken",
"policies": ["web", "stage"],
"path": "auth/github/login",
"meta": {"user": "armon", "organization": "hashicorp"},
"display_name": "github-armon",
"num_uses": 0,
}
}
```
</dd>
</dl>
### /auth/token/lookup[/token]
#### GET
<dl class="api">
<dt>Description</dt>
<dd>
Returns information about the client token provided in the request path.
</dd>
<dt>Method</dt>
<dd>GET</dd>
<dt>URL</dt>
<dd>`/auth/token/lookup/<token>`</dd>
<dt>Parameters</dt>
<dd>
None
</dd>
<dt>Returns</dt>
<dd>
```javascript
{
"data": {
"id": "ClientToken",
"policies": ["web", "stage"],
"path": "auth/github/login",
"meta": {"user": "armon", "organization": "hashicorp"},
"display_name": "github-armon",
"num_uses": 0,
}
}
```
</dd>
</dl>
#### POST
<dl class="api">
<dt>Description</dt>
<dd>
Returns information about the client token provided in the request body.
</dd>
<dt>Method</dt>
<dd>GET</dd>
<dt>URL</dt>
<dd>`/auth/token/lookup`</dd>
<dt>Parameters</dt>
<dd>
<ul>
<li>
<span class="param">token</span>
<span class="param-flags">required</span>
Token to lookup.
</li>
</ul>
</dd>
<dt>Returns</dt>
<dd>
```javascript
{
"data": {
"id": "ClientToken",
"policies": ["web", "stage"],
"path": "auth/github/login",
"meta": {"user": "armon", "organization": "hashicorp"},
"display_name": "github-armon",
"num_uses": 0,
}
}
```
</dd>
</dl>
### /auth/token/renew-self
#### POST
<dl class="api">
<dt>Description</dt>
<dd>
Renews a lease associated with the calling token. This is used to prevent
the expiration of a token, and the automatic revocation of it. Token
renewal is possible only if there is a lease associated with it.
</dd>
<dt>Method</dt>
<dd>POST</dd>
<dt>URL</dt>
<dd>`/auth/token/renew-self`</dd>
<dt>Parameters</dt>
<dd>
<ul>
<li>
<span class="param">increment</span>
<span class="param-flags">optional</span>
An optional requested lease increment can be provided. This
increment may be ignored.
</li>
</ul>
</dd>
<dt>Returns</dt>
<dd>
```javascript
{
"auth": {
"client_token": "ABCD",
"policies": ["web", "stage"],
"metadata": {"user": "armon"},
"lease_duration": 3600,
"renewable": true,
}
}
```
</dd>
</dl>
### /auth/token/renew[/token]
#### POST
<dl class="api">
<dt>Description</dt>
<dd>
Renews a lease associated with a token. This is used to prevent the
expiration of a token, and the automatic revocation of it. Token
renewal is possible only if there is a lease associated with it.
</dd>
<dt>Method</dt>
<dd>POST</dd>
<dt>URL</dt>
<dd>`/auth/token/renew</token>`</dd>
<dt>Parameters</dt>
<dd>
<ul>
<li>
<span class="param">token</span>
<span class="param-flags">required</span>
Token to revoke. This can be part of the URL or the body.
</li>
</ul>
</dd>
<dd>
<ul>
<li>
<span class="param">increment</span>
<span class="param-flags">optional</span>
An optional requested lease increment can be provided. This
increment may be ignored.
</li>
</ul>
</dd>
<dt>Returns</dt>
<dd>
```javascript
{
"auth": {
"client_token": "ABCD",
"policies": ["web", "stage"],
"metadata": {"user": "armon"},
"lease_duration": 3600,
"renewable": true,
}
}
```
</dd>
</dl>
### /auth/token/revoke[/token]
#### POST
<dl class="api">
<dt>Description</dt>
<dd>
Revokes a token and all child tokens. When the token is revoked,
all secrets generated with it are also revoked.
</dd>
<dt>Method</dt>
<dd>POST</dd>
<dt>URL</dt>
<dd>`/auth/token/revoke</token>`</dd>
<dt>Parameters</dt>
<dd>
<ul>
<li>
<span class="param">token</span>
<span class="param-flags">required</span>
Token to revoke. This can be part of the URL or the body.
</li>
</ul>
</dd>
<dt>Returns</dt>
<dd>`204` response code.
</dd>
</dl>
### /auth/token/revoke-self/
#### POST
<dl class="api">
<dt>Description</dt>
<dd>
Revokes the token used to call it and all child tokens.
When the token is revoked, all secrets generated with
it are also revoked.
</dd>
<dt>Method</dt>
<dd>POST</dd>
<dt>URL</dt>
<dd>`/auth/token/revoke-self`</dd>
<dt>Parameters</dt>
<dd>
None
</dd>
<dt>Returns</dt>
<dd>`204` response code.
</dd>
</dl>
### /auth/token/revoke-orphan[/token]
#### POST
<dl class="api">
<dt>Description</dt>
<dd>
Revokes a token but not its child tokens. When the token is revoked, all
secrets generated with it are also revoked. All child tokens are orphaned,
but can be revoked sub-sequently using `/auth/token/revoke/`. This is a
root-protected endpoint.
</dd>
<dt>Method</dt>
<dd>POST</dd>
<dt>URL</dt>
<dd>`/auth/token/revoke-orphan</token>`</dd>
<dt>Parameters</dt>
<dd>
<ul>
<li>
<span class="param">token</span>
<span class="param-flags">required</span>
Token to revoke. This can be part of the URL or the body.
</li>
</ul>
</dd>
<dt>Returns</dt>
<dd>`204` response code.
</dd>
</dl>
### /auth/token/roles/[role_name]
#### DELETE
<dl class="api">
<dt>Description</dt>
<dd>
Deletes the named role.
</dd>
<dt>Method</dt>
<dd>GET</dd>
<dt>URL</dt>
<dd>`/auth/token/roles/<role_name>`</dd>
<dt>Parameters</dt>
<dd>
None
</dd>
<dt>Returns</dt>
<dd>
A `204` response code.
</dd>
</dl>
#### GET
<dl class="api">
<dt>Description</dt>
<dd>
Fetches the named role configuration.
</dd>
<dt>Method</dt>
<dd>GET</dd>
<dt>URL</dt>
<dd>`/auth/token/roles/<role_name>`</dd>
<dt>Parameters</dt>
<dd>
None
</dd>
<dt>Returns</dt>
<dd>
```javascript
{
"data": {
"period": 3600,
"allowed_policies": ["web", "stage"],
"orphan": true,
"path_suffix": ""
}
}
```
</dd>
</dl>
#### LIST
<dl class="api">
<dt>Description</dt>
<dd>
Lists available roles.
</dd>
<dt>Method</dt>
<dd>GET</dd>
<dt>URL</dt>
<dd>`/auth/token/roles?list=true`<dd>
<dt>Parameters</dt>
<dd>
None
</dd>
<dt>Returns</dt>
<dd>
```javascript
{
"data": {
"keys": ["role1", "role2"]
}
}
```
</dd>
</dl>
#### POST
<dl class="api">
<dt>Description</dt>
<dd>
Creates (or replaces) the named role. Roles enforce specific behavior when
creating tokens that allow token functionality that is otherwise not
available or would require `sudo`/root privileges to access. Role
parameters, when set, override any provided options to the `create`
endpoints. The role name is also included in the token path, allowing all
tokens created against a role to be revoked using the `sys/revoke-prefix`
endpoint.
</dd>
<dt>Method</dt>
<dd>POST</dd>
<dt>URL</dt>
<dd>`/auth/token/roles/<role_name>`</dd>
<dt>Parameters</dt>
<dd>
<ul>
<li>
<span class="param">allowed_policies</span>
<span class="param-flags">optional</span>
If set, tokens can be created with any subset of the policies in this
list, rather than the normal semantics of tokens being a subset of the
calling token's policies. The parameter is a comma-delimited string of
policy names.
</li>
<li>
<span class="param">orphan</span>
<span class="param-flags">optional</span>
If `true`, tokens created against this policy will be orphan tokens
(they will have no parent). As such, they will not be automatically
revoked by the revocation of any other token.
</li>
<li>
<span class="param">period</span>
<span class="param-flags">optional</span>
If set, tokens created against this role will <i>not</i> have a maximum
lifetime. Instead, they will have a fixed TTL that is refreshed with
each renewal. So long as they continue to be renewed, they will never
expire. The parameter is an integer duration of seconds or a duration
string (e.g. `"72h"`).
</li>
<li>
<span class="param">path_suffix</span>
<span class="param-flags">optional</span>
If set, tokens created against this role will have the given suffix as
part of their path in addition to the role name. This can be useful in
certain scenarios, such as keeping the same role name in the future but
revoking all tokens created against it before some point in time. The
suffix can be changed, allowing new callers to have the new suffix as
part of their path, and then tokens with the old suffix can be revoked
via `sys/revoke-prefix`.
</li>
</ul>
</dd>
<dt>Returns</dt>
<dd>
A `204` return code.
</dd>
</dl>
### /auth/token/lookup-accessor[/accessor]
#### POST
<dl class="api">
<dt>Description</dt>
<dd>
Fetch the properties of the token associated with the accessor, except the token ID.
This is meant for purposes where there is no access to token ID but there is need
to fetch the properties of a token.
</dd>
<dt>Method</dt>
<dd>POST</dd>
<dt>URL</dt>
<dd>`/auth/token/lookup-accessor</accessor>`</dd>
<dt>Parameters</dt>
<dd>
<ul>
<li>
<span class="param">accessor</span>
<span class="param-flags">required</span>
Accessor of the token to lookup. This can be part of the URL or the body.
</li>
</ul>
</dd>
<dt>Returns</dt>
<dd>
```javascript
{
"lease_id": "",
"renewable": false,
"lease_duration": 0,
"data": {
"creation_time": 1457533232,
"creation_ttl": 2592000,
"display_name": "token",
"id": "",
"meta": null,
"num_uses": 0,
"orphan": false,
"path": "auth/token/create",
"policies": ["default", "web"],
"ttl": 2591976
},
"warnings": null,
"auth": null
}
```
</dd>
</dl>
### /auth/token/revoke-accessor[/accessor]
#### POST
<dl class="api">
<dt>Description</dt>
<dd>
Revoke the token associated with the accessor and all the child tokens.
This is meant for purposes where there is no access to token ID but
there is need to revoke a token and its children.
</dd>
<dt>Method</dt>
<dd>POST</dd>
<dt>URL</dt>
<dd>`/auth/token/revoke-accessor</accessor>`</dd>
<dt>Parameters</dt>
<dd>
<ul>
<li>
<span class="param">accessor</span>
<span class="param-flags">required</span>
Accessor of the token. This can be part of the URL or the body.
</li>
</ul>
</dd>
<dt>Returns</dt>
<dd>`204` response code.
</dd>
</dl>
|
doubledutch/vault
|
website/source/docs/auth/token.html.md
|
Markdown
|
mpl-2.0
| 15,966
|
# encoding: utf-8
#
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http:# mozilla.org/MPL/2.0/.
#
# Author: Kyle Lahnakoski (kyle@lahnakoski.com)
#
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from jx_base.expressions import Variable, DateOp, TupleOp, LeavesOp, BinaryOp, OrOp, InequalityOp, extend, Literal, NullOp, TrueOp, FalseOp, DivOp, FloorOp, \
NeOp, NotOp, LengthOp, NumberOp, StringOp, CountOp, MultiOp, RegExpOp, CoalesceOp, MissingOp, ExistsOp, \
PrefixOp, UnixOp, FromUnixOp, NotLeftOp, RightOp, NotRightOp, FindOp, InOp, RangeOp, CaseOp, AndOp, \
ConcatOp, LeftOp, EqOp, WhenOp, BasicIndexOfOp, IntegerOp, MaxOp, BasicSubstringOp, FALSE, MinOp, BooleanOp, SuffixOp, BetweenOp, simplified, ZERO, SqlInstrOp, SqlSubstrOp, NULL, ONE, builtin_ops, TRUE, SqlEqOp, BasicMultiOp
from jx_base.queries import get_property_name
from jx_sqlite import quoted_GUID, GUID
from mo_dots import coalesce, wrap, Null, split_field, listwrap, startswith_field
from mo_dots import join_field, ROOT_PATH, relative_field
from mo_future import text_type
from mo_json import json2value
from mo_json.typed_encoder import OBJECT, BOOLEAN, EXISTS, NESTED
from mo_logs import Log
from mo_math import Math
from pyLibrary import convert
from pyLibrary.sql import SQL, SQL_AND, SQL_EMPTY_STRING, SQL_OR, SQL_TRUE, SQL_ZERO, SQL_FALSE, SQL_NULL, SQL_ONE, SQL_IS_NOT_NULL, sql_list, sql_iso, SQL_IS_NULL, SQL_END, SQL_ELSE, SQL_THEN, SQL_WHEN, SQL_CASE, sql_concat, sql_coalesce
from pyLibrary.sql.sqlite import quote_column, quote_value
@extend(Variable)
def to_sql(self, schema, not_null=False, boolean=False):
if self.var == GUID:
return wrap([{"name": ".", "sql": {"s": quoted_GUID}, "nested_path": ROOT_PATH}])
vars = schema[self.var]
if not vars:
# DOES NOT EXIST
return wrap([{"name": ".", "sql": {"0": SQL_NULL}, "nested_path": ROOT_PATH}])
var_name = list(set(listwrap(vars).name))
if len(var_name) > 1:
Log.error("do not know how to handle")
var_name = var_name[0]
cols = schema.leaves(self.var)
acc = {}
if boolean:
for col in cols:
cname = relative_field(col.name, var_name)
nested_path = col.nested_path[0]
if col.type == OBJECT:
value = SQL_TRUE
elif col.type == BOOLEAN:
value = quote_column(col.es_column)
else:
value = quote_column(col.es_column) + SQL_IS_NOT_NULL
tempa = acc.setdefault(nested_path, {})
tempb = tempa.setdefault(get_property_name(cname), {})
tempb['b'] = value
else:
for col in cols:
cname = relative_field(col.name, var_name)
if col.type == OBJECT:
prefix = self.var + "."
for cn, cs in schema.items():
if cn.startswith(prefix):
for child_col in cs:
tempa = acc.setdefault(child_col.nested_path[0], {})
tempb = tempa.setdefault(get_property_name(cname), {})
tempb[json_type_to_sql_type[col.type]] = quote_column(child_col.es_column)
else:
nested_path = col.nested_path[0]
tempa = acc.setdefault(nested_path, {})
tempb = tempa.setdefault(get_property_name(cname), {})
tempb[json_type_to_sql_type[col.type]] = quote_column(col.es_column)
return wrap([
{"name": cname, "sql": types, "nested_path": nested_path}
for nested_path, pairs in acc.items() for cname, types in pairs.items()
])
@extend(Literal)
def to_sql(self, schema, not_null=False, boolean=False):
value = self.value
v = quote_value(value)
if v == None:
return wrap([{"name": "."}])
elif isinstance(value, text_type):
return wrap([{"name": ".", "sql": {"s": quote_value(value)}}])
elif Math.is_number(v):
return wrap([{"name": ".", "sql": {"n": quote_value(value)}}])
elif v in [True, False]:
return wrap([{"name": ".", "sql": {"b": quote_value(value)}}])
else:
return wrap([{"name": ".", "sql": {"j": quote_value(self.json)}}])
@extend(NullOp)
def to_sql(self, schema, not_null=False, boolean=False):
return Null
@extend(TrueOp)
def to_sql(self, schema, not_null=False, boolean=False):
return wrap([{"name": ".", "sql": {"b": SQL_TRUE}}])
@extend(FalseOp)
def to_sql(self, schema, not_null=False, boolean=False):
return wrap([{"name": ".", "sql": {"b": SQL_FALSE}}])
@extend(DateOp)
def to_sql(self, schema, not_null=False, boolean=False):
return wrap([{"name": ".", "sql": {"n": quote_value(self.value)}}])
@extend(TupleOp)
def to_sql(self, schema, not_null=False, boolean=False):
return wrap([{"name": ".", "sql": t.to_sql(schema)[0].sql} for t in self.terms])
@extend(LeavesOp)
def to_sql(self, schema, not_null=False, boolean=False):
if not isinstance(self.term, Variable):
Log.error("Can only handle Variable")
term = self.term.var
prefix_length = len(split_field(term))
output = wrap([
{
"name": join_field(split_field(schema.get_column_name(c))[prefix_length:]),
"sql": Variable(schema.get_column_name(c)).to_sql(schema)[0].sql
}
for c in schema.columns
if startswith_field(c.name, term) and (
(c.jx_type not in (EXISTS, OBJECT, NESTED) and startswith_field(schema.nested_path[0], c.nested_path[0])) or
(c.jx_type not in (EXISTS, OBJECT) and schema.nested_path[0] == c.nested_path[0])
)
])
return output
@extend(EqOp)
def to_sql(self, schema, not_null=False, boolean=False):
lhs = self.lhs.to_sql(schema)
rhs = self.rhs.to_sql(schema)
acc = []
if len(lhs) != len(rhs):
Log.error("lhs and rhs have different dimensionality!?")
for l, r in zip(lhs, rhs):
for t in "bsnj":
if l.sql[t] == None:
if r.sql[t] == None:
pass
else:
acc.append(sql_iso(r.sql[t]) + SQL_IS_NULL)
else:
if r.sql[t] == None:
acc.append(sql_iso(l.sql[t]) + SQL_IS_NULL)
else:
acc.append(sql_iso(l.sql[t]) + " = " + sql_iso(r.sql[t]))
if not acc:
return FALSE.to_sql(schema)
else:
return wrap([{"name": ".", "sql": {"b": SQL_OR.join(acc)}}])
@extend(EqOp)
@simplified
def partial_eval(self):
lhs = self.lhs.partial_eval()
rhs = self.rhs.partial_eval()
if isinstance(lhs, Literal) and isinstance(rhs, Literal):
return TRUE if builtin_ops["eq"](lhs.value, rhs.value) else FALSE
else:
rhs_missing = rhs.missing().partial_eval()
return CaseOp(
"case",
[
WhenOp("when", lhs.missing(), **{"then": rhs_missing}),
WhenOp("when", rhs_missing, **{"then": FALSE}),
SqlEqOp("eq", [lhs, rhs])
]
).partial_eval()
@extend(NeOp)
def to_sql(self, schema, not_null=False, boolean=False):
return NotOp('not', EqOp('eq', [self.lhs, self.rhs]).partial_eval()).partial_eval().to_sql(schema)
@extend(BasicIndexOfOp)
def to_sql(self, schema, not_null=False, boolean=False):
value = self.value.to_sql(schema)[0].sql.s
find = self.find.to_sql(schema)[0].sql.s
start = self.start
if isinstance(start, Literal) and start.value == 0:
return wrap([{"name": ".", "sql": {"n": "INSTR" + sql_iso(value + "," + find) + "-1"}}])
else:
start_index = start.to_sql(schema)[0].sql.n
found = "INSTR(SUBSTR" + sql_iso(value + "," + start_index + "+1)," + find)
return wrap([{"name": ".", "sql": {"n": (
SQL_CASE +
SQL_WHEN + found +
SQL_THEN + found + "+" + start_index + "-1" +
SQL_ELSE + "-1" +
SQL_END
)}}])
@extend(BasicSubstringOp)
def to_sql(self, schema, not_null=False, boolean=False):
value = self.value.to_sql(schema)[0].sql.s
start = MultiOp("add", [self.start, Literal(None, 1)]).partial_eval().to_sql(schema)[0].sql.n
length = BinaryOp("subtract", [self.end, self.start]).partial_eval().to_sql(schema)[0].sql.n
return wrap([{"name": ".", "sql": {"s": "SUBSTR" + sql_iso(value + "," + start + ", " + length)}}])
@extend(BinaryOp)
def to_sql(self, schema, not_null=False, boolean=False):
lhs = self.lhs.to_sql(schema)[0].sql.n
rhs = self.rhs.to_sql(schema)[0].sql.n
return wrap([{"name": ".", "sql": {"n": sql_iso(lhs) + " " + BinaryOp.operators[self.op] + " " + sql_iso(rhs)}}])
@extend(MinOp)
def to_sql(self, schema, not_null=False, boolean=False):
terms = [t.partial_eval().to_sql(schema)[0].sql.n for t in self.terms]
return wrap([{"name": ".", "sql": {"n": "min" + sql_iso((sql_list(terms)))}}])
@extend(MaxOp)
def to_sql(self, schema, not_null=False, boolean=False):
terms = [t.partial_eval().to_sql(schema)[0].sql.n for t in self.terms]
return wrap([{"name": ".", "sql": {"n": "max" + sql_iso((sql_list(terms)))}}])
@extend(InequalityOp)
def to_sql(self, schema, not_null=False, boolean=False):
lhs = self.lhs.to_sql(schema, not_null=True)[0].sql
rhs = self.rhs.to_sql(schema, not_null=True)[0].sql
lhs_exists = self.lhs.exists().to_sql(schema)[0].sql
rhs_exists = self.rhs.exists().to_sql(schema)[0].sql
if len(lhs) == 1 and len(rhs) == 1:
return wrap([{"name": ".", "sql": {
"b": sql_iso(lhs.values()[0]) + " " + InequalityOp.operators[self.op] + " " + sql_iso(rhs.values()[0])
}}])
ors = []
for l in "bns":
ll = lhs[l]
if not ll:
continue
for r in "bns":
rr = rhs[r]
if not rr:
continue
elif r == l:
ors.append(
sql_iso(lhs_exists[l]) + SQL_AND + sql_iso(rhs_exists[r]) + SQL_AND + sql_iso(lhs[l]) + " " +
InequalityOp.operators[self.op] + " " + sql_iso(rhs[r])
)
elif (l > r and self.op in ["gte", "gt"]) or (l < r and self.op in ["lte", "lt"]):
ors.append(
sql_iso(lhs_exists[l]) + SQL_AND + sql_iso(rhs_exists[r])
)
sql = sql_iso(SQL_OR.join(sql_iso(o) for o in ors))
return wrap([{"name": ".", "sql": {"b": sql}}])
@extend(DivOp)
def to_sql(self, schema, not_null=False, boolean=False):
lhs = self.lhs.to_sql(schema)[0].sql.n
rhs = self.rhs.to_sql(schema)[0].sql.n
d = self.default.to_sql(schema)[0].sql.n
if lhs and rhs:
if d == None:
return wrap([{
"name": ".",
"sql": {"n": sql_iso(lhs) + " / " + sql_iso(rhs)}
}])
else:
return wrap([{
"name": ".",
"sql": {"n": sql_coalesce([sql_iso(lhs) + " / " + sql_iso(rhs), d])}
}])
else:
return Null
@extend(FloorOp)
def to_sql(self, schema, not_null=False, boolean=False):
lhs = self.lhs.to_sql(schema)
rhs = self.rhs.to_sql(schema)
acc = []
if len(lhs) != len(rhs):
Log.error("lhs and rhs have different dimensionality!?")
for l, r in zip(lhs, rhs):
for t in "bsnj":
if l.sql[t] == None:
if r.sql[t] == None:
pass
else:
acc.append(sql_iso(r.sql[t]) + " IS " + SQL_NULL)
else:
if r.sql[t] == None:
acc.append(sql_iso(l.sql[t]) + " IS " + SQL_NULL)
else:
acc.append("(" + sql_iso(l.sql[t]) + " = " + sql_iso(r.sql[t]) + " OR (" + sql_iso(l.sql[t]) + " IS" + SQL_NULL + SQL_AND + "(" + r.sql[
t] + ") IS NULL))")
if not acc:
return FALSE.to_sql(schema)
else:
return wrap([{"name": ".", "sql": {"b": SQL_OR.join(acc)}}])
# @extend(NeOp)
# def to_sql(self, schema, not_null=False, boolean=False):
# return NotOp("not", EqOp("eq", [self.lhs, self.rhs])).to_sql(schema, not_null, boolean)
@extend(NotOp)
def to_sql(self, schema, not_null=False, boolean=False):
not_expr = NotOp("not", BooleanOp("boolean", self.term)).partial_eval()
if isinstance(not_expr, NotOp):
return wrap([{"name": ".", "sql": {"b": "NOT " + sql_iso(not_expr.term.to_sql(schema)[0].sql.b)}}])
else:
return not_expr.to_sql(schema)
@extend(BooleanOp)
def to_sql(self, schema, not_null=False, boolean=False):
term = self.term.partial_eval()
if term.type == "boolean":
sql = term.to_sql(schema)
return sql
else:
sql = term.exists().partial_eval().to_sql(schema)
return sql
@extend(AndOp)
def to_sql(self, schema, not_null=False, boolean=False):
if not self.terms:
return wrap([{"name": ".", "sql": {"b": SQL_TRUE}}])
elif all(self.terms):
return wrap([{"name": ".", "sql": {
"b": SQL_AND.join([sql_iso(t.to_sql(schema, boolean=True)[0].sql.b) for t in self.terms])
}}])
else:
return wrap([{"name": ".", "sql": {"b": SQL_FALSE}}])
@extend(OrOp)
def to_sql(self, schema, not_null=False, boolean=False):
return wrap([{
"name": ".",
"sql": {"b": SQL_OR.join(
sql_iso(t.to_sql(schema, boolean=True)[0].sql.b)
for t in self.terms
)}
}])
@extend(LengthOp)
def to_sql(self, schema, not_null=False, boolean=False):
term = self.term.partial_eval()
if isinstance(term, Literal):
val = term.value
if isinstance(val, text_type):
return wrap([{"name": ".", "sql": {"n": convert.value2json(len(val))}}])
elif isinstance(val, (float, int)):
return wrap([{"name": ".", "sql": {"n": convert.value2json(len(convert.value2json(val)))}}])
else:
return Null
value = term.to_sql(schema)[0].sql.s
return wrap([{"name": ".", "sql": {"n": "LENGTH" + sql_iso(value)}}])
@extend(IntegerOp)
def to_sql(self, schema, not_null=False, boolean=False):
value = self.term.to_sql(schema, not_null=True)
acc = []
for c in value:
for t, v in c.sql.items():
if t == "s":
acc.append("CAST(" + v + " as INTEGER)")
else:
acc.append(v)
if not acc:
return wrap([])
elif len(acc) == 1:
return wrap([{"name": ".", "sql": {"n": acc[0]}}])
else:
return wrap([{"name": ".", "sql": {"n": sql_coalesce(acc)}}])
@extend(NumberOp)
def to_sql(self, schema, not_null=False, boolean=False):
value = self.term.to_sql(schema, not_null=True)
acc = []
for c in value:
for t, v in c.sql.items():
if t == "s":
acc.append("CAST(" + v + " as FLOAT)")
else:
acc.append(v)
if not acc:
return wrap([])
elif len(acc) == 1:
return wrap([{"name": ".", "sql": {"n": acc}}])
else:
return wrap([{"name": ".", "sql": {"n": sql_coalesce(acc)}}])
@extend(StringOp)
def to_sql(self, schema, not_null=False, boolean=False):
test = self.term.missing().to_sql(schema, boolean=True)[0].sql.b
value = self.term.to_sql(schema, not_null=True)[0].sql
acc = []
for t, v in value.items():
if t == "b":
acc.append(SQL_CASE+SQL_WHEN + sql_iso(test) + SQL_THEN + SQL_NULL + SQL_WHEN + sql_iso(v) + SQL_THEN+"'true'"+SQL_ELSE+"'false'"+SQL_END)
elif t == "s":
acc.append(v)
else:
acc.append("RTRIM(RTRIM(CAST" + sql_iso(v + " as TEXT), " + quote_value('0')) + ", " + quote_value(".") + ")")
if not acc:
return wrap([{}])
elif len(acc) == 1:
return wrap([{"name": ".", "sql": {"s": acc[0]}}])
else:
return wrap([{"name": ".", "sql": {"s": sql_coalesce(acc)}}])
@extend(CountOp)
def to_sql(self, schema, not_null=False, boolean=False):
acc = []
for term in self.terms:
sqls = term.to_sql(schema)
if len(sqls) > 1:
acc.append(SQL_TRUE)
else:
for t, v in sqls[0].sql.items():
if t in ["b", "s", "n"]:
acc.append(SQL_CASE+SQL_WHEN + sql_iso(v) + SQL_IS_NULL + SQL_THEN+"0"+SQL_ELSE+"1"+SQL_END)
else:
acc.append(SQL_TRUE)
if not acc:
return wrap([{}])
else:
return wrap([{"nanme": ".", "sql": {"n": SQL("+").join(acc)}}])
_sql_operators = {
"add": (SQL(" + "), SQL_ZERO), # (operator, zero-array default value) PAIR
"basic.add": (SQL(" + "), SQL_ZERO), # (operator, zero-array default value) PAIR
"sum": (SQL(" + "), SQL_ZERO),
"mul": (SQL(" * "), SQL_ONE),
"mult": (SQL(" * "), SQL_ONE),
"multiply": (SQL(" * "), SQL_ONE),
"basic.mult": (SQL(" * "), SQL_ONE)
}
@extend(BasicMultiOp)
def to_sql(self, schema, not_null=False, boolean=False):
op, identity = _sql_operators[self.op]
sql = op.join(sql_iso(t.to_sql(schema)[0].sql.n) for t in self.terms)
return wrap([{"name": ".", "sql": {"n": sql}}])
@extend(RegExpOp)
def to_sql(self, schema, not_null=False, boolean=False):
pattern = quote_value(json2value(self.pattern.json))
value = self.var.to_sql(schema)[0].sql.s
return wrap([
{"name": ".", "sql": {"b": value + " REGEXP " + pattern}}
])
@extend(CoalesceOp)
def to_sql(self, schema, not_null=False, boolean=False):
acc = {
"b": [],
"s": [],
"n": []
}
for term in self.terms:
for t, v in term.to_sql(schema)[0].sql.items():
acc[t].append(v)
output = {}
for t, terms in acc.items():
if not terms:
continue
elif len(terms) == 1:
output[t] = terms[0]
else:
output[t] = sql_coalesce(terms)
return wrap([{"name": ".", "sql": output}])
@extend(MissingOp)
def to_sql(self, schema, not_null=False, boolean=False):
value = self.expr.partial_eval()
missing_value = value.missing().partial_eval()
if not isinstance(missing_value, MissingOp):
return missing_value.to_sql(schema)
value_sql = value.to_sql(schema)
if len(value_sql) > 1:
return wrap([{"name": ".", "sql": {"b": SQL_FALSE}}])
acc = []
for c in value_sql:
for t, v in c.sql.items():
if t == "b":
acc.append(sql_iso(v) + SQL_IS_NULL)
if t == "s":
acc.append(sql_iso(sql_iso(v) + SQL_IS_NULL) + SQL_OR + sql_iso(sql_iso(v) + "=" + SQL_EMPTY_STRING))
if t == "n":
acc.append(sql_iso(v) + SQL_IS_NULL)
if not acc:
return wrap([{"name": ".", "sql": {"b": SQL_TRUE}}])
else:
return wrap([{"name": ".", "sql": {"b": SQL_AND.join(acc)}}])
@extend(WhenOp)
def to_sql(self, schema, not_null=False, boolean=False):
when = self.when.partial_eval().to_sql(schema, boolean=True)[0].sql
then = self.then.partial_eval().to_sql(schema, not_null=not_null)[0].sql
els_ = self.els_.partial_eval().to_sql(schema, not_null=not_null)[0].sql
output = {}
for t in "bsn":
if then[t] == None:
if els_[t] == None:
pass
else:
output[t] = SQL_CASE+SQL_WHEN + when.b + SQL_THEN + SQL_NULL + SQL_ELSE + els_[t] + SQL_END
else:
if els_[t] == None:
output[t] = SQL_CASE+SQL_WHEN + when.b + SQL_THEN + then[t] + SQL_END
else:
output[t] = SQL_CASE+SQL_WHEN + when.b + SQL_THEN + then[t] + SQL_ELSE + els_[t] + SQL_END
if not output:
return wrap([{"name": ".", "sql": {"0": SQL_NULL}}])
else:
return wrap([{"name": ".", "sql": output}])
@extend(ExistsOp)
def to_sql(self, schema, not_null=False, boolean=False):
field = self.field.to_sql(schema)[0].sql
acc = []
for t, v in field.items():
if t in "bns":
acc.append(sql_iso(v + SQL_IS_NOT_NULL))
if not acc:
return wrap([{"name": ".", "sql": {"b": SQL_FALSE}}])
else:
return wrap([{"name": ".", "sql": {"b": SQL_OR.join(acc)}}])
@extend(PrefixOp)
def to_sql(self, schema, not_null=False, boolean=False):
if not self.expr:
return wrap([{"name": ".", "sql": {"b": SQL_TRUE}}])
else:
return wrap([{"name": ".", "sql": {
"b": "INSTR" + sql_iso(self.expr.to_sql(schema)[0].sql.s + ", " + self.prefix.to_sql(schema)[0].sql.s) + "==1"
}}])
@extend(SuffixOp)
def to_sql(self, schema, not_null=False, boolean=False):
if not self.expr:
return wrap([{"name": ".", "sql": {"b": SQL_FALSE}}])
elif isinstance(self.suffix, Literal) and not self.suffix.value:
return wrap([{"name": ".", "sql": {"b": SQL_TRUE}}])
else:
return EqOp(
"eq",
[
RightOp("right", [self.expr, LengthOp("length", self.suffix)]),
self.suffix
]
).partial_eval().to_sql(schema)
@extend(ConcatOp)
def to_sql(self, schema, not_null=False, boolean=False):
defult = self.default.to_sql(schema)
if len(self.terms) == 0:
return defult
defult = coalesce(defult[0].sql, SQL_NULL)
sep = self.separator.to_sql(schema)[0].sql.s
acc = []
for t in self.terms:
missing = t.missing().partial_eval()
term = t.to_sql(schema, not_null=True)[0].sql
if term.s:
term_sql = term.s
elif term.n:
term_sql = "cast(" + term.n + " as text)"
else:
term_sql = SQL_CASE + SQL_WHEN + term.b + SQL_THEN + quote_value("true") + SQL_ELSE + quote_value("false") + SQL_END
if isinstance(missing, TrueOp):
acc.append(SQL_EMPTY_STRING)
elif missing:
acc.append(
SQL_CASE +
SQL_WHEN + sql_iso(missing.to_sql(schema, boolean=True)[0].sql.b) +
SQL_THEN + SQL_EMPTY_STRING +
SQL_ELSE + sql_iso(sql_concat([sep, term_sql])) +
SQL_END
)
else:
acc.append(sql_concat([sep, term_sql]))
expr_ = "substr(" + sql_concat(acc) + ", " + LengthOp(None, self.separator).to_sql(schema)[0].sql.n + "+1)"
missing = self.missing()
if not missing:
return wrap([{"name": ".", "sql": {"s": expr_}}])
else:
return wrap([{
"name": ".",
"sql": {
"s": SQL_CASE+SQL_WHEN+"(" + missing.to_sql(schema, boolean=True)[0].sql.b +
")"+SQL_THEN+"(" + defult +
")"+SQL_ELSE+"(" + expr_ +
")"+SQL_END
}
}])
@extend(UnixOp)
def to_sql(self, schema, not_null=False, boolean=False):
v = self.value.to_sql(schema)[0].sql
return wrap([{
"name": ".",
"sql": {"n": "UNIX_TIMESTAMP" + sql_iso(v.n)}
}])
@extend(FromUnixOp)
def to_sql(self, schema, not_null=False, boolean=False):
v = self.value.to_sql(schema)[0].sql
return wrap([{
"name": ".",
"sql": {"n": "FROM_UNIXTIME" + sql_iso(v.n)}
}])
@extend(LeftOp)
def to_sql(self, schema, not_null=False, boolean=False):
return SqlSubstrOp(
"substr",
[
self.value,
ONE,
self.length
]
).partial_eval().to_sql(schema)
@extend(NotLeftOp)
def to_sql(self, schema, not_null=False, boolean=False):
# test_v = self.value.missing().to_sql(boolean=True)[0].sql.b
# test_l = self.length.missing().to_sql(boolean=True)[0].sql.b
v = self.value.to_sql(schema, not_null=True)[0].sql.s
l = "max(0, " + self.length.to_sql(schema, not_null=True)[0].sql.n + ")"
expr = "substr(" + v + ", " + l + "+1)"
return wrap([{"name": ".", "sql": {"s": expr}}])
@extend(RightOp)
def to_sql(self, schema, not_null=False, boolean=False):
v = self.value.to_sql(schema, not_null=True)[0].sql.s
r = self.length.to_sql(schema, not_null=True)[0].sql.n
l = "max(0, length" + sql_iso(v) + "-max(0, " + r + "))"
expr = "substr(" + v + ", " + l + "+1)"
return wrap([{"name": ".", "sql": {"s": expr}}])
@extend(RightOp)
@simplified
def partial_eval(self):
value = self.value.partial_eval()
length = self.length.partial_eval()
max_length = LengthOp("length", value)
return BasicSubstringOp("substring", [
value,
MaxOp("max", [ZERO, MinOp("min", [max_length, BinaryOp("sub", [max_length, length])])]),
max_length
])
@extend(NotRightOp)
def to_sql(self, schema, not_null=False, boolean=False):
v = self.value.to_sql(schema, not_null=True)[0].sql.s
r = self.length.to_sql(schema, not_null=True)[0].sql.n
l = "max(0, length" + sql_iso(v) + "-max(0, " + r + "))"
expr = "substr" + sql_iso(v + ", 1, " + l)
return wrap([{"name": ".", "sql": {"s": expr}}])
@extend(FindOp)
def to_sql(self, schema, not_null=False, boolean=False):
test = SqlInstrOp("substr", [
SqlSubstrOp("substr", [
self.value,
MultiOp("add", [self.start, ONE]),
NULL
]),
self.find
]).partial_eval()
if boolean:
return test.to_sql(schema)
else:
offset = BinaryOp("sub", [self.start, ONE]).partial_eval()
index = MultiOp("add", [test, offset]).partial_eval()
temp = index.to_sql(schema)
return WhenOp(
"when",
EqOp("eq", [test, ZERO]),
**{
"then": self.default,
"else": index
}
).partial_eval().to_sql(schema)
@extend(FindOp)
@simplified
def partial_eval(self):
return FindOp(
"find",
[
self.value.partial_eval(),
self.find.partial_eval()
],
**{
"start": self.start.partial_eval(),
"default": self.default.partial_eval()
}
)
@extend(BetweenOp)
def to_sql(self, schema, not_null=False, boolean=False):
return self.partial_eval().to_sql(schema)
@extend(InOp)
def to_sql(self, schema, not_null=False, boolean=False):
if not isinstance(self.superset, Literal):
Log.error("Not supported")
j_value = json2value(self.superset.json)
if j_value:
var = self.value.to_sql(schema)
return SQL_OR.join(sql_iso(var + "==" + quote_value(v)) for v in j_value)
else:
return wrap([{"name": ".", "sql": {"b": SQL_FALSE}}])
@extend(RangeOp)
def to_sql(self, schema, not_null=False, boolean=False):
when = self.when.to_sql(schema, boolean=True)[0].sql
then = self.then.to_sql(schema, not_null=not_null)[0].sql
els_ = self.els_.to_sql(schema, not_null=not_null)[0].sql
output = {}
for t in "bsn":
if then[t] == None:
if els_[t] == None:
pass
else:
output[t] = SQL_CASE+SQL_WHEN + when.b + SQL_THEN + SQL_NULL + SQL_ELSE + els_[t] + SQL_END
else:
if els_[t] == None:
output[t] = SQL_CASE+SQL_WHEN + when.b + SQL_THEN + then[t] + SQL_END
else:
output[t] = SQL_CASE+SQL_WHEN + when.b + SQL_THEN + then[t] + SQL_ELSE + els_[t] + SQL_END
if not output:
return wrap([{"name": ".", "sql": {"0": SQL_NULL}}])
else:
return wrap([{"name": ".", "sql": output}])
@extend(CaseOp)
def to_sql(self, schema, not_null=False, boolean=False):
if len(self.whens) == 1:
return self.whens[-1].to_sql(schema)
output = {}
for t in "bsn": # EXPENSIVE LOOP to_sql() RUN 3 TIMES
els_ = coalesce(self.whens[-1].to_sql(schema)[0].sql[t], SQL_NULL)
acc = SQL_ELSE + els_ + SQL_END
for w in reversed(self.whens[0:-1]):
acc = SQL_WHEN + w.when.to_sql(schema, boolean=True)[0].sql.b + SQL_THEN + coalesce(w.then.to_sql(schema)[0].sql[t], SQL_NULL) + acc
output[t] = SQL_CASE + acc
return wrap([{"name": ".", "sql": output}])
@extend(SqlEqOp)
def to_sql(self, schema, not_null=False, boolean=False):
lhs = self.lhs.partial_eval().to_sql(schema)[0].sql.values()[0]
rhs = self.rhs.partial_eval().to_sql(schema)[0].sql.values()[0]
return wrap([{"name": ".", "sql": {
"b": sql_iso(lhs) + "=" + sql_iso(rhs)
}}])
@extend(SqlInstrOp)
def to_sql(self, schema, not_null=False, boolean=False):
value = self.value.to_sql(schema)[0].sql.s
find = self.find.to_sql(schema)[0].sql.s
return wrap([{"name": ".", "sql": {
"n": "INSTR" + sql_iso(sql_list([value, find]))
}}])
@extend(SqlInstrOp)
@simplified
def partial_eval(self):
value = self.value.partial_eval()
find = self.find.partial_eval()
return SqlInstrOp("instr", [value, find])
@extend(SqlSubstrOp)
def to_sql(self, schema, not_null=False, boolean=False):
value = self.value.to_sql(schema)[0].sql.s
start = self.start.to_sql(schema)[0].sql.n
if self.length is NULL:
return wrap([{"name": ".", "sql": {
"s": "SUBSTR" + sql_iso(sql_list([value, start]))
}}])
else:
length = self.length.to_sql(schema)[0].sql.n
return wrap([{"name": ".", "sql": {
"s": "SUBSTR" + sql_iso(sql_list([value, start, length]))
}}])
@extend(SqlSubstrOp)
@simplified
def partial_eval(self):
value = self.value.partial_eval()
start = self.start.partial_eval()
length = self.length.partial_eval()
if isinstance(start, Literal) and start.value == 1:
if length is NULL:
return value
return SqlSubstrOp("substr", [value, start, length])
json_type_to_sql_type = {
"null": "0",
"boolean": "b",
"number": "n",
"string": "s",
"object": "j",
"nested": "j"
}
sql_type_to_json_type = {
"0": "null",
"b": "boolean",
"n": "number",
"s": "string",
"j": "object"
}
|
klahnakoski/JsonSchemaToMarkdown
|
vendor/jx_sqlite/expressions.py
|
Python
|
mpl-2.0
| 30,120
|
const getEngineName = (engine) => {
switch (engine) {
case 'electron': {
return 'Electron';
}
case 'firefox': {
return 'Mozilla Firefox';
}
case 'chromium': {
return 'Chromium';
}
case 'chrome': {
return 'Google Chrome';
}
case 'brave': {
return 'Brave';
}
case 'vivaldi': {
return 'Vivaldi';
}
case 'edge': {
return 'Microsoft Edge';
}
default: {
throw new Error('Engine is not supported');
}
}
};
export default getEngineName;
|
quanglam2807/webcatalog
|
src/helpers/get-engine-name.js
|
JavaScript
|
mpl-2.0
| 546
|
{"gift":{"activityId":null,"activityType":null,"venderId":null,"type":0,"name":null,"itemHb":null,"id":"1","giftType":"9","giftName":"1积分","giftNum":"1","giftTotal":"10000","giftResidue":null,"priceInfo":"0","shortLink":"","orginLink":null,"giftInfoId":"92c8bff381e84e2280ba9d7be0b7c2d0","commonAddAwardVO":null},"msg":"","isOk":true,"isSend":true,"key":"gmaMCQ"}
|
bobon/push_weibo_to_shequdaren
|
jd_signup/1309893722-164885/1000325645_signUp.html
|
HTML
|
mpl-2.0
| 368
|
package ecc
import (
"bytes"
b64 "encoding/base64"
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"reflect"
"time"
"github.com/socketplane/ecc/Godeps/_workspace/src/github.com/hashicorp/consul/api"
"github.com/socketplane/ecc/Godeps/_workspace/src/github.com/hashicorp/consul/command"
"github.com/socketplane/ecc/Godeps/_workspace/src/github.com/hashicorp/consul/watch"
"github.com/socketplane/ecc/Godeps/_workspace/src/github.com/mitchellh/cli"
)
// Embedded Consul Client
// Quick and Dirty way to embed Consul with any golang based application without the
// additional step of installing the Consul application in the host system
// Consul Agent related functions
var started bool
var OfflineSupport bool = true
var listener eccListener
func Start(serverMode bool, bootstrap bool, bindInterface string, dataDir string) error {
bindAddress := ""
if bindInterface != "" {
intf, err := net.InterfaceByName(bindInterface)
if err != nil {
log.Printf("Error : %v", err)
return err
}
addrs, err := intf.Addrs()
if err == nil {
for i := 0; i < len(addrs); i++ {
addr := addrs[i].String()
ip, _, _ := net.ParseCIDR(addr)
if ip != nil && ip.To4() != nil {
bindAddress = ip.To4().String()
}
}
}
}
errCh := make(chan int)
watchForExistingRegisteredUpdates()
go RegisterForNodeUpdates(listener)
go startConsul(serverMode, bootstrap, bindAddress, dataDir, errCh)
select {
case <-errCh:
return errors.New("Error starting Consul Agent")
case <-time.After(time.Second * 5):
}
return nil
}
func startConsul(serverMode bool, bootstrap bool, bindAddress string, dataDir string, eCh chan int) {
args := []string{"agent", "-data-dir", dataDir}
if serverMode {
args = append(args, "-server")
}
if bootstrap {
args = append(args, "-bootstrap")
}
if bindAddress != "" {
args = append(args, "-bind")
args = append(args, bindAddress)
args = append(args, "-advertise")
args = append(args, bindAddress)
}
ret := Execute(args...)
eCh <- ret
}
func HasStarted() bool {
return started
}
func Join(address string) error {
ret := Execute("join", address)
if ret != 0 {
log.Println("Error (%d) joining %s with Consul peers", ret, address)
return errors.New("Error adding member")
}
return nil
}
func Leave() error {
stopWatches()
ret := Execute("leave")
if ret != 0 {
log.Println("Error Leaving Consul membership")
return errors.New("Error leaving Consul cluster")
}
return nil
}
// Execute function is borrowed from Consul's main.go
func Execute(args ...string) int {
for _, arg := range args {
if arg == "-v" || arg == "--version" {
newArgs := make([]string, len(args)+1)
newArgs[0] = "version"
copy(newArgs[1:], args)
args = newArgs
break
}
}
cli := &cli.CLI{
Args: args,
Commands: Commands,
HelpFunc: cli.BasicHelpFunc("consul"),
}
exitCode, err := cli.Run()
if err != nil {
fmt.Fprintf(os.Stderr, "Error executing CLI: %s\n", err.Error())
return 1
}
return exitCode
}
const CONSUL_BASE_URL = "http://localhost:8500/v1/"
func ConsulGet(url string) (string, bool) {
resp, err := http.Get(url)
if err != nil {
log.Printf("Error (%v) in Get for %s\n", err, url)
return "", false
}
defer resp.Body.Close()
log.Printf("Status of Get %s %d for %s", resp.Status, resp.StatusCode, url)
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
var jsonBody []consulBody
body, err := ioutil.ReadAll(resp.Body)
err = json.Unmarshal(body, &jsonBody)
existingValue, err := b64.StdEncoding.DecodeString(jsonBody[0].Value)
if err != nil {
return "", false
}
return string(existingValue[:]), true
} else {
return "", false
}
}
// Consul KV Store related
const CONSUL_KV_BASE_URL = "http://localhost:8500/v1/kv/"
type consulBody struct {
CreateIndex int `json:"CreateIndex,omitempty"`
ModifyIndex int `json:"ModifyIndex,omitempty"`
Key string `json:"Key,omitempty"`
Flags int `json:"Flags,omitempty"`
Value string `json:"Value,omitempty"`
}
func GetAll(store string) ([][]byte, []int, bool) {
if OfflineSupport && !started {
return getAllFromCache(store)
}
url := CONSUL_KV_BASE_URL + store + "?recurse"
resp, err := http.Get(url)
if err != nil {
log.Printf("Error (%v) in Get for %s\n", err, url)
return nil, nil, false
}
defer resp.Body.Close()
log.Printf("Status of Get %s %d for %s", resp.Status, resp.StatusCode, url)
if resp.StatusCode >= 400 && resp.StatusCode < 500 {
return nil, nil, false
} else if resp.StatusCode >= 200 && resp.StatusCode < 300 {
var jsonBody []consulBody
valueArr := make([][]byte, 0)
indexArr := make([]int, 0)
body, _ := ioutil.ReadAll(resp.Body)
err = json.Unmarshal(body, &jsonBody)
for _, body := range jsonBody {
existingValue, _ := b64.StdEncoding.DecodeString(body.Value)
valueArr = append(valueArr, existingValue)
indexArr = append(indexArr, body.ModifyIndex)
}
return valueArr, indexArr, true
} else {
return nil, nil, false
}
}
func Get(store string, key string) ([]byte, int, bool) {
if OfflineSupport && !started {
return getFromCache(store, key)
}
url := CONSUL_KV_BASE_URL + store + "/" + key
resp, err := http.Get(url)
if err != nil {
log.Printf("Error (%v) in Get for %s\n", err, url)
return nil, 0, false
}
defer resp.Body.Close()
log.Printf("Status of Get %s %d for %s", resp.Status, resp.StatusCode, url)
if resp.StatusCode >= 400 && resp.StatusCode < 500 {
return nil, 0, false
} else if resp.StatusCode >= 200 && resp.StatusCode < 300 {
var jsonBody []consulBody
body, err := ioutil.ReadAll(resp.Body)
err = json.Unmarshal(body, &jsonBody)
existingValue, err := b64.StdEncoding.DecodeString(jsonBody[0].Value)
if err != nil {
return nil, jsonBody[0].ModifyIndex, false
}
return existingValue, jsonBody[0].ModifyIndex, true
} else {
return nil, 0, false
}
}
const (
OK = iota
OUTDATED
ERROR
)
type eccerror int
func Put(store string, key string, value []byte, oldValue []byte) eccerror {
if OfflineSupport && !started {
return putInCache(store, key, value, oldValue)
}
existingValue, casIndex, ok := Get(store, key)
if ok && !bytes.Equal(oldValue, existingValue) {
return OUTDATED
}
url := fmt.Sprintf("%s%s/%s?cas=%d", CONSUL_KV_BASE_URL, store, key, casIndex)
log.Printf("Updating KV pair for %s %s %s %d", url, key, value, casIndex)
req, err := http.NewRequest("PUT", url, bytes.NewBuffer(value))
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Println("Error creating KV pair for ", url, err)
return ERROR
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
if string(body) == "false" {
// Let the application retry based on return value
// return Put(store, key, value, oldValue)
return OUTDATED
}
return OK
}
func Delete(store string, key string) eccerror {
if OfflineSupport && !started {
return deleteFromCache(store, key)
}
url := fmt.Sprintf("%s%s/%s", CONSUL_KV_BASE_URL, store, key)
log.Printf("Deleting KV pair for %s", url)
req, err := http.NewRequest("DELETE", url, nil)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Println("Error creating KV pair for ", url, err)
return ERROR
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
log.Println(string(body))
return OK
}
type Store struct {
cache map[string][]byte
}
// Local KV store cache for bootstrap node consul connection issues
var cache map[string]Store = make(map[string]Store)
func getAllFromCache(storeName string) ([][]byte, []int, bool) {
store, ok := cache[storeName]
if !ok {
return nil, nil, false
}
vals := make([][]byte, 0)
for _, val := range store.cache {
vals = append(vals, val)
}
return vals, nil, true
}
func getFromCache(storeName string, key string) ([]byte, int, bool) {
store, ok := cache[storeName]
if !ok {
return nil, 0, false
}
val, ok := store.cache[key]
return val, 0, ok
}
func putInCache(storeName string, key string, value []byte, oldValue []byte) eccerror {
store, ok := cache[storeName]
if !ok {
store = Store{make(map[string][]byte)}
cache[storeName] = store
}
store.cache[key] = value
return OK
}
func deleteFromCache(storeName string, key string) eccerror {
store, ok := cache[storeName]
if ok {
delete(store.cache, key)
}
return OK
}
func populateKVStoreFromCache() {
if !OfflineSupport || started {
return
}
started = true
for storeName, store := range cache {
for key, val := range store.cache {
go Put(storeName, key, val, nil)
}
delete(cache, storeName)
}
}
// Watch related
const (
NOTIFY_UPDATE_ADD = iota
NOTIFY_UPDATE_MODIFY
NOTIFY_UPDATE_DELETE
)
type NotifyUpdateType int
const (
WATCH_TYPE_NODE = iota
WATCH_TYPE_KEY
WATCH_TYPE_STORE
WATCH_TYPE_EVENT
)
type WatchType int
type watchData struct {
listeners map[string][]Listener
watchPlans []*watch.WatchPlan
}
var watches map[WatchType]watchData = make(map[WatchType]watchData)
type Listener interface {
NotifyNodeUpdate(NotifyUpdateType, string)
NotifyKeyUpdate(NotifyUpdateType, string, []byte)
NotifyStoreUpdate(NotifyUpdateType, string, map[string][]byte)
}
type eccListener struct {
}
func (e eccListener) NotifyNodeUpdate(nType NotifyUpdateType, nodeAddress string) {
if nType == NOTIFY_UPDATE_ADD && !started {
populateKVStoreFromCache()
}
}
func (e eccListener) NotifyKeyUpdate(nType NotifyUpdateType, key string, data []byte) {
}
func (e eccListener) NotifyStoreUpdate(nType NotifyUpdateType, store string, data map[string][]byte) {
}
func contains(wtype WatchType, key string, elem interface{}) bool {
ws, ok := watches[wtype]
if !ok {
return false
}
list, ok := ws.listeners[key]
if !ok {
return false
}
v := reflect.ValueOf(list)
for i := 0; i < v.Len(); i++ {
if v.Index(i).Interface() == elem {
return true
}
}
return false
}
type watchconsul bool
func addListener(wtype WatchType, key string, listener Listener) watchconsul {
var wc watchconsul = false
if !contains(WATCH_TYPE_NODE, key, listener) {
ws, ok := watches[wtype]
if !ok {
watches[wtype] = watchData{make(map[string][]Listener), make([]*watch.WatchPlan, 0)}
ws = watches[wtype]
}
listeners, ok := ws.listeners[key]
if !ok {
listeners = make([]Listener, 0)
wc = true
}
ws.listeners[key] = append(listeners, listener)
}
return wc
}
func getListeners(wtype WatchType, key string) []Listener {
ws, ok := watches[wtype]
if !ok {
return nil
}
list, ok := ws.listeners[key]
if ok {
return list
}
return nil
}
func addWatchPlan(wtype WatchType, wp *watch.WatchPlan) {
ws, ok := watches[wtype]
if !ok {
return
}
ws.watchPlans = append(ws.watchPlans, wp)
watches[wtype] = ws
}
func stopWatches() {
for _, ws := range watches {
for _, wp := range ws.watchPlans {
wp.Stop()
}
ws.watchPlans = ws.watchPlans[:0]
}
}
func register(wtype WatchType, params map[string]interface{}, handler watch.HandlerFunc) {
// Create the watch
wp, err := watch.Parse(params)
if err != nil {
fmt.Printf("Register error : %s", err)
return
}
addWatchPlan(wtype, wp)
wp.Handler = handler
cmdFlags := flag.NewFlagSet("watch", flag.ContinueOnError)
httpAddr := command.HTTPAddrFlag(cmdFlags)
// Run the watch
if err := wp.Run(*httpAddr); err != nil {
fmt.Printf("Error querying Consul agent: %s", err)
}
}
var nodeCache []*api.Node
func compare(X, Y []*api.Node) []*api.Node {
m := make(map[string]bool)
for _, y := range Y {
m[y.Address] = true
}
var ret []*api.Node
for _, x := range X {
if m[x.Address] {
continue
}
ret = append(ret, x)
}
return ret
}
func updateNodeListeners(clusterNodes []*api.Node) {
toDelete := compare(nodeCache, clusterNodes)
toAdd := compare(clusterNodes, nodeCache)
nodeCache = clusterNodes
listeners := getListeners(WATCH_TYPE_NODE, "")
if listeners == nil {
return
}
for _, deleteNode := range toDelete {
for _, listener := range listeners {
listener.NotifyNodeUpdate(NOTIFY_UPDATE_DELETE, deleteNode.Address)
}
}
for _, addNode := range toAdd {
for _, listener := range listeners {
listener.NotifyNodeUpdate(NOTIFY_UPDATE_ADD, addNode.Address)
}
}
}
func updateKeyListeners(idx uint64, key string, data interface{}) {
listeners := getListeners(WATCH_TYPE_KEY, key)
if listeners == nil {
return
}
var kv *api.KVPair = nil
var val []byte = nil
updateType := NOTIFY_UPDATE_MODIFY
if data != nil {
kv = data.(*api.KVPair)
}
if kv == nil {
updateType = NOTIFY_UPDATE_DELETE
} else {
updateType = NOTIFY_UPDATE_MODIFY
if idx == kv.CreateIndex {
updateType = NOTIFY_UPDATE_ADD
}
val = kv.Value
}
for _, listener := range listeners {
listener.NotifyKeyUpdate(NotifyUpdateType(updateType), key, val)
}
}
func registerForNodeUpdates() {
// Compile the watch parameters
params := make(map[string]interface{})
params["type"] = "nodes"
handler := func(idx uint64, data interface{}) {
updateNodeListeners(data.([]*api.Node))
}
register(WATCH_TYPE_NODE, params, handler)
}
func RegisterForNodeUpdates(listener Listener) {
wc := addListener(WATCH_TYPE_NODE, "", listener)
if wc {
registerForNodeUpdates()
}
}
func registerForKeyUpdates(absKey string) {
params := make(map[string]interface{})
params["type"] = "key"
params["key"] = absKey
handler := func(idx uint64, data interface{}) {
updateKeyListeners(idx, absKey, data)
}
register(WATCH_TYPE_KEY, params, handler)
}
func RegisterForKeyUpdates(store string, key string, listener Listener) {
absKey := store + "/" + key
wc := addListener(WATCH_TYPE_KEY, absKey, listener)
if wc {
registerForKeyUpdates(absKey)
}
}
func registerForStoreUpdates(store string) {
// Compile the watch parameters
params := make(map[string]interface{})
params["type"] = "keyprefix"
params["prefix"] = store + "/"
handler := func(idx uint64, data interface{}) {
fmt.Println("NOT IMPLEMENTED Store Update :", idx, data)
}
register(WATCH_TYPE_STORE, params, handler)
}
func RegisterForStoreUpdates(store string, listener Listener) {
wc := addListener(WATCH_TYPE_STORE, store, listener)
if wc {
registerForStoreUpdates(store)
}
}
func watchForExistingRegisteredUpdates() {
for wType, ws := range watches {
log.Println("watchForExistingRegisteredUpdates : ", wType)
for key, _ := range ws.listeners {
log.Println("key : ", key)
switch wType {
case WATCH_TYPE_NODE:
go registerForNodeUpdates()
case WATCH_TYPE_KEY:
go registerForKeyUpdates(key)
case WATCH_TYPE_STORE:
go registerForStoreUpdates(key)
}
}
}
}
|
socketplane/ecc
|
ecc.go
|
GO
|
mpl-2.0
| 14,626
|
var NAVTREEINDEX0 =
{
"adc_8h_source.html":[2,0,0],
"annotated.html":[1,0],
"classes.html":[1,1],
"crc_8h_source.html":[2,0,1],
"cs_8h_source.html":[2,0,2],
"driverlib_8h_source.html":[2,0,3],
"ecomp_8h_source.html":[2,0,4],
"eusci__a__spi_8h_source.html":[2,0,5],
"eusci__a__uart_8h_source.html":[2,0,6],
"eusci__b__i2c_8h_source.html":[2,0,7],
"eusci__b__spi_8h_source.html":[2,0,8],
"files.html":[2,0],
"framctl_8h_source.html":[2,0,9],
"functions.html":[1,2,0],
"functions_vars.html":[1,2,1],
"gpio_8h_source.html":[2,0,10],
"group__adc__api.html":[0,1],
"group__adc__api.html#ga0012e2b1fead5663fc9c8900215f0152":[0,1,13],
"group__adc__api.html#ga0029fd13453bffe85fc0b119d740b655":[0,1,1],
"group__adc__api.html#ga05ac6e509a2c344389b950431beda6c7":[0,1,8],
"group__adc__api.html#ga06530dbc06c398eb358300e9c62b4c0d":[0,1,9],
"group__adc__api.html#ga0de3ac40712f6273014336d078676ff2":[0,1,11],
"group__adc__api.html#ga227b4827b1995ab1e1ae1102429de6d8":[0,1,12],
"group__adc__api.html#ga2a2f0981dea099322ae526e8f1ee8d56":[0,1,15],
"group__adc__api.html#ga47485079b973d5837519ef9624cd89b4":[0,1,5],
"group__adc__api.html#ga54b0a5fe7e6982d3dbbdd19729e54f8a":[0,1,7],
"group__adc__api.html#ga7ccc674a9f642169c1358e064fa891b4":[0,1,4],
"group__adc__api.html#ga99636f7fccfc867dbd1f64c27135fba3":[0,1,17],
"group__adc__api.html#ga9c47f80a409b58fbcf33e286d492f350":[0,1,18],
"group__adc__api.html#gaafa37ac91fa4b60020b6cf9095e15351":[0,1,2],
"group__adc__api.html#gab769fb505c23d0eebbf490091be7ec3a":[0,1,16],
"group__adc__api.html#gabbdca7473fa2bad25b9d5e185863d74e":[0,1,0],
"group__adc__api.html#gaca37376c40e9e754caf1e278a91f46b8":[0,1,19],
"group__adc__api.html#gad442d21e6f3ea6e83bf388c3277acef4":[0,1,14],
"group__adc__api.html#gad8af8f7d7a687f85391b5afd3b205832":[0,1,6],
"group__adc__api.html#gadb1fc4a51321b758928a806fee7a204a":[0,1,3],
"group__adc__api.html#gafdff93b9a4e25d3335ad5c6935c0d6d7":[0,1,10],
"group__crc__api.html":[0,2],
"group__crc__api.html#ga4527407a07de8d32e77c40fca7eac4f4":[0,2,4],
"group__crc__api.html#ga4b84bdb66c91e12c5d9c49b2e26ab66a":[0,2,6],
"group__crc__api.html#ga546982ae7c7bff8b27229b506f3c1dcd":[0,2,3],
"group__crc__api.html#ga73086d7ba9d2162de6149d965e88a574":[0,2,1],
"group__crc__api.html#gaa7f85d73fc76b7d6fd2e35d548a56e9b":[0,2,7],
"group__crc__api.html#gaabcd07853c69211f509da5a79fdea9c5":[0,2,5],
"group__crc__api.html#gabfd146dc6616a99e0e7ada62ce4efe1a":[0,2,0],
"group__crc__api.html#gac276eb05e9178cdda7ec0b33f99b9987":[0,2,2],
"group__cs__api.html":[0,3],
"group__cs__api.html#ga057db654dafdf9a3a81f51d83660e593":[0,3,31],
"group__cs__api.html#ga0fa3d27598e86f1098a96dd041673141":[0,3,16],
"group__cs__api.html#ga14aab64fc9fe9b7e9d154fd220782cfd":[0,3,0],
"group__cs__api.html#ga17b93c8741649cc85f9bf9b165ebc613":[0,3,2],
"group__cs__api.html#ga197a36cbe290ef4c28f25ec8b4689f72":[0,3,7],
"group__cs__api.html#ga1f05cf6c91f1d045e6bcdc34c40b6057":[0,3,10],
"group__cs__api.html#ga2253673c6716b244ae6630fc62182de9":[0,3,20],
"group__cs__api.html#ga2a26c1bdfeffc3b11431fd811d50db68":[0,3,17],
"group__cs__api.html#ga2c3697b6e0b652b8f0c69a59f1600473":[0,3,33],
"group__cs__api.html#ga2d6b21b0770fca22924c1b0a3d1e3174":[0,3,6],
"group__cs__api.html#ga2e02ddb15b854383842bbc8f52fa050d":[0,3,18],
"group__cs__api.html#ga4132a2bdca1271461f6633732e20f2a0":[0,3,3],
"group__cs__api.html#ga41614de6796c5b269ac27dc86ef07090":[0,3,24],
"group__cs__api.html#ga4356ee7b0c190fdcc8b20fd3ae6bf741":[0,3,25],
"group__cs__api.html#ga4d1578bbcb91642dc86b7264710282c9":[0,3,32],
"group__cs__api.html#ga50781f9ad55c0527b05883822a5d270d":[0,3,19],
"group__cs__api.html#ga5a9e1c2cc9af2ca0bd7e6463b9fee95a":[0,3,26],
"group__cs__api.html#ga5e98aa060bd3aed44eb926f0415720e7":[0,3,35],
"group__cs__api.html#ga6950bde5b0df067674ee0a1bf3cb3dcd":[0,3,13],
"group__cs__api.html#ga72c43f397b5920540e6dee598810f1c9":[0,3,8],
"group__cs__api.html#ga803057e12c7d7c6cc6316f559afbbf40":[0,3,12],
"group__cs__api.html#ga8c347bc9d053e28f9ff28e6d5182f7d5":[0,3,11],
"group__cs__api.html#ga913b79f0c9819862d6c53e1ddd1874af":[0,3,29],
"group__cs__api.html#gaa618188babf9fcc510ec99392f13dc7e":[0,3,27],
"group__cs__api.html#gaa731c50c41e01fbab65c4061d5863191":[0,3,22],
"group__cs__api.html#gaa94c0692c60a78228ea374dbecbe80c0":[0,3,15],
"group__cs__api.html#gab0ceebc3cea3113d15711ea63f552189":[0,3,30],
"group__cs__api.html#gab9553e354826bca3eb3cef3f7de4b0f0":[0,3,1],
"group__cs__api.html#gab9b0d0c56498e144f20abea7d7319c15":[0,3,28],
"group__cs__api.html#gaba9277292b225f48d5e0568babffb0fc":[0,3,23],
"group__cs__api.html#gabe4df93b5487a9e19b4b2fc62185be8f":[0,3,4],
"group__cs__api.html#gad5a8296684172b71a863840e1a932fa2":[0,3,34],
"group__cs__api.html#gad72e9f5fa944264551f16a59a865e3d1":[0,3,14],
"group__cs__api.html#gae012353ccb47ae03e7b0939a12d79c3c":[0,3,21],
"group__cs__api.html#gae2f91ff1443e77f61f116ffbe154b8ed":[0,3,9],
"group__cs__api.html#gafbbb62b645345eee2096c0e9b3ac8e82":[0,3,5],
"group__ecomp__api.html":[0,4],
"group__eusci__a__spi__api.html":[0,5],
"group__eusci__a__spi__api.html#ga0494b51f3cfe976a070a256fce3ca4fa":[0,5,6],
"group__eusci__a__spi__api.html#ga28fac820247ff9eb27cea15e795c3f3c":[0,5,10],
"group__eusci__a__spi__api.html#ga346b242110d8fa7117a30df56b43dfea":[0,5,7],
"group__eusci__a__spi__api.html#ga4c2a3af00d3f109afc6bbf6f98445a4d":[0,5,12],
"group__eusci__a__spi__api.html#ga4e64e21421f0952074484ab116124d02":[0,5,8],
"group__eusci__a__spi__api.html#ga76ea4cbe0fcca41c1bcb70412c66f09e":[0,5,11],
"group__eusci__a__spi__api.html#ga78ea9ababaf4161809dfa1de8bf5062f":[0,5,13],
"group__eusci__a__spi__api.html#ga887a169b3b6bb10316576f04a43e212d":[0,5,5],
"group__eusci__a__spi__api.html#ga9a75a79ce93830e157147b1eff1c82c9":[0,5,3],
"group__eusci__a__spi__api.html#gaad64c84c41eeed8eb2b391c5a5e4b88c":[0,5,16],
"group__eusci__a__spi__api.html#gaaf780504ce42367714da3c12c366b38b":[0,5,2],
"group__eusci__a__spi__api.html#gab07b208b18627c7074060f0e5291c158":[0,5,14],
"group__eusci__a__spi__api.html#gab2d3afb337e2966e9bc5273fcadade59":[0,5,4],
"group__eusci__a__spi__api.html#gac170dfce3401bd736c7eec0da58e494b":[0,5,9],
"group__eusci__a__spi__api.html#gacc3a03a1689c77be07c4275e2622e848":[0,5,15],
"group__eusci__a__spi__api.html#gae566374a62c75e9ea74cea2a84287226":[0,5,0],
"group__eusci__a__spi__api.html#gaede23884d973a7bcaf4203b39b1b0fdf":[0,5,1],
"group__eusci__a__uart__api.html":[0,6],
"group__eusci__a__uart__api.html#ga09f2b714ce0556e210b5c054b3138eaa":[0,6,13],
"group__eusci__a__uart__api.html#ga1b4fa41e9447eef4c5f270369b8902c7":[0,6,15],
"group__eusci__a__uart__api.html#ga2a08645b3003df7cdf0b9bd416efcddf":[0,6,8],
"group__eusci__a__uart__api.html#ga36bc7fc49217a06c33a397cd71c571ee":[0,6,12],
"group__eusci__a__uart__api.html#ga612febef76882199aaa395bb941e4a64":[0,6,0],
"group__eusci__a__uart__api.html#ga8264a417944411b5fbe988d94ae21d20":[0,6,4],
"group__eusci__a__uart__api.html#ga8c4cf3e29c3200191506e8d576393c26":[0,6,9],
"group__eusci__a__uart__api.html#ga929c7fbd7c476127cd511beea6d01294":[0,6,14],
"group__eusci__a__uart__api.html#ga97ed7748495844b3506d778ecdbb5dfa":[0,6,6],
"group__eusci__a__uart__api.html#gaae82375105abc8655ef50f8c36ffcf13":[0,6,1],
"group__eusci__a__uart__api.html#gab10882f5122070c22250ab4241ea7a6f":[0,6,5],
"group__eusci__a__uart__api.html#gab18364db57b4719f71e83a5f69897d66":[0,6,10],
"group__eusci__a__uart__api.html#gab53ed9c282a4ef15ab1d7feb278c4e78":[0,6,11],
"group__eusci__a__uart__api.html#gae0a01876b95bcd1396eddbb26e7ffabe":[0,6,16],
"group__eusci__a__uart__api.html#gaf1c34e38356e6918732151dc92b47b50":[0,6,2],
"group__eusci__a__uart__api.html#gaf2bd04f23261ebafd4890c35945a7877":[0,6,3],
"group__eusci__a__uart__api.html#gaf637ca8f96fc93101f1111b23da6c87f":[0,6,17],
"group__eusci__a__uart__api.html#gaf873d22baa0ed6b207b5f3aebbea1a4c":[0,6,7],
"group__eusci__b__i2c__api.html":[0,7],
"group__eusci__b__i2c__api.html#ga05d1357111f00447b9712db99caec223":[0,7,31],
"group__eusci__b__i2c__api.html#ga14372b17afed0ddd5b8d1166876079e3":[0,7,34],
"group__eusci__b__i2c__api.html#ga1566d542d05cd0022501c482821a8af1":[0,7,1],
"group__eusci__b__i2c__api.html#ga192fcc01db124a886901523bfe793379":[0,7,12],
"group__eusci__b__i2c__api.html#ga1bb93f7d987f97bf22687033debc2007":[0,7,38],
"group__eusci__b__i2c__api.html#ga29a3dd23e89bbcc27728f510ad88fb84":[0,7,19],
"group__eusci__b__i2c__api.html#ga29e69a05dac2cd1337305c47c6827782":[0,7,24],
"group__eusci__b__i2c__api.html#ga2bf2eb4c44b7b12ad8e2d6e3f1af0fa1":[0,7,22],
"group__eusci__b__i2c__api.html#ga39c316f7c1e0cfa63db101a419f33052":[0,7,25],
"group__eusci__b__i2c__api.html#ga3a4bd43e5302e32f8b1bea79ead2379b":[0,7,14],
"group__eusci__b__i2c__api.html#ga406176586f20ee82448be3243042f96a":[0,7,37],
"group__eusci__b__i2c__api.html#ga4ea4fce66769096d7e2ac10e4addd640":[0,7,0],
"group__eusci__b__i2c__api.html#ga575c7899bb875640f75bab7138a18c66":[0,7,11],
"group__eusci__b__i2c__api.html#ga576b4647b551d71202d79a8db904c9eb":[0,7,8],
"group__eusci__b__i2c__api.html#ga5913816a25cd775ec5cb15ef646637bd":[0,7,27],
"group__eusci__b__i2c__api.html#ga6277f511d27dec845ded98da0da5efc0":[0,7,20],
"group__eusci__b__i2c__api.html#ga65e4d906257c71881cfbf87c18561f8f":[0,7,6],
"group__eusci__b__i2c__api.html#ga67f4b5139adece5a9050ee832c388757":[0,7,5],
"group__eusci__b__i2c__api.html#ga6c068fa93e7df171077d967c08835656":[0,7,4],
"group__eusci__b__i2c__api.html#ga6cea61484692bff9b3c0058b4f215496":[0,7,18],
"group__eusci__b__i2c__api.html#ga6e4f72c087f34334d03844c9b73b6368":[0,7,21],
"group__eusci__b__i2c__api.html#ga72a1ce27a6b6c8a31fbdaa875a6a3434":[0,7,35],
"group__eusci__b__i2c__api.html#ga73662743450ae6e7e7dc802ed2ee26a1":[0,7,10],
"group__eusci__b__i2c__api.html#ga91e951ea2bc7ba4c6ca37f146be4f9bb":[0,7,17],
"group__eusci__b__i2c__api.html#ga931cf95c88a427320415901bb9a09392":[0,7,32],
"group__eusci__b__i2c__api.html#ga9b87172cf71cdfa2617aa9eaf512f855":[0,7,33],
"group__eusci__b__i2c__api.html#ga9bad1810c1e8d71ccb19bfb3fb32c238":[0,7,28],
"group__eusci__b__i2c__api.html#ga9d8895927876c43dd6d2c55584aefc2e":[0,7,9],
"group__eusci__b__i2c__api.html#gaa7eba38c8d9fdf701aacce8c556a8bc2":[0,7,30],
"group__eusci__b__i2c__api.html#gaa9649c2aa696bc5abf84defd7667cfef":[0,7,26],
"group__eusci__b__i2c__api.html#gab4458db4aa4d75f1f544e9913655848c":[0,7,23],
"group__eusci__b__i2c__api.html#gabdb3f2891ff4d79a2d032671446ae92c":[0,7,3],
"group__eusci__b__i2c__api.html#gac389d3e08214769c8df793b79377be95":[0,7,36],
"group__eusci__b__i2c__api.html#gac891873a0a211186a3b4841765825f0e":[0,7,13],
"group__eusci__b__i2c__api.html#gade7a54d59b5f3bc01115a5ac0a4cff67":[0,7,29],
"group__eusci__b__i2c__api.html#gae15cc38fc4db01e744f666a44211c72e":[0,7,7],
"group__eusci__b__i2c__api.html#gae45ee9c8bfb4156333f20d486d336271":[0,7,15],
"group__eusci__b__i2c__api.html#gae77d36617b0cab5f36e5fde90bfc1491":[0,7,16],
"group__eusci__b__i2c__api.html#gaff58ca7965a5f201db823e7ee81f0d1b":[0,7,2],
"group__eusci__b__spi__api.html":[0,8],
"group__eusci__b__spi__api.html#ga0956e03b07c7bd9ef470520b3cc629ec":[0,8,0],
"group__eusci__b__spi__api.html#ga0af8a2608105d46bf2535cf66955f9e8":[0,8,15],
"group__eusci__b__spi__api.html#ga17ac731bf7574e7d304f491ba6544b46":[0,8,8],
"group__eusci__b__spi__api.html#ga2a1983e938844a55b61392b511948e95":[0,8,12],
"group__eusci__b__spi__api.html#ga3413c7bce09d85f08297e897382c4cfc":[0,8,10],
"group__eusci__b__spi__api.html#ga378725ad1d2a3ac56a28a344970dc441":[0,8,16],
"group__eusci__b__spi__api.html#ga42caef5502406076a1ad04e1d4f23b29":[0,8,1],
"group__eusci__b__spi__api.html#ga4316a532a812f592834eca58303fd4b8":[0,8,2],
"group__eusci__b__spi__api.html#ga5e82fba6d057eeace8b997573f4c76ba":[0,8,6],
"group__eusci__b__spi__api.html#ga5ee08ebc3ff91a2d6f1cbc5ffeb6285a":[0,8,9],
"group__eusci__b__spi__api.html#ga72e65c23c4b857b24778623d22e3acf0":[0,8,5],
"group__eusci__b__spi__api.html#ga90b76b02da1da4358e3ce0bf5f23b422":[0,8,3],
"group__eusci__b__spi__api.html#gaa3cf1d5f8838437b46c6a1b73a50cd0c":[0,8,11],
"group__eusci__b__spi__api.html#gac5c42699fc07d7cd05e6bee66c02cd66":[0,8,14],
"group__eusci__b__spi__api.html#gac753bb7a04151a31ae789076bac29cbe":[0,8,4],
"group__eusci__b__spi__api.html#gad15613f58cc934d947b2466e1d4c6101":[0,8,7],
"group__eusci__b__spi__api.html#gadb08b8aed76fc888a65e04b305bac146":[0,8,13],
"group__framctl__api.html":[0,9],
"group__framctl__api.html#ga112a4aea2a769a75d93c8427b45fa8cd":[0,9,2],
"group__framctl__api.html#ga20be8186a8159457ccbdd21575637540":[0,9,6],
"group__framctl__api.html#ga29f80e1cc1cd23f165d252477c0b1790":[0,9,8],
"group__framctl__api.html#ga3b5f0b348d7e0dd8b27e865d1adafd6b":[0,9,0],
"group__framctl__api.html#ga439075a19aefcca4457083c467c51fc2":[0,9,5],
"group__framctl__api.html#ga493739a0c950f70639fa3863799b732d":[0,9,1],
"group__framctl__api.html#gaa474d7ee2b69f092adb57802008dfc40":[0,9,7],
"group__framctl__api.html#gaa9ce3c69be02a257eb8fa5319d94f94a":[0,9,4],
"group__framctl__api.html#gab88bbf17342d3820a95c1450e4d72126":[0,9,3],
"group__gpio__api.html":[0,10],
"group__gpio__api.html#ga13f6c6a83d81877266af538314998db9":[0,10,10],
"group__gpio__api.html#ga1d4a8c508fc5f4d944dc38ce60efb05e":[0,10,8],
"group__gpio__api.html#ga239c2aa2b682b2fe1139df4656c42ae6":[0,10,14],
"group__gpio__api.html#ga425a400f734dfa0f078d5a8a34346047":[0,10,2],
"group__gpio__api.html#ga49a10a5656e40d62a123f22dd268976e":[0,10,5],
"group__gpio__api.html#ga4afb507d137c3d3948dd72d2d67df673":[0,10,3],
"group__gpio__api.html#ga545a2f454e5980e99e116e128f39b3ed":[0,10,1],
"group__gpio__api.html#ga5cffcf0f7edd29fd2fe7bc0617fcbde0":[0,10,13],
"group__gpio__api.html#ga715a2af6a6867b7d091050616ab0b323":[0,10,4],
"group__gpio__api.html#ga864f1f3df9373c219534b8fc293ae192":[0,10,12],
"group__gpio__api.html#gab60c47114886532d84ed7db0066dd24c":[0,10,6],
"group__gpio__api.html#gad664f4c8cee8e11ffe4af82a0fd6e221":[0,10,0],
"group__gpio__api.html#gae4590f0d22361f8f3c5cb4ae7476e779":[0,10,7],
"group__gpio__api.html#gaf14067f736b2f686f7ab813dc3ab739a":[0,10,11],
"group__gpio__api.html#gaf91ee8bc0b0a62c494c74b747d6f2fad":[0,10,9],
"group__lcd__e__api.html":[0,11],
"group__lcd__e__api.html#ga0400ba5d4b3788e1f33c88df7d57db3d":[0,11,9],
"group__lcd__e__api.html#ga092eec3e228e4f37c929fce9aef3936c":[0,11,21],
"group__lcd__e__api.html#ga218012d76ad4e9c93805f20bb6814998":[0,11,30],
"group__lcd__e__api.html#ga291cee95046f2d3c73868b4d953cf390":[0,11,15],
"group__lcd__e__api.html#ga2f06fed48ce0b64b45a6d48e14b607ba":[0,11,26],
"group__lcd__e__api.html#ga32d709511d4f1c9825d8d51b62565dcc":[0,11,28],
"group__lcd__e__api.html#ga3779ccf6573f7585d1d30df4cc7de4b2":[0,11,5],
"group__lcd__e__api.html#ga39acb5bfd70b27024a6a615452142427":[0,11,22],
"group__lcd__e__api.html#ga47be3503199b114cb86a69e978ebd221":[0,11,29],
"group__lcd__e__api.html#ga5227d805004b5a09d95fc38421358c5f":[0,11,23],
"group__lcd__e__api.html#ga5fc150c37bd64732439efd605893bd4d":[0,11,3],
"group__lcd__e__api.html#ga61695041d6b52201ff7e93cc0e467791":[0,11,16],
"group__lcd__e__api.html#ga68a6b28eda6142be495e3b103d7f8d72":[0,11,24],
"group__lcd__e__api.html#ga763ad05312432f8b6f4ad39b8b8d7d74":[0,11,25],
"group__lcd__e__api.html#ga7d2a4f219364d7c2d020b49b741f32d5":[0,11,20],
"group__lcd__e__api.html#ga87f57273c0fb2be7f1fa41a934263d85":[0,11,11],
"group__lcd__e__api.html#ga8f6d78a778d71b2d61415156a4ad92ab":[0,11,10],
"group__lcd__e__api.html#ga919d4509272775a4e7b3ebdbda6e33bd":[0,11,8],
"group__lcd__e__api.html#ga9cdb2fabdb95af287433caa3d03f569f":[0,11,13],
"group__lcd__e__api.html#gab0559e18c47d42fb23021f530f7fb38b":[0,11,14],
"group__lcd__e__api.html#gac4644fcf886b03e5931815d3a34ff6f8":[0,11,27],
"group__lcd__e__api.html#gacaf1d8220c5b2816d1f6fcd00ec03570":[0,11,18],
"group__lcd__e__api.html#gace814b81039b5261204c25da37f42c02":[0,11,6],
"group__lcd__e__api.html#gacfc2bf69faf06c3be3560c1d73b92d5d":[0,11,4],
"group__lcd__e__api.html#gad1364a2e03f90d3e6b9d5188e6aeaeee":[0,11,19],
"group__lcd__e__api.html#gad15fd1bf5799dd1d893e501cbf328ad6":[0,11,0],
"group__lcd__e__api.html#gad78722bef439fc413182ae97c113a785":[0,11,2],
"group__lcd__e__api.html#gad8455b77a760c9b052847545311d3a27":[0,11,7],
"group__lcd__e__api.html#gae96763e1d60c25102db1af0014480788":[0,11,17],
"group__lcd__e__api.html#gae97d85e5023632ab2e1cfe8956fedf8e":[0,11,1],
"group__lcd__e__api.html#gaeb4be069714b216ec525d35eaf76a030":[0,11,12],
"group__mpy32__api.html":[0,12],
"group__mpy32__api.html#ga00e157318e40a40eb56c3bca91fda200":[0,12,7],
"group__mpy32__api.html#ga17d43977c93fcdc23235e2febca9425e":[0,12,5],
"group__mpy32__api.html#ga1fb1ffe9c28d753ac0303ce353486b3b":[0,12,4],
"group__mpy32__api.html#ga44996e5e712ed5dcf8ed60620693bd93":[0,12,13],
"group__mpy32__api.html#ga4e27d31749381782bac863a604668524":[0,12,14],
"group__mpy32__api.html#ga5da97fc45c397895c4b521d121e8f69c":[0,12,10],
"group__mpy32__api.html#ga692f3a81694e17328584b053b8594bdb":[0,12,0],
"group__mpy32__api.html#ga73024d2ce511f91f5a091eee50b1efb6":[0,12,6],
"group__mpy32__api.html#ga746d031e3164665e33c1bef60347903b":[0,12,16],
"group__mpy32__api.html#ga81dad36d1470774fbb2cb1da157d333e":[0,12,8],
"group__mpy32__api.html#ga83c0235a1029d60d0b2156aa564605ae":[0,12,1],
"group__mpy32__api.html#gaa305a12c35535913e6f1eef5cf12b993":[0,12,3]
};
|
ots-m2m/sew-lwm2m-reference-design
|
thirdparty/msp430/doc/MSP430FR2xx_4xx/html/navtreeindex0.js
|
JavaScript
|
mpl-2.0
| 17,055
|
---
--- Created by slanska.
--- DateTime: 2017-11-01 11:26 PM
---
--[[
Implementation of flexi_data virtual table BestIndex API
]]
---@param self DBContext
local flexi_DataBestIndex = function(self)
end
return flexi_DataBestIndex
|
slanska/flexilite
|
src_lua/flexi_DataBestIndex.lua
|
Lua
|
mpl-2.0
| 233
|
#include "thumbnailcreator.h"
namespace libthmbnlr {
ThumbnailCreator::ThumbnailCreator(const STD_STRING_TYPE &videoPath):
m_SeekPercentage(10)
{}
bool ThumbnailCreator::createThumbnail(std::vector<uint8_t> &rgbBuffer, int &width, int &height) {
(void)rgbBuffer;
width = 0;
height = 0;
return false;
}
}
|
Artiom-M/xpiks
|
vendors/libthmbnlr/thumbnailcreator_stub.cpp
|
C++
|
mpl-2.0
| 375
|
create table coalescetest (id int,
age int,
name varchar(20));
insert into coalescetest values (1,20,'a');
insert into coalescetest(id,age) values (2,26);
insert into coalescetest(id,name) values (3,'c');
insert into coalescetest(id) values (4);
select avg(coalesce(age,38)) from coalescetest;
--detect the NULL value for column name
select id, coalesce(name,'user unknown') from coalescetest;
--detect the NULL value for column age
select id, coalesce(age,'age unknown') from coalescetest;
select id, coalesce(age,-1) from coalescetest;
--detect the NULL value for column age and name
select id, coalesce(name, age, 'unknown') from coalescetest;
SELECT COALESCE(NULL,'x');
---Coalesce in the where clause:
--select only the id where the name is unknown
select id, name, age from coalescetest where coalesce(name,'unknown') LIKE 'unknown';
--select the name where the id > age
select id, name, age from coalescetest where coalesce(id, 0) < coalesce(age, 1) and coalesce(name,'unknown') LIKE 'unknown';
drop table coalescetest;
|
zyzyis/monetdb
|
sql/test/coalesce.sql
|
SQL
|
mpl-2.0
| 1,074
|
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
import React, { useState } from 'react';
import { styled } from '@csegames/linaria/react';
const Hero = styled.div`
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
flex: 1 1 auto;
display: flex;
flex-direction: column;
align-content: stretch;
align-items: stretch;
justify-content: flex-start;
flex-wrap: nowrap;
user-select: none !important;
-webkit-user-select: none !important;
transition: opacity 2s ease;
`;
const Content = styled.div`
width: 100%;
height: 100%;
flex: 1 1 auto;
`;
const Video = styled.video`
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
object-fit: cover;
`;
export function ColossusHero(props: {}) {
const [isInitialVideo, setIsInitialVideo] = useState(true);
function onVideoEnded() {
setIsInitialVideo(false);
}
return (
<Hero>
<Content>
<Video src='videos/fsr-logo-4k-10q-loop.webm' poster='' onEnded={onVideoEnded} autoPlay={isInitialVideo} loop></Video>
{isInitialVideo && <Video src='videos/fsr-intro-4k-10q.webm' poster='images/cse/login-cse.jpg' onEnded={onVideoEnded} autoPlay></Video>}
</Content>
</Hero>
)
}
|
csegames/Camelot-Unchained
|
patcher/src/components/ColossusHero.tsx
|
TypeScript
|
mpl-2.0
| 1,382
|
/*
* Copyright © 2010-2011 Rebecca G. Bettencourt / Kreative Software
* <p>
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* <a href="http://www.mozilla.org/MPL/">http://www.mozilla.org/MPL/</a>
* <p>
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
* <p>
* Alternatively, the contents of this file may be used under the terms
* of the GNU Lesser General Public License (the "LGPL License"), in which
* case the provisions of LGPL License are applicable instead of those
* above. If you wish to allow use of your version of this file only
* under the terms of the LGPL License and not to allow others to use
* your version of this file under the MPL, indicate your decision by
* deleting the provisions above and replace them with the notice and
* other provisions required by the LGPL License. If you do not delete
* the provisions above, a recipient may use your version of this file
* under either the MPL or the LGPL License.
* @since KSFL 1.2
* @author Rebecca G. Bettencourt, Kreative Software
*/
package com.kreative.binpack;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
public class FPUtilities {
private FPUtilities() {}
public static int optimalSignWidth(int floatWidth) {
return (floatWidth > 0) ? 1 : 0;
}
public static int optimalExponentWidth(int floatWidth) {
if (floatWidth < 2) return 0;
else if (floatWidth < 4) return 1;
else if (floatWidth < 6) return 2;
else if (floatWidth < 8) return 3;
else if (floatWidth < 12) return 4;
else if (floatWidth < 20) return 5;
else if (floatWidth < 24) return 6;
else if (floatWidth < 32) return 7;
else if (floatWidth < 48) return 8;
else if (floatWidth < 56) return 9;
else if (floatWidth < 64) return 10;
else if (floatWidth < 80) return 11;
else if (floatWidth < 96) return 12;
else if (floatWidth < 112) return 13;
else if (floatWidth < 128) return 14;
else if (floatWidth < 160) return 15;
else if (floatWidth < 192) return 16;
else if (floatWidth < 224) return 17;
else if (floatWidth < 256) return 18;
else if (floatWidth < 320) return 19;
else if (floatWidth < 384) return 20;
else if (floatWidth < 448) return 21;
else if (floatWidth < 512) return 22;
else return 23;
}
public static int optimalMantissaWidth(int floatWidth) {
return (floatWidth > 2) ? (floatWidth - optimalExponentWidth(floatWidth) - 1) : 0;
}
public static int optimalBias(int exponentWidth) {
return ((1 << (exponentWidth - 1)) - 1);
}
public static BigInteger[] splitFloat(BigInteger rawFloat, int signWidth, int exponentWidth, int mantissaWidth) {
BigInteger rawSign = rawFloat.shiftRight(exponentWidth + mantissaWidth).and(BigInteger.ONE.shiftLeft(signWidth).subtract(BigInteger.ONE));
BigInteger rawExponent = rawFloat.shiftRight(mantissaWidth).and(BigInteger.ONE.shiftLeft(exponentWidth).subtract(BigInteger.ONE));
BigInteger rawMantissa = rawFloat.and(BigInteger.ONE.shiftLeft(mantissaWidth).subtract(BigInteger.ONE));
return new BigInteger[] { rawSign, rawExponent, rawMantissa };
}
public static BigInteger joinFloat(BigInteger rawSign, BigInteger rawExponent, BigInteger rawMantissa, int signWidth, int exponentWidth, int mantissaWidth) {
return (rawSign.and(BigInteger.ONE.shiftLeft(signWidth).subtract(BigInteger.ONE)).shiftLeft(exponentWidth + mantissaWidth))
.or(rawExponent.and(BigInteger.ONE.shiftLeft(exponentWidth).subtract(BigInteger.ONE)).shiftLeft(mantissaWidth))
.or(rawMantissa.and(BigInteger.ONE.shiftLeft(mantissaWidth).subtract(BigInteger.ONE)));
}
public static Number decodeFloat(BigInteger rawSign, BigInteger rawExponent, BigInteger rawMantissa, int signWidth, int exponentWidth, int mantissaWidth, int bias, MathContext mc) {
if (signWidth < 0 || signWidth > 1 || exponentWidth < 0 || mantissaWidth < 0) throw new IllegalArgumentException();
else if (rawExponent.compareTo(BigInteger.ZERO) == 0) {
// zero or subnormal
if (rawMantissa.compareTo(BigInteger.ZERO) == 0) {
// zero
// must use double, instead of BigDecimal, in order to preserve sign
boolean isNegative = (rawSign.compareTo(BigInteger.ZERO) != 0);
return isNegative ? -0.0 : 0.0;
} else {
// subnormal
boolean isNegative = (rawSign.compareTo(BigInteger.ZERO) != 0);
int negativeExponent = bias + mantissaWidth - 1;
BigDecimal mantissa = new BigDecimal(rawMantissa);
if (negativeExponent < 0) {
BigDecimal multiplier = BigDecimal.valueOf(2L).pow(-negativeExponent);
return isNegative ? mantissa.multiply(multiplier, mc).negate() : mantissa.multiply(multiplier, mc);
} else {
BigDecimal multiplier = BigDecimal.valueOf(2L).pow(negativeExponent);
return isNegative ? mantissa.divide(multiplier, mc).negate() : mantissa.divide(multiplier, mc);
}
}
} else if (rawExponent.compareTo(BigInteger.ONE.shiftLeft(exponentWidth).subtract(BigInteger.ONE)) == 0) {
// infinity or NaN
if (rawMantissa.compareTo(BigInteger.ZERO) == 0) {
// infinity
boolean isNegative = (rawSign.compareTo(BigInteger.ZERO) != 0);
return isNegative ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
} else {
// NaN
boolean isNegative = (rawSign.compareTo(BigInteger.ZERO) != 0);
boolean isQuietNaN = rawMantissa.testBit(mantissaWidth-1);
BigInteger mantissa = rawMantissa.clearBit(mantissaWidth-1);
long rawDouble = 0x7FF0000000000000L;
if (isNegative) rawDouble |= 0x8000000000000000L;
if (isQuietNaN) rawDouble |= 0x0008000000000000L;
rawDouble |= (mantissa.longValue() & 0x0007FFFFFFFFFFFFL);
return Double.longBitsToDouble(rawDouble);
}
} else {
// normal
boolean isNegative = (rawSign.compareTo(BigInteger.ZERO) != 0);
int negativeExponent = bias + mantissaWidth - rawExponent.intValue();
BigDecimal mantissa = new BigDecimal(rawMantissa.setBit(mantissaWidth));
if (negativeExponent < 0) {
BigDecimal multiplier = BigDecimal.valueOf(2L).pow(-negativeExponent);
return isNegative ? mantissa.multiply(multiplier, mc).negate() : mantissa.multiply(multiplier, mc);
} else {
BigDecimal multiplier = BigDecimal.valueOf(2L).pow(negativeExponent);
return isNegative ? mantissa.divide(multiplier, mc).negate() : mantissa.divide(multiplier, mc);
}
}
}
public static BigInteger[] encodeFloat(Number v, int signWidth, int exponentWidth, int mantissaWidth, int bias, MathContext mc) {
if (signWidth < 0 || signWidth > 1 || exponentWidth < 0 || mantissaWidth < 0) throw new IllegalArgumentException();
else if (v instanceof BigDecimal) {
BigDecimal d = (BigDecimal)v;
if (d.compareTo(BigDecimal.ZERO) == 0) {
return encodeZero(false, signWidth, exponentWidth, mantissaWidth);
} else {
return encodeFiniteNonZero(d, signWidth, exponentWidth, mantissaWidth, bias, mc);
}
} else if (v instanceof BigInteger) {
BigInteger i = (BigInteger)v;
if (i.compareTo(BigInteger.ZERO) == 0) {
return encodeZero(false, signWidth, exponentWidth, mantissaWidth);
} else {
return encodeFiniteNonZero(new BigDecimal(i), signWidth, exponentWidth, mantissaWidth, bias, mc);
}
} else if (v instanceof Double) {
double d = v.doubleValue();
if (Double.isNaN(d)) {
long rawDouble = Double.doubleToRawLongBits(d);
boolean isNegative = ((rawDouble & 0x8000000000000000L) != 0L);
boolean isQuietNaN = ((rawDouble & 0x0008000000000000L) != 0L);
long diagnosticCode = ((rawDouble & 0x0007FFFFFFFFFFFFL));
return encodeNaN(isNegative, isQuietNaN, diagnosticCode, signWidth, exponentWidth, mantissaWidth);
} else if (Double.isInfinite(d)) {
return encodeInfinity(d < 0.0, signWidth, exponentWidth, mantissaWidth);
} else if (d == 0.0) {
long rawDouble = Double.doubleToRawLongBits(d);
boolean isNegative = ((rawDouble & 0x8000000000000000L) != 0L);
return encodeZero(isNegative, signWidth, exponentWidth, mantissaWidth);
} else {
return encodeFiniteNonZero(BigDecimal.valueOf(d), signWidth, exponentWidth, mantissaWidth, bias, mc);
}
} else if (v instanceof Float) {
float f = v.floatValue();
if (Float.isNaN(f)) {
int rawFloat = Float.floatToRawIntBits(f);
boolean isNegative = ((rawFloat & 0x80000000) != 0);
boolean isQuietNaN = ((rawFloat & 0x00400000) != 0);
int diagnosticCode = ((rawFloat & 0x003FFFFF));
return encodeNaN(isNegative, isQuietNaN, diagnosticCode, signWidth, exponentWidth, mantissaWidth);
} else if (Float.isInfinite(f)) {
return encodeInfinity(f < 0.0f, signWidth, exponentWidth, mantissaWidth);
} else if (f == 0.0f) {
int rawFloat = Float.floatToRawIntBits(f);
boolean isNegative = ((rawFloat & 0x80000000) != 0);
return encodeZero(isNegative, signWidth, exponentWidth, mantissaWidth);
} else {
return encodeFiniteNonZero(new BigDecimal(Float.toString(f)), signWidth, exponentWidth, mantissaWidth, bias, mc);
}
} else if (v instanceof Long) {
long l = v.longValue();
if (l == 0l) {
return encodeZero(false, signWidth, exponentWidth, mantissaWidth);
} else {
return encodeFiniteNonZero(BigDecimal.valueOf(l), signWidth, exponentWidth, mantissaWidth, bias, mc);
}
} else if (v instanceof Integer || v instanceof Short || v instanceof Byte) {
int i = v.intValue();
if (i == 0) {
return encodeZero(false, signWidth, exponentWidth, mantissaWidth);
} else {
return encodeFiniteNonZero(BigDecimal.valueOf(i), signWidth, exponentWidth, mantissaWidth, bias, mc);
}
} else {
double d = v.doubleValue();
if (Double.isNaN(d)) {
long rawDouble = Double.doubleToRawLongBits(d);
boolean isNegative = ((rawDouble & 0x8000000000000000L) != 0L);
boolean isQuietNaN = ((rawDouble & 0x0008000000000000L) != 0L);
long diagnosticCode = ((rawDouble & 0x0007FFFFFFFFFFFFL));
return encodeNaN(isNegative, isQuietNaN, diagnosticCode, signWidth, exponentWidth, mantissaWidth);
} else if (Double.isInfinite(d)) {
return encodeInfinity(d < 0.0, signWidth, exponentWidth, mantissaWidth);
} else if (d == 0.0) {
long rawDouble = Double.doubleToRawLongBits(d);
boolean isNegative = ((rawDouble & 0x8000000000000000L) != 0L);
return encodeZero(isNegative, signWidth, exponentWidth, mantissaWidth);
} else {
return encodeFiniteNonZero(BigDecimal.valueOf(d), signWidth, exponentWidth, mantissaWidth, bias, mc);
}
}
}
private static BigInteger[] encodeNaN(boolean isNegative, boolean isQuietNaN, long diagnosticCode, int signWidth, int exponentWidth, int mantissaWidth) {
BigInteger mantissa = BigInteger.valueOf(diagnosticCode);
if (isQuietNaN) mantissa = mantissa.setBit(mantissaWidth-1);
else mantissa = mantissa.clearBit(mantissaWidth-1);
return new BigInteger[] {
(isNegative ? BigInteger.ONE.negate() : BigInteger.ZERO),
BigInteger.ONE.negate(),
mantissa
};
}
private static BigInteger[] encodeInfinity(boolean isNegative, int signWidth, int exponentWidth, int mantissaWidth) {
return new BigInteger[] {
(isNegative ? BigInteger.ONE.negate() : BigInteger.ZERO),
BigInteger.ONE.negate(),
BigInteger.ZERO
};
}
private static BigInteger[] encodeZero(boolean isNegative, int signWidth, int exponentWidth, int mantissaWidth) {
return new BigInteger[] {
(isNegative ? BigInteger.ONE.negate() : BigInteger.ZERO),
BigInteger.ZERO,
BigInteger.ZERO
};
}
private static BigInteger[] encodeFiniteNonZero(BigDecimal v, int signWidth, int exponentWidth, int mantissaWidth, int bias, MathContext mc) {
// writing floating-point numbers is HARD, especially when your big number library uses DECIMAL
boolean isNegative = (v.compareTo(BigDecimal.ZERO) < 0);
v = v.abs();
// this is the HARD part; as written, it still screws up sometimes (see evil trick)
int exponent = ilog2(v, mc) + bias;
// while loop is part of an evil trick
while (true) {
if (exponent >= ((1 << exponentWidth) - 1)) {
// overflow -> infinity
return new BigInteger[] {
(isNegative ? BigInteger.ONE.negate() : BigInteger.ZERO),
BigInteger.ONE.negate(),
BigInteger.ZERO
};
} else if (exponent <= 0) {
// underflow -> subnormal
int negativeExponent = bias + mantissaWidth - 1;
BigInteger mantissa;
if (negativeExponent < 0) {
BigDecimal multiplier = BigDecimal.valueOf(2L).pow(-negativeExponent);
mantissa = v.divide(multiplier, mc).setScale(0, mc.getRoundingMode()).toBigIntegerExact();
} else {
BigDecimal multiplier = BigDecimal.valueOf(2L).pow(negativeExponent);
mantissa = v.multiply(multiplier, mc).setScale(0, mc.getRoundingMode()).toBigIntegerExact();
}
if (mantissa.testBit(mantissaWidth)) {
// the other part of the evil trick
// this is essentially a GOTO! that's how evil this is!
exponent++;
continue;
} else {
return new BigInteger[] {
(isNegative ? BigInteger.ONE.negate() : BigInteger.ZERO),
BigInteger.ZERO,
mantissa
};
}
} else {
// normal
int negativeExponent = bias + mantissaWidth - exponent;
BigInteger mantissa;
if (negativeExponent < 0) {
BigDecimal multiplier = BigDecimal.valueOf(2L).pow(-negativeExponent);
mantissa = v.divide(multiplier, mc).setScale(0, mc.getRoundingMode()).toBigIntegerExact();
} else {
BigDecimal multiplier = BigDecimal.valueOf(2L).pow(negativeExponent);
mantissa = v.multiply(multiplier, mc).setScale(0, mc.getRoundingMode()).toBigIntegerExact();
}
if (!mantissa.testBit(mantissaWidth)) {
// the other part of the evil trick
// this is essentially a GOTO! that's how evil this is!
if (mantissa.testBit(mantissaWidth+1)) {
exponent++;
continue;
} else {
exponent--;
continue;
}
} else {
return new BigInteger[] {
(isNegative ? BigInteger.ONE.negate() : BigInteger.ZERO),
BigInteger.valueOf(exponent),
mantissa
};
}
}
}
}
private static int ilog2(BigDecimal v, MathContext mc) {
// provide a first approximation
// (v.precision()-v.scale()-1) is essentially the base-10 logarithm of v
// by multiplying this by 100000/30103 (dividing by 30103/100000, or log2(10) Å 0.30103)
// we can approximate the base 2 logarithm
// naively, this would give us 0, 0, 0, 0, 3, 3, 3, 6, 6, 6, 10, 10, 10, 10, etc.
// so we add the first digit of the (base-10) mantissa for a better approximation
int approximation = (int)(
(
((long)v.precision()-(long)v.scale()-1L)*100000L
+ (long)(v.unscaledValue().toString().charAt(0)-'0')*10000L
) / 30103L
);
// now go searching for the true logarithm
approximation += 3;
while (true) {
BigDecimal power = BigDecimal.valueOf(2L).pow(Math.abs(approximation));
if (approximation < 0) power = BigDecimal.ONE.divide(power, mc);
if (power.compareTo(v) <= 0) return approximation;
approximation--;
}
// WARNING: this will go into an infinite loop with n <= 0
// since this is a private method, we assume this has been checked beforehand
}
}
|
james-wallace-ghub/ydkjx
|
src/com/kreative/binpack/FPUtilities.java
|
Java
|
mpl-2.0
| 15,452
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.mozstumbler.client.mapview;
import android.location.Location;
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import org.mozilla.mozstumbler.service.AppGlobals;
import org.mozilla.mozstumbler.service.core.http.HttpUtil;
import org.mozilla.mozstumbler.service.core.http.IHttpUtil;
import org.mozilla.mozstumbler.service.core.http.ILocationService;
import org.mozilla.mozstumbler.service.core.http.IResponse;
import org.mozilla.mozstumbler.service.core.http.MLS;
import org.mozilla.mozstumbler.service.utils.LocationAdapter;
import java.util.concurrent.atomic.AtomicInteger;
/*
This class provides MLS locations by calling HTTP methods against the MLS.
*/
public class MLSLocationGetter extends AsyncTask<String, Void, Location> {
private static final String LOG_TAG = AppGlobals.LOG_PREFIX + MLSLocationGetter.class.getSimpleName();
private static final String RESPONSE_OK_TEXT = "ok";
private ILocationService mls;
private MLSLocationGetterCallback mCallback;
private byte[] mQueryMLSBytes;
private final int MAX_REQUESTS = 10;
private static AtomicInteger sRequestCounter = new AtomicInteger(0);
private boolean mIsBadRequest;
public interface MLSLocationGetterCallback {
void setMLSResponseLocation(Location loc);
void errorMLSResponse(boolean stopRequesting);
}
public MLSLocationGetter(MLSLocationGetterCallback callback, JSONObject mlsQueryObj) {
mCallback = callback;
mQueryMLSBytes = mlsQueryObj.toString().getBytes();
IHttpUtil httpUtil = new HttpUtil();
mls = new MLS(httpUtil);
}
@Override
public Location doInBackground(String... params) {
int requests = sRequestCounter.incrementAndGet();
if (requests > MAX_REQUESTS) {
return null;
}
IResponse resp = mls.search(mQueryMLSBytes, null, false);
if (resp == null) {
Log.i(LOG_TAG, "Error processing search request");
return null;
}
if (resp.isErrorCode400BadRequest()) {
//TODO detect malformed request, and clear out mlsrequest on observation point
mIsBadRequest = true;
return null;
}
JSONObject response;
try {
response = new JSONObject(resp.body());
} catch (JSONException e) {
Log.e(LOG_TAG, "Error deserializing JSON", e);
return null;
}
String status = "";
try {
status = response.getString("status");
} catch (JSONException ex) {
Log.e(LOG_TAG, "Error deserializing status from JSON");
return null;
}
if (!status.equals(RESPONSE_OK_TEXT)) {
return null;
}
return LocationAdapter.fromJSON(response);
}
@Override
protected void onPostExecute(Location location) {
sRequestCounter.decrementAndGet();
if (location == null) {
mCallback.errorMLSResponse(mIsBadRequest);
} else {
mCallback.setMLSResponseLocation(location);
}
}
}
|
garvankeeley/MozStumbler
|
android/src/main/java/org/mozilla/mozstumbler/client/mapview/MLSLocationGetter.java
|
Java
|
mpl-2.0
| 3,381
|
"""TxnReconcile allow txn_id to be null
Revision ID: 08b6358a04bf
Revises: 04e61490804b
Create Date: 2018-03-07 19:48:06.050926
"""
from alembic import op
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = '08b6358a04bf'
down_revision = '04e61490804b'
branch_labels = None
depends_on = None
def upgrade():
op.alter_column(
'txn_reconciles', 'txn_id',
existing_type=mysql.INTEGER(display_width=11),
nullable=True
)
def downgrade():
conn = op.get_bind()
conn.execute("SET FOREIGN_KEY_CHECKS=0")
op.alter_column(
'txn_reconciles', 'txn_id',
existing_type=mysql.INTEGER(display_width=11),
nullable=False
)
conn.execute("SET FOREIGN_KEY_CHECKS=1")
|
jantman/biweeklybudget
|
biweeklybudget/alembic/versions/08b6358a04bf_txnreconcile_allow_txn_id_to_be_null.py
|
Python
|
agpl-3.0
| 765
|
package florian_haas.lucas.security;
public enum EnumPermissionModule {
ACCOUNT("account"),
ATTENDANCE("attendance"),
COMPANY("company"),
EMPLOYMENT("employment"),
ENTITY("entity"),
GLOBAL_DATA("globalData"),
ID_CARD("idCard"),
ITEM("item"),
JOB("job"),
LOGIN("login"),
LOGIN_ROLE("loginRole"),
LOGIN_USER("loginUser"),
ROOM("room"),
USER("user");
private String moduleName;
private EnumPermissionModule(String moduleName) {
this.moduleName = moduleName;
}
public String getModuleName() {
return moduleName;
}
@Override
public String toString() {
return moduleName;
}
}
|
Listopia-Official/listopia-user-and-company-administration-system
|
lucas-ejbClient/ejbModule/florian_haas/lucas/security/EnumPermissionModule.java
|
Java
|
agpl-3.0
| 640
|
package gplx.core.log_msgs; import gplx.*; import gplx.core.*;
public class Gfo_msg_data {
public int Uid() {return uid;} int uid = uid_next++;
public Gfo_msg_itm Item() {return item;} Gfo_msg_itm item;
public Object[] Vals() {return vals;} Object[] vals;
public byte[] Src_bry() {return src_bry;} private byte[] src_bry;
public int Src_bgn() {return src_bgn;} int src_bgn;
public int Src_end() {return src_end;} int src_end;
public Gfo_msg_data Ctor_val_many(Gfo_msg_itm item, Object[] vals) {this.item = item; this.vals = vals; return this;}
public Gfo_msg_data Ctor_src_many(Gfo_msg_itm item, byte[] src_bry, int src_bgn, int src_end, Object[] vals) {this.item = item; this.src_bry = src_bry; this.src_bgn = src_bgn; this.src_end = src_end; this.vals = vals; return this;}
public void Clear() {
item = null; vals = null; src_bry = null;
}
public String Gen_str_ary() {return item.Gen_str_ary(vals);}
static int uid_next = 0;
public static final Gfo_msg_data[] Ary_empty = new Gfo_msg_data[0];
}
|
gnosygnu/xowa_android
|
_100_core/src/main/java/gplx/core/log_msgs/Gfo_msg_data.java
|
Java
|
agpl-3.0
| 1,030
|
from cl.api import views
from cl.audio import api_views as audio_views
from cl.people_db import api_views as judge_views
from cl.search import api_views as search_views
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
# Search & Audio
router.register(r'dockets', search_views.DocketViewSet)
router.register(r'courts', search_views.CourtViewSet)
router.register(r'audio', audio_views.AudioViewSet)
router.register(r'clusters', search_views.OpinionClusterViewSet)
router.register(r'opinions', search_views.OpinionViewSet)
router.register(r'opinions-cited', search_views.OpinionsCitedViewSet)
router.register(r'search', search_views.SearchViewSet, base_name='search')
# Judges
router.register(r'people', judge_views.PersonViewSet)
router.register(r'positions', judge_views.PositionViewSet)
router.register(r'retention-events', judge_views.RetentionEventViewSet)
router.register(r'educations', judge_views.EducationViewSet)
router.register(r'schools', judge_views.SchoolViewSet)
router.register(r'political-affiliations',
judge_views.PoliticalAffiliationViewSet)
router.register(r'sources', judge_views.SourceViewSet)
router.register(r'aba-ratings', judge_views.ABARatingViewSet)
urlpatterns = [
url(r'^api-auth/',
include('rest_framework.urls', namespace='rest_framework')),
url(r'^api/rest/(?P<version>[v3]+)/', include(router.urls)),
# Documentation
url(r'^api/$',
views.api_index,
name='api_index'),
url(r'^api/jurisdictions/$',
views.court_index,
name='court_index'),
url(r'^api/rest-info/(?P<version>v[123])?/?$',
views.rest_docs,
name='rest_docs'),
url(r'^api/bulk-info/$',
views.bulk_data_index,
name='bulk_data_index'),
url(r'^api/rest/v(?P<version>[123])/coverage/(?P<court>.+)/$',
views.coverage_data,
name='coverage_data'),
# Pagerank file
url(r'^api/bulk/external_pagerank/$',
views.serve_pagerank_file,
name='pagerank_file'),
# Deprecation Dates:
# v1: 2016-04-01
# v2: 2016-04-01
url(r'^api/rest/v(?P<v>[12])/.*',
views.deprecated_api,
name='deprecated_api'),
]
|
voutilad/courtlistener
|
cl/api/urls.py
|
Python
|
agpl-3.0
| 2,240
|
// Copyright 2010 - UDS/CNRS
// The Aladin program is distributed under the terms
// of the GNU General Public License version 3.
//
//This file is part of Aladin.
//
// Aladin 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 3 of the License.
//
// Aladin 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.
//
// The GNU General Public License is available in COPYING file
// along with Aladin.
//
package cds.aladin;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import javax.swing.JComboBox;
import javax.swing.SwingUtilities;
import cds.astro.Astrocoo;
import cds.astro.Astroframe;
import cds.astro.Coo;
import cds.astro.Ecliptic;
import cds.astro.FK4;
import cds.astro.FK5;
import cds.astro.Galactic;
import cds.astro.ICRS;
import cds.astro.Supergal;
import cds.tools.Util;
/**
* Classe gerant l'indication de position de la souris dans la vue
* Elle permet de choisir le repere. Etroitement associee a la classe
* LCoord
*
* @author Pierre Fernique [CDS]
* @version 1.1 : (12 dec 00) Gestion du champ de saisie rapide
* @version 1.0 : (10 mai 99) Toilettage du code
* @version 0.9 : (??) creation
* @see aladin.LCoord()
*/
public final class Localisation extends MyBox {
// les constantes associees a chaque repere
static final public int ICRS = 0;
static final public int ICRSD = 1;
static final public int ECLIPTIC = 2;
static final public int GAL = 3;
static final public int SGAL = 4;
static final public int J2000 = 5;
static final public int J2000D = 6;
static final public int B1950 = 7;
static final public int B1950D = 8;
static final public int B1900 = 9;
static final public int B1875 = 10;
static final public int XY = 11;
static final public int XYNAT = 12;
static final public int XYLINEAR = 13;
// Le label pour chaque repere (dans l'ordre des constantes ci-dessus)
static final String [] REPERE = {
"ICRS","ICRSd","Ecliptic","Gal","SGal",
"J2000","J2000d","B1950","B1950d","B1900","B1875",
"XY Fits","XY image","XY linear"
};
// Le mot clé RADECSYS Fits correspondant au système de coordonnée
static final String [] RADECSYS = {
"ICRS","ICRS",null,null,null,
"FK5","FK5","FK4","FK4","FK4","FK4",
null,null,null,
};
// Le préfixe du mot clé CTYPE1 Fits correspondant au système de coordonnée
static final String [] CTYPE1 = {
"RA---","RA---","ELON-","GLON-","SLON-",
"RA---","RA---","RA---","RA---","RA---","RA---",
null,null,"SOLAR",
};
// Le préfixe du mot clé CTYPE2 Fits correspondant au système de coordonnée
static final String [] CTYPE2 = {
"DEC--","DEC--","ELAT-","GLAT-","SLAT-",
"DEC--","DEC--","DEC--","DEC--","DEC--","DEC--",
null,null,"SOLAR",
};
// Les différents Frames possibles (mode AllSky)
static final String [] FRAME = { "Default", REPERE[ICRS], REPERE[ECLIPTIC], REPERE[GAL], REPERE[SGAL] };
static JComboBox createFrameCombo() {return new JComboBox(FRAME); }
// Les différents Frames possibles (pour la recalibration)
static final String [] FRAMEBIS = { "Equatorial", "Galactic", "Ecliptic", "SuperGal" };
static final int [] FRAMEBISVAL = { Calib.FK5, Calib.GALACTIC, Calib.ECLIPTIC, Calib.SUPERGALACTIC };
static final int [] FRAMEVAL = { ICRS, GAL, ECLIPTIC, SGAL };
static JComboBox createFrameComboBis() {return new JComboBox(FRAMEBIS); }
static int getFrameComboBisValue(String s) {
int i = Util.indexInArrayOf(s, FRAMEBIS, true);
if( i<0 ) return 0;
return FRAMEBISVAL[i];
}
static int getFrameComboValue(String s) {
int i = Util.indexInArrayOf(s, FRAMEBIS, true);
if( i<0 ) return 0;
return FRAMEVAL[i];
}
// Retourne true s'il s'agit du même système de référence (en ignorant la différence degrés et sexa)
static final boolean isSameFrame(int frame1,int frame2) {
if( frame1==ICRSD || frame1==J2000D || frame1==B1950D ) frame1--;
if( frame2==ICRSD || frame2==J2000D || frame2==B1950D ) frame2--;
return frame1==frame2;
}
static final String NOREDUCTION = "No astrometrical reduction";
static final String NOHPX = "No HEALPix map";
static final String NOPROJECTION = "No proj => select "+REPERE[XYLINEAR];
static final String NOXYLINEAR = "No XY linear trans.";
static protected String POSITION,YOUROBJ;
private int previousFrame=-1; // Frame précédent;
/* Pour gerer les changements de frame */
Astrocoo afs = new Astrocoo(AF_ICRS); // Frame ICRS (la reference de base)
/** Creation de l'objet de localisation. */
protected Localisation(Aladin aladin) {
super(aladin,aladin.chaine.getString("POSITION"));
String tip = aladin.chaine.getString("TIPPOS");
Util.toolTip(pos, tip);
Util.toolTip(label,tip);
Util.toolTip(text, aladin.chaine.getString("TIPCMD"));
Util.toolTip(c,aladin.chaine.getString("TIPPOSCHOICE"));
// c.setEnabled(false);
POSITION = aladin.chaine.getString("POSITION");
YOUROBJ = aladin.chaine.getString("YOUROBJ");
text.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
clearIfRequired();
}
public void keyReleased(KeyEvent e) {
clearIfRequired();
if( e.getKeyCode()==KeyEvent.VK_ENTER ) submit();
}
});
text.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
flagReadyToClear=false;
setMode(SAISIE);
}
});
pos.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
setMode(SAISIE);
}
});
text.requestFocusInWindow();
}
boolean first=true;
int posHist=-1;
/** Positionnement du texte qui sera affiché en mode de saisie */
protected void setTextSaisie(String s) {
first=true;
super.setTextSaisie(s);
text.select(0, text.getText().length());
}
/** La commande en cours reçoit un nouveau caractère */
protected void sendKey(KeyEvent e) {
int key = e.getKeyCode();
char k = e.getKeyChar();
if( e.isControlDown() || e.isAltDown() ) return;
clearIfRequired();
StringBuffer cmd = new StringBuffer(text.getText());
if( key==KeyEvent.VK_ENTER ) {
String s=shortCutLoad(cmd.toString());
aladin.execAsyncCommand(s);
first=true;
} else if( key==KeyEvent.VK_BACK_SPACE || key==KeyEvent.VK_DELETE ) {
first =false;
if( cmd.length()>0 ) cmd.deleteCharAt(cmd.length()-1);
// } else if( key==KeyEvent.VK_DOWN || key==KeyEvent.VK_UP) {
// first=true;
// String s = aladin.pad.getHistCommand(key);
// if( s!=null ) cmd = new StringBuffer(s);
// On insere un nouveau caractere
} else {
posHist = -1;
if( first ) { cmd.delete(0, cmd.length()); first=false; }
if( k>=31 && k<=255 || k=='@') cmd.append(k);
}
setMode(SAISIE);
String s = cmd.toString();
if( s.startsWith(aladin.GETOBJ) ) s = s.substring(aladin.GETOBJ.length());
super.setTextSaisie(s);
}
private boolean flagReadyToClear=false; // Indique que le champ de saisie est prêt à être effacé (voir testClear())
private boolean flagStopInfo=false; // Indique que l'info de démarrage doit s'arrêter immédiatement
/** Effacement du champ de saisie si on a pas cliqué dans le champ auparavant */
protected void clearIfRequired() {
flagStopInfo=true;
if( !flagReadyToClear ) return;
flagReadyToClear=false;
text.setText("");
}
/** Spécifie que le champ de saisie s'effacera à la prochaine frappe de clavier,
* sauf si on a cliqué dans le champ */
protected void readyToClear() {
flagReadyToClear=true;
}
protected void setMode(int mode ) {
super.setMode(mode);
if( mode==SAISIE ) /* text.requestFocusInWindow() */;
else {
ViewSimple v=aladin.view.getCurrentView();
if( v!=null && !v.hasFocus() ) v.requestFocusInWindow();
}
}
/** Fait clignoter le champ pour attirer l'attention
* de l'utilisateur et demande le focus sur le champ de saisie */
protected void focus(String s) { focus(s,null); }
protected void focus(String s,final String initial) {
setMode(SAISIE);
text.setText(s);
(new Thread() {
Color def = text.getBackground();
Color deff = text.getForeground();
public void run() {
for( int i=0; i<2; i++ ) {
text.setBackground(Color.green);
text.setForeground(Color.black);
Util.pause(1000);
text.setBackground(def);
text.setForeground(deff);
Util.pause(100);
}
if( initial==null ) {
text.setText("");
text.requestFocusInWindow();
} else {
text.setText(initial);
setInitialFocus();
}
}
}).start();
}
protected void setInitialFocus() {
setMode(SAISIE);
text.requestFocusInWindow();
text.setCaretPosition(text.getText().length());
}
protected void infoStart() {
if( !aladin.calque.isFree() || text.getText().length()>0 || aladin.dialog==null || aladin.dialog.isVisible() ) return;
setMode(SAISIE);
final String s = aladin.GETOBJ;
text.setText(s);
text.setFont(text.getFont().deriveFont(Font.ITALIC));
(new Thread() {
Color def = text.getBackground();
Color deff = text.getForeground();
public void run() {
flagReadyToClear=true;
text.setBackground(Color.white);
for( int i=0; i<3 && aladin.calque.isFree() && !flagStopInfo ; i++ ) {
if( !flagStopInfo ) {
text.setText("");
text.setForeground(Color.gray);
Util.pause(100);
}
if( !flagStopInfo ) {
text.setText(s);
Util.pause(1500);
}
}
if( flagStopInfo ) {
text.setCaretPosition(text.getText().length());
flagReadyToClear=flagStopInfo=false;
}
text.setText("");
text.setForeground(deff);
text.setFont(text.getFont().deriveFont(Font.BOLD));
text.requestFocusInWindow();
}
}).start();
}
protected JComboBox createSimpleChoice() {
return new JComboBox(REPERE);
}
protected JComboBox createChoice() {
final JComboBox c = super.createChoice();
c.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setInternalFrame(c.getSelectedIndex());
}
});
c.setPrototypeDisplayValue(new Integer(100000));
c.setFont(F);
for( int i=0; i<REPERE.length; i++ ) c.addItem(REPERE[i]);
// else for( int i=0; i<REPERE.length-1; i++ ) c.addItem(REPERE[i]);
c.setSelectedIndex(ICRS);
previousFrame=ICRS;
c.setMaximumRowCount(REPERE.length);
return c;
}
/**
* Positionnement du système de coordonnées
* @param s une valeur possible dans le menu déroulant des coord. (REPERE[])
* @return true si ok, false sinon
*/
protected boolean setPositionMode(String s) {
if( s.equalsIgnoreCase("xy") ) s = REPERE[XY]; // juste pour tolérer xy et XY
for( int i=0; i<REPERE.length; i++ ) {
if( !REPERE[i].equalsIgnoreCase(s) ) continue;
setFrame(i);
actionChoice();
return true;
}
return false;
}
private int frame = 0;
private void setInternalFrame(int frame) { this.frame=frame; }
/** Positionne le frame */
protected void setFrame(int frame) {
this.frame=frame;
setChoiceIndex(frame);
}
/** Retourne le nom du frame passé en paramètre */
protected String getFrameName() { return getFrameName(frame); }
static public String getFrameName(int frame) { return frame<0 ? "" : REPERE[frame]; }
/** Retourne la position du menu deroulant */
protected int getFrame() { return frame; }
/** Insère le résultat d'une résolution Sésame dans le champ de commande avec le label
* POSITION histoire que cela se comprenne */
protected void setSesameResult(String s) {
aladin.localisation.setTextSaisie(s);
aladin.localisation.readyToClear();
}
/** Affiche la position, en fonction du frame defini
* dans le menu deroulant
* @param x,y Les coordonnees de la souris dans la View
*/
private Coord coo = new Coord();
protected void setPos(ViewSimple v,double x,double y) { setPos(v,x,y,0); }
protected void setPos(ViewSimple v,double x,double y,int methode) { setPos(v,x,y,methode,false); }
protected void setPos(ViewSimple v,double x,double y,int methode,boolean sendPlasticMsg) {
int frame = getFrame();
// Forcage pour les nuage de point
ViewSimple view = aladin.view.getMouseView();
if( view!=null && view.isPlotView() ) frame=XYLINEAR;
Plan plan = v.pref;
if( plan==null ) return;
Projection proj = v.getProj();
PointD p = v.getPosition(x,y);
String s=null;
// Position (X,Y) simplement (mode FITS)
if( frame==XY || proj!=null && proj.modeCalib==Projection.NO ) {
if( plan.isImage() ) s=Util.myRound(""+(p.x+0.5),4)
+" "+Util.myRound(""+(((PlanImage)plan).naxis2-p.y+0.5),4);
else s="";
// Position (X,Y) simplement (mode Natif)
} else if( frame==XYNAT || proj!=null && proj.modeCalib==Projection.NO ) {
if( plan.isImage() ) s=Util.myRound(""+p.x,0)
+" "+Util.myRound(""+p.y,0);
else s="";
// Calcul de la projection
} else {
if( !Projection.isOk(proj) ) s=NOREDUCTION;
else {
coo.x = p.x;
coo.y = p.y;
proj.getCoord(coo);
if( Double.isNaN(coo.al) ) s="";
else if( frame==XYLINEAR ) {
if( !proj.isXYLinear() ) s=NOXYLINEAR;
else s=Util.myRound(coo.al+"",4)+" : "+Util.myRound(coo.del+"",4);
} else {
if( proj.isXYLinear() ) s=NOPROJECTION;
else {
// Gestion de la précision en fonction du champ
double r = v.getTailleRA();
int precision = r==0.0 ? Astrocoo.ARCMIN :
r> 0.001 ? Astrocoo.ARCSEC+1 :
r > 0.00001 ?Astrocoo.MAS-1 :
Astrocoo.MAS+1;
s=J2000ToString(coo.al,coo.del,precision);
if( Aladin.PLASTIC_SUPPORT && sendPlasticMsg ) {
aladin.getMessagingMgr().pointAtCoords(coo.al, coo.del);
}
}
}
}
}
lastPosition = s==NOREDUCTION ? "" : s;
//Affichage du resultat
if( methode==1 ) {
// Aladin.copyToClipBoard(s); C'EST VRAIMENT TROP GONFLANT
setTextSaisie(s);
setMode(SAISIE);
} else {
setTextAffichage(s);
setMode(AFFICHAGE);
}
}
private String lastPosition="";
protected String getLastPosition() { return lastPosition; }
protected Coord getLastCoord() { return coo; }
static final Astroframe AF_FK4 = new FK4();
static final Astroframe AF_FK5 = new FK5();
static final Astroframe AF_GAL = new Galactic();
static final Astroframe AF_SGAL = new Supergal();
static final Astroframe AF_ICRS = new ICRS();
static final Astroframe AF_ECLI = new Ecliptic();
static final Astroframe AF_FK4_1900 = new FK4(1900);
static final Astroframe AF_FK4_1875 = new FK4(1875);
// Retourne la valeur du frame prevue dans Astroframe
// en fonction de la valeur courante du menu deroulant
static protected Astroframe getAstroframe(int i) {
return (i==ICRS || i==ICRSD )?AF_ICRS:
(i==GAL)?AF_GAL:
(i==J2000 || i==J2000D)?AF_FK5:
(i==B1950 || i==B1950D)?AF_FK4:
(i==B1900)?AF_FK4_1900:
(i==B1875)?AF_FK4_1875:
(i==ECLIPTIC)?AF_ECLI:
(i==SGAL)?AF_SGAL:AF_ICRS;
}
// static protected Coord frameToFrame1(Coord c, int frameSrc,int frameDst) {
// if( frameSrc==frameDst ) return c;
// Astrocoo aft = new Astrocoo(Localisation.getAstroframe(frameSrc),c.al,c.del);
// aft.convertTo(Localisation.getAstroframe(frameDst));
// c.al=aft.getLon();
// c.del=aft.getLat();
// return c;
// }
public static Coord frameToFrame(Coord c, int frameSrc,int frameDst) {
if( frameSrc==frameDst ) return c;
Coo cTmp = new Coo(c.al,c.del);
if( frameSrc!=ICRS && frameSrc!=ICRSD ) Localisation.getAstroframe(frameSrc).toICRS(cTmp);
if( frameDst!=ICRS && frameDst!=ICRSD ) Localisation.getAstroframe(frameDst).fromICRS(cTmp);
c.al = cTmp.getLon();
c.del= cTmp.getLat();
return c;
}
protected Coord ICRSToFrame(Coord c) {
if( frame==ICRS || frame==ICRSD ) return c;
return frameToFrame(c,ICRS,frame);
}
protected Coord frameToICRS(Coord c) {
if( frame==ICRS || frame==ICRSD ) return c;
return frameToFrame(c,frame,ICRS);
}
/** Mise en forme des coordonnees en ICRS sexa */
protected String getICRSCoord(String coo) {
if( coo.length()==0 ) return coo;
return convert(coo, frame, ICRS );
}
/** Mise en forme des coordonnees dans le frame courant */
protected String getFrameCoord(String coo) {
return convert(coo, ICRS, frame);
}
/** Conversion et/ou mise en forme de coordonnées
* @param coo coordonnées ou identificateur
* @param frameSource numéro du système de référence source : ICRS, ICRSd...
* @param frameTarget numéro du système de référence cible
* @return les coordonnées éditées dans le système cible, ou l'identificateur inchangé
*/
static protected String convert(String coo,int frameSource,int frameTarget) {
// Champ vide => Rien à faire
if( coo==null || coo.length()==0 || coo.indexOf("--")>=0 ) return "";
// Identificateur à la place d'une coordonnée => Rien à faire
for( int i=0; i<coo.length(); i++) {
char ch = coo.charAt(i);
if( (ch>='A' && ch<='Z') || (ch>='a' && ch<='z') ) return coo;
}
// Edition et conversion si nécessaire
try {
Astrocoo aft = new Astrocoo( getAstroframe(frameSource) );
aft.setPrecision(Astrocoo.MAS+3);
aft.set(coo);
if( frameSource!=frameTarget ) aft.convertTo( getAstroframe(frameTarget) );
String s = (frameTarget==J2000D || frameTarget==B1950D || frameTarget==ICRSD
|| frameTarget==ECLIPTIC || frameTarget==GAL || frameTarget==SGAL )?
aft.toString("2d"):aft.toString("2s");
//if( frameSource!=frameTarget ) {
// System.out.println("convert ["+coo+"]/"+Localisation.REPERE[frameSource]+" => ["+s+"]/"+Localisation.REPERE[frameTarget]);
////try { throw new Exception("convert"); } catch(Exception e) { e.printStackTrace(); }
//}
if( s.indexOf("--")>=0 ) return "";
return s;
} catch( Exception e ) { e.printStackTrace(); return coo; }
}
/** Retourne la position d'un objet en fonction du frame
* courant
* @param al,del : coordonnees (ICRS)
* @return La chaine decrivant la position
*/
protected String J2000ToString(double al,double del) { return J2000ToString(al,del,Astrocoo.ARCSEC+1); }
protected String J2000ToString(double al,double del,int precision) {
Coord cTmp = new Coord(al,del);
cTmp = ICRSToFrame(cTmp);
afs.setPrecision(precision);
return frameToString(cTmp.al,cTmp.del,precision);
}
protected String frameToString(double al,double del) { return frameToString(al,del,Astrocoo.ARCSEC+1); }
protected String frameToString(double al,double del,int precision) {
int i = getFrame();
afs.setPrecision(precision);
afs.set(al,del);
try {
return (i==J2000D || i==B1950D || i==ICRSD
|| i==ECLIPTIC || i==GAL || i==SGAL )?
afs.toString("2d"):afs.toString("2:");
} catch( Exception e) { System.err.println(e); }
return "";
}
/** Indication de la position d'une source.
* (en fonction du repere courant)
* @param o La source
* @param methode 0 dans pos, 1 dans text (memorisation+clipboard)
*/
protected void seeCoord(Position o) { seeCoord(o,0); }
protected void seeCoord(Position o,int methode) {
String s=getLocalisation(o);
if( s==null ) return;
if( methode==0 ) { setTextAffichage(s); setMode(AFFICHAGE); }
else {
// aladin.copyToClipBoard(s); //POSE TROP DE PROBLEME
setTextSaisie(s);
setMode(SAISIE);
aladin.console.printInPad(s+"\n");
}
}
/** Localisation de la source en fonction du frame courant */
protected String getLocalisation(Obj o) {
String s="";
int frame = getFrame();
switch( frame ) {
case XY:
ViewSimple v = aladin.view.getCurrentView();
Projection proj = v.getProj();
Coord c = new Coord(o.getRa(),o.getDec());
proj.getXY(c);
double x = c.x;
double y = c.y;
Plan plan = v.pref;
if( plan.isImage() ) s=Util.myRound(""+(x+0.5),2)
+" "+Util.myRound(""+(((PlanImage)plan).naxis2-(y-0.5)),2);
else s=null;
break;
default : s = s+ J2000ToString(o.getRa(),o.getDec());
}
return s;
}
// retourne true s'il s'agit d'un nom de fichier local
private boolean isFile(String s) {
File f = new File(aladin.getFullFileName(s));
return f.canRead();
}
// Petit raccourci pour insérer "load " devant une url ou un nom de fichier
private String shortCutLoad(String s) {
if( s.startsWith("http://") || s.startsWith("https://")
|| s.startsWith("ftp://") || s.startsWith("file://")
|| isFile(s) ) {
s = "load "+s;
setTextSaisie(s);
}
return s;
}
/** Gere la validation du champ de saisie rapide. */
private void submit() {
String s = getTextSaisie();
if( s.length()>0 ) {
s=shortCutLoad(s);
aladin.console.pushCmd(s);
}
readyToClear();
}
protected void actionChoice() {
if( text==null ) return;
try {
aladin.calque.resumeFrame();
previousFrame=getFrame();
// Change la dernière coordonnée mémorisée
setTextSaisie( convert(getTextSaisie(),previousFrame,getFrame()));
} catch( Exception e ) { if( Aladin.levelTrace>=3 ) e.printStackTrace(); }
}
}
|
jankotek/asterope
|
aladin/cds/aladin/Localisation.java
|
Java
|
agpl-3.0
| 23,904
|
# -*- coding: utf-8 -*-
# Akvo RSR is covered by the GNU Affero General Public License.
# See more details in the license.txt file located at the root folder of the Akvo RSR module.
# For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >.
from django.contrib.auth import get_user_model
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from akvo.rsr.forms import (check_password_minimum_length, check_password_has_number,
check_password_has_upper, check_password_has_lower,
check_password_has_symbol)
from akvo.rsr.models import ProjectHierarchy
from .employment import EmploymentSerializer
from .organisation import (
OrganisationExtraSerializer, OrganisationBasicSerializer, UserManagementOrgSerializer)
from .program import ProgramSerializer
from .rsr_serializer import BaseRSRSerializer
class UserRawSerializer(BaseRSRSerializer):
"""
Raw user serializer.
"""
class Meta:
model = get_user_model()
fields = (
'id',
'first_name',
'last_name',
'email',
'is_active',
'is_staff',
'is_admin',
'is_support',
'is_superuser',
)
class UserSerializer(BaseRSRSerializer):
# Needed to show only the first organisation of the user
organisation = OrganisationExtraSerializer(source='first_organisation', required=False,)
organisations = OrganisationExtraSerializer(many=True, required=False,)
user_management_organisations = UserManagementOrgSerializer(many=True, required=False)
approved_employments = EmploymentSerializer(many=True, required=False,)
api_key = serializers.ReadOnlyField(source='get_api_key')
# Legacy fields to support Tastypie API emulation
legacy_org = serializers.SerializerMethodField()
username = serializers.SerializerMethodField()
can_manage_users = serializers.SerializerMethodField()
programs = serializers.SerializerMethodField()
class Meta:
model = get_user_model()
fields = (
'id',
'first_name',
'last_name',
'email',
'username',
'is_active',
'is_staff',
'is_admin',
'is_support',
'is_superuser',
'can_manage_users',
'organisation',
'organisations',
'approved_employments',
'api_key',
'legacy_org',
'programs',
'user_management_organisations',
'seen_announcements',
)
def __init__(self, *args, **kwargs):
""" Delete the 'absolute_url' field added in BaseRSRSerializer.__init__().
It's neither correct nor do we want this data to be visible.
Remove the fields "legacy_org" and "username" that are only present to support older
versions of Up calling the Tastypie API endpoints that we now emulate using DRF
"""
super(UserSerializer, self).__init__(*args, **kwargs)
del self.fields['absolute_url']
# Remove the fields unless we're called via Tastypie URLs
request = kwargs.get("context", {}).get("request", None)
if request and "/api/v1/" not in request.path:
del self.fields['legacy_org']
del self.fields['username']
def get_legacy_org(self, obj):
""" Up needs the last tag to be the user's org, it only needs the org ID
"""
if obj.first_organisation():
return {"object": {"id": obj.first_organisation().id}}
return None
def get_username(self, obj):
return obj.email
def get_can_manage_users(self, obj):
return obj.has_perm('rsr.user_management')
def get_programs(self, user):
hierarchies = ProjectHierarchy.objects.select_related('root_project')\
.prefetch_related('root_project__partners').all()
if not (user.is_superuser or user.is_admin):
hierarchies = hierarchies.filter(root_project__in=user.my_projects()).distinct()
return ProgramSerializer(hierarchies, many=True, context=self.context).data
class UserPasswordSerializer(serializers.Serializer):
"""Change password serializer"""
old_password = serializers.CharField(
help_text='Current Password',
)
new_password1 = serializers.CharField(
help_text='New Password',
)
new_password2 = serializers.CharField(
help_text='New Password (confirmation)',
)
class Meta:
fields = '__all__'
def validate_old_password(self, value):
"""Check for current password"""
if not self.instance.check_password(value):
raise serializers.ValidationError(_('Old password is not correct.'))
return value
def validate(self, data):
"""Check if password1 and password2 match"""
if data['new_password1'] != data['new_password2']:
raise serializers.ValidationError(_('Passwords do not match.'))
password = data['new_password1']
check_password_minimum_length(password)
check_password_has_number(password)
check_password_has_upper(password)
check_password_has_lower(password)
check_password_has_symbol(password)
return data
def update(self, instance, validated_data):
instance.set_password(validated_data.get('new_password2', instance.password))
return instance
class UserDetailsSerializer(BaseRSRSerializer):
approved_organisations = OrganisationBasicSerializer(many=True, required=False)
email = serializers.ReadOnlyField()
class Meta:
model = get_user_model()
fields = (
'id',
'email',
'first_name',
'last_name',
'approved_organisations',
)
def __init__(self, *args, **kwargs):
""" Delete the 'absolute_url' field added in BaseRSRSerializer.__init__().
It's neither correct nor do we want this data to be visible.
"""
super(UserDetailsSerializer, self).__init__(*args, **kwargs)
del self.fields['absolute_url']
|
akvo/akvo-rsr
|
akvo/rest/serializers/user.py
|
Python
|
agpl-3.0
| 6,303
|
<?php
// Set page title and set crumbs to index
set_page_title(lang('clients'));
if(owner_company()->canAddClient(logged_user())) {
add_page_action(lang('add company'), get_url('company', 'add_client'), 'ico-add');
} // if
?>
<div class="adminClients" style="height:100%;background-color:white">
<div class="adminHeader">
<div class="adminTitle"><?php echo lang('clients') ?></div>
</div>
<div class="adminSeparator"></div>
<div class="adminMainBlock">
<?php if(isset($clients) && is_array($clients) && count($clients)) { ?>
<table style="min-width:400px;margin-top:10px;">
<tr>
<th><?php echo lang('name') ?></th>
<th><?php echo lang('users') ?></th>
<th><?php echo lang('options') ?></th>
</tr>
<?php
$isAlt = true;
foreach($clients as $client) {
$isAlt = !$isAlt;?>
<tr class="<?php echo $isAlt? 'altRow' : ''?>">
<td><a class="internalLink" href="<?php echo $client->getViewUrl() ?>"><?php echo clean($client->getName()) ?></a></td>
<td style="text-align: center"><?php echo $client->countUsers() ?></td>
<?php
$options = array();
if($client->canAddUser(logged_user())) {
$options[] = '<a class="internalLink" href="' . $client->getAddUserUrl() . '">' . lang('add user') . '</a>';
} // if
if($client->canUpdatePermissions(logged_user())) {
$options[] = '<a class="internalLink" href="' . $client->getUpdatePermissionsUrl() . '">' . lang('permissions') . '</a>';
} // if
if($client->canEdit(logged_user())) {
$options[] = '<a class="internalLink" href="' . $client->getEditUrl() . '">' . lang('edit') . '</a>';
} // if
if($client->canDelete(logged_user())) {
$options[] = '<a class="internalLink" href="' . $client->getDeleteClientUrl() . '" onclick="return confirm(\'' . escape_single_quotes(lang('confirm delete client')) . '\')">' . lang('delete') . '</a>';
} // if
?>
<td style="font-size:80%;"><?php echo implode(' | ', $options) ?></td>
</tr>
<?php } // foreach ?>
</table>
<?php } else { ?>
<?php echo lang('no clients in company') ?>
<?php } // if ?>
</div>
</div>
|
yanlingling/xnjs
|
application/views/administration/clients.php
|
PHP
|
agpl-3.0
| 2,135
|
/*
Copyright (c) 2010, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.com/yui/license.html
version: 3.3.0
build: 3167
*/
YUI.add("lang/datatype-date-format_es-PY",function(a){a.Intl.add("datatype-date-format","es-PY",{"a":["dom","lun","mar","mié","jue","vie","sáb"],"A":["domingo","lunes","martes","miércoles","jueves","viernes","sábado"],"b":["ene","feb","mar","abr","may","jun","jul","ago","sep","oct","nov","dic"],"B":["enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre"],"c":"%a, %d %b %Y %H:%M:%S %Z","p":["A.M.","P.M."],"P":["a.m.","p.m."],"x":"%d/%m/%y","X":"%H:%M:%S"});},"3.3.0");YUI.add("lang/datatype-date_es-PY",function(a){},"3.3.0",{use:["lang/datatype-date-format_es-PY"]});YUI.add("lang/datatype_es-PY",function(a){},"3.3.0",{use:["lang/datatype-date_es-PY"]});
|
RajkumarSelvaraju/FixNix_CRM
|
jssource/src_files/include/javascript/yui3/build/datatype/lang/datatype_es-PY.js
|
JavaScript
|
agpl-3.0
| 895
|
#!/usr/bin/env bash
if [ $# -lt 3 ]; then
echo "usage: $0 <db-name> <db-user> <db-pass> [db-host] [wp-version]"
exit 1
fi
DB_NAME=$1
DB_USER=$2
DB_PASS=$3
DB_HOST=${4-localhost}
WP_VERSION=${5-latest}
WP_TESTS_DIR=${WP_TESTS_DIR-/tmp/wordpress-tests-lib}
WP_CORE_DIR=${WP_CORE_DIR-/tmp/wordpress/}
set -ex
download() {
if [ `which curl` ]; then
curl -s "$1" > "$2";
elif [ `which wget` ]; then
wget -nv -O "$2" "$1"
fi
}
install_wp() {
if [ -d $WP_CORE_DIR ]; then
return;
fi
mkdir -p $WP_CORE_DIR
if [ $WP_VERSION == 'latest' ]; then
local ARCHIVE_NAME='latest'
else
local ARCHIVE_NAME="wordpress-$WP_VERSION"
fi
download https://wordpress.org/${ARCHIVE_NAME}.tar.gz /tmp/wordpress.tar.gz
tar --strip-components=1 -zxmf /tmp/wordpress.tar.gz -C $WP_CORE_DIR
download https://raw.github.com/markoheijnen/wp-mysqli/master/db.php $WP_CORE_DIR/wp-content/db.php
}
install_test_suite() {
# portable in-place argument for both GNU sed and Mac OSX sed
if [[ $(uname -s) == 'Darwin' ]]; then
local ioption='-i .bak'
else
local ioption='-i'
fi
# set up testing suite if it doesn't yet exist
if [ ! "$(ls -A $WP_TESTS_DIR)" ]; then
# set up testing suite
mkdir -p $WP_TESTS_DIR
svn co --quiet http://develop.svn.wordpress.org/trunk/tests/phpunit/includes/ $WP_TESTS_DIR
fi
cd $WP_TESTS_DIR
if [ ! -f wp-tests-config.php ]; then
download https://develop.svn.wordpress.org/trunk/wp-tests-config-sample.php wp-tests-config.php
sed $ioption "s:dirname( __FILE__ ) . '/src/':'$WP_CORE_DIR':" wp-tests-config.php
sed $ioption "s/youremptytestdbnamehere/$DB_NAME/" wp-tests-config.php
sed $ioption "s/yourusernamehere/$DB_USER/" wp-tests-config.php
sed $ioption "s/yourpasswordhere/$DB_PASS/" wp-tests-config.php
sed $ioption "s|localhost|${DB_HOST}|" wp-tests-config.php
fi
}
install_db() {
# parse DB_HOST for port or socket references
local PARTS=(${DB_HOST//\:/ })
local DB_HOSTNAME=${PARTS[0]};
local DB_SOCK_OR_PORT=${PARTS[1]};
local EXTRA=""
if ! [ -z $DB_HOSTNAME ] ; then
if [ $(echo $DB_SOCK_OR_PORT | grep -e '^[0-9]\{1,\}$') ]; then
EXTRA=" --host=$DB_HOSTNAME --port=$DB_SOCK_OR_PORT --protocol=tcp"
elif ! [ -z $DB_SOCK_OR_PORT ] ; then
EXTRA=" --socket=$DB_SOCK_OR_PORT"
elif ! [ -z $DB_HOSTNAME ] ; then
EXTRA=" --host=$DB_HOSTNAME --protocol=tcp"
fi
fi
# create database
mysqladmin create $DB_NAME --user="$DB_USER" --password="$DB_PASS"$EXTRA
}
install_wp
install_test_suite
install_db
|
corajr/wp-zotero-sync
|
bin/install-wp-tests.sh
|
Shell
|
agpl-3.0
| 2,514
|
package org.yamcs.parameterarchive;
import java.io.PrintStream;
import org.junit.Ignore;
import org.junit.Test;
import org.yamcs.utils.TimeEncoding;
import org.yamcs.yarch.YarchDatabase;
public class PrintStats {
@Ignore
@Test
public void test1() throws Exception {
TimeEncoding.setUp();
YarchDatabase.setHome("/storage/yamcs-data");
ParameterArchive parchive = new ParameterArchive("aces-ops");
PrintStream ps = new PrintStream("/tmp/aces-ops6-stats.txt");
PrintStream ps1 = new PrintStream("/storage/aces-ops-stats/aces-ops6-paraid.txt");
parchive.printKeys(ps);
parchive.getParameterIdDb().print(ps1);
ps1.close();
ps.close();
parchive.close();
}
}
|
dhosa/yamcs
|
yamcs-core/src/test/java/org/yamcs/parameterarchive/PrintStats.java
|
Java
|
agpl-3.0
| 760
|
# ubuntu:14.04 as of 2017-11-15
FROM ubuntu@sha256:f6eed4def93a3b54da920737f0abf1a8cae2e480bb368280c898265fcaf910a3
RUN apt-get update # 2017-11-15
RUN apt-get install -y \
python-pip libpython2.7-dev libssl-dev secure-delete gnupg2 ruby redis-server
# refs securedrop/issues/1594
RUN gem install sass -v 3.4.23
# test requirements:
RUN apt-get install -y firefox
RUN apt-get install -y git xvfb haveged curl gettext paxctl
RUN apt-get install -y x11vnc
# pinned firefox version for selenium compatibility. See bd795e2f5865b4f6e6e1b88bcbbacef704675c74
ENV FIREFOX_CHECKSUM=88d25053306d33658580973b063cd459a56e3596a3a298c1fb8ab1d52171d860
RUN curl -LO https://launchpad.net/~ubuntu-mozilla-security/+archive/ubuntu/ppa/+build/9727836/+files/firefox_46.0.1+build1-0ubuntu0.14.04.3_amd64.deb && \
shasum -a 256 firefox*deb && \
echo "${FIREFOX_CHECKSUM} firefox_46.0.1+build1-0ubuntu0.14.04.3_amd64.deb" | shasum -a 256 -c - && \
dpkg -i firefox*deb && apt-get install -f && \
paxctl -cm /usr/lib/firefox/firefox
#
# This can be removed when upgrading to something more recent than trusty
#
RUN echo deb http://archive.ubuntu.com/ubuntu/ xenial main > /etc/apt/sources.list.d/xenial.list
RUN apt-get update
RUN apt-get install -y gettext
RUN rm /etc/apt/sources.list.d/xenial.list
RUN apt-get update
COPY requirements requirements
RUN pip install -r requirements/securedrop-app-code-requirements.txt
# test requirements:
RUN pip install -r requirements/test-requirements.txt
WORKDIR /app
COPY static static
COPY sass sass
RUN sass --force --stop-on-error --update sass:static/css --style compressed
RUN mkdir -p /var/lib/securedrop/store /var/lib/securedrop/keys
COPY ./tests/files/test_journalist_key.pub /var/lib/securedrop/keys
RUN gpg --homedir /var/lib/securedrop/keys --import /var/lib/securedrop/keys/test_journalist_key.pub
COPY . /app
RUN make test-config
RUN ./manage.py reset
EXPOSE 8080 8081
EXPOSE 5901
CMD ["./manage.py", "run"]
|
garrettr/securedrop
|
securedrop/Dockerfile
|
Dockerfile
|
agpl-3.0
| 1,971
|
package com.github._1element.sc.properties; //NOSONAR
import org.apache.commons.io.FileUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* Configuration properties for SFTP remote copy.
*/
@Component
@ConfigurationProperties("sc.remotecopy.sftp")
public class SFTPRemoteCopyProperties {
private boolean enabled;
private String host;
private String dir = "/";
private String username;
private String password;
private boolean cleanupEnabled = false;
private long cleanupMaxDiskSpace;
private int cleanupKeep;
public boolean isEnabled() {
return enabled;
}
public void setEnabled(final boolean enabled) {
this.enabled = enabled;
}
public String getHost() {
return host;
}
public void setHost(final String host) {
this.host = host;
}
public String getDir() {
return dir;
}
public void setDir(final String dir) {
this.dir = dir;
}
public String getUsername() {
return username;
}
public void setUsername(final String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(final String password) {
this.password = password;
}
public boolean isCleanupEnabled() {
return cleanupEnabled;
}
public void setCleanupEnabled(final boolean cleanupEnabled) {
this.cleanupEnabled = cleanupEnabled;
}
public long getCleanupMaxDiskSpace() {
return cleanupMaxDiskSpace;
}
public void setCleanupMaxDiskSpace(final long cleanupMaxDiskSpace) {
this.cleanupMaxDiskSpace = FileUtils.ONE_MB * cleanupMaxDiskSpace;
}
public int getCleanupKeep() {
return cleanupKeep;
}
public void setCleanupKeep(final int cleanupKeep) {
this.cleanupKeep = cleanupKeep;
}
}
|
1element/sc
|
src/main/java/com/github/_1element/sc/properties/SFTPRemoteCopyProperties.java
|
Java
|
agpl-3.0
| 1,848
|
/* This file is part of VoltDB.
* Copyright (C) 2008-2013 VoltDB Inc.
*
* 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 VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltdb;
public enum SysProcSelector {
TABLE, // invoked as @stat table
INDEX, // invoked as @stat index
PROCEDURE, // invoked as @stat procedure
STARVATION,
INITIATOR, // invoked as @stat initiator
LATENCY, // invoked as @stat latency
PARTITIONCOUNT,
IOSTATS,
MEMORY, // info about node's memory usage
LIVECLIENTS, // info about the currently connected clients
PLANNER, // info about planner and EE performance and cache usage
MANAGEMENT, //Returns pretty much everything
SNAPSHOTSTATUS,
/*
* DRPARTITION and DRNODE are internal names
* Externally the selector is just "DR"
*/
DRPARTITION,
DRNODE,
TOPO // return leader and site info for iv2
}
|
kobronson/cs-voltdb
|
src/frontend/org/voltdb/SysProcSelector.java
|
Java
|
agpl-3.0
| 1,568
|
linguas.directive('bunchRow', ['$window', 'TranslationService',
function ($window, TranslationService) {
return {
restrict: 'AE',
replace: true,
scope: {
bunch: '=bunch'
},
templateUrl: 'app/features/translation-bunch/bunch-row/bunch-row.html',
controller: function ($scope) {
}
};
}]);
|
asm-products/linguas
|
app/features/translation-bunch/bunch-row/bunch-row.js
|
JavaScript
|
agpl-3.0
| 349
|
/*
PogoLocationFeeder gathers pokemon data from various sources and serves it to connected clients
Copyright (C) 2016 PogoLocationFeeder Development Team <admin@pokefeeder.live>
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/>.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading;
using PogoLocationFeeder.Config;
using PogoLocationFeeder.Helper;
namespace PogoLocationFeeder.Readers
{
public class DiscordWebReader
{
public Stream stream;
public DiscordWebReader()
{
InitializeWebClient();
}
//private WebClient Wc { get; set; }
public void InitializeWebClient()
{
var request = WebRequest.Create(new Uri("http://pogo-feed.mmoex.com/messages"));
((HttpWebRequest) request).AllowReadStreamBuffering = false;
try
{
var response = request.GetResponse();
Log.Info($"Connection established. Waiting for data...");
GlobalSettings.Output?.SetStatus($"Connected to discord feed");
stream = response.GetResponseStream();
}
catch (WebException)
{
Log.Warn($"Experiencing connection issues. Throttling...");
Thread.Sleep(30*1000);
}
catch (Exception e)
{
Log.Warn($"Exception: {e}\n\n\n");
}
}
public class AuthorStruct
{
public string id;
}
public class DiscordMessage
{
public string channel_id = "";
public AuthorStruct author;
public string content = "";
public string id = "";
public string timestamp = "";
//public string edited_timestamp = null;
public bool tts = false;
//public string mentions = "";
//public string nonce = "";
//public bool deleted = false;
//public bool pinned = false;
//public bool mention_everyone = false;
//public string mention_roles = "";
//public xxx attachments = "";
//public xxx embeds = "";
}
}
}
|
5andr0/PogoLocationFeeder
|
PogoLocationFeeder/Readers/DiscordWebReader.cs
|
C#
|
agpl-3.0
| 2,854
|
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Snackbar from 'material-ui/Snackbar';
import { Route } from 'react-router';
import { store } from '..';
import { isConfigLoaded, getConfig } from '../modules/config';
import AppBar from './AppBar';
import Dashboard from './Dashboard';
import Drawer from './Drawer';
import FailureDialog from './FailureDialog';
import ItemEditor from './ItemEditor';
import Loans from './Loans';
import MainView from './MainView';
import Places from './Places';
import Settings from './Settings';
import SpeedDial from './SpeedDial';
import StuffList from './StuffList';
import Team from './Team';
import timings from '../styles/timings';
import User from './User';
class App extends React.Component {
static propTypes = {
failed: PropTypes.bool,
snackbarMessage: PropTypes.string,
getConfig: PropTypes.func.isRequired,
}
static defaultProps = {
failed: false,
snackbarMessage: '',
}
componentDidMount = () => {
if (!isConfigLoaded(store.getState())) {
this.props.getConfig();
}
}
render() {
const { failed, snackbarMessage } = this.props;
if (failed) {
return <FailureDialog />;
} else {
return (
<div>
<AppBar />
<Drawer />
<MainView>
<Route path="/" component={Dashboard} />
<Route path="/stuff" component={StuffList} />
<Route path="/stuff/:itemSlug" component={ItemEditor} />
<Route path="/places" component={Places} />
<Route path="/loans" component={Loans} />
<Route path="/settings" component={Settings} />
<Route path="/user" component={User} />
<Route path="/team" component={Team} />
</MainView>
<SpeedDial />
{snackbarMessage ? (
<Snackbar
open
message={snackbarMessage}
autoHideDuration={timings.snackbarCloseTimeout}
/>
) : null}
</div>
);
}
}
}
export default connect(
state => ({
failed: state.tallessa.getIn(['config', 'failed']),
snackbarMessage: state.tallessa.getIn(['ui', 'snackbar']),
}),
{
getConfig,
},
)(App);
|
tallessa/tallessa-frontend
|
src/components/App.js
|
JavaScript
|
agpl-3.0
| 2,288
|
var clover = new Object();
// JSON: {classes : [{name, id, sl, el, methods : [{sl, el}, ...]}, ...]}
clover.pageData = {"classes":[{"el":54,"id":84685,"methods":[{"el":40,"sc":2,"sl":38},{"el":45,"sc":2,"sl":42},{"el":52,"sc":2,"sl":47}],"name":"EscapeHTML","sl":33}]}
// JSON: {test_ID : {"methods": [ID1, ID2, ID3...], "name" : "testXXX() void"}, ...};
clover.testTargets = {}
// JSON: { lines : [{tests : [testid1, testid2, testid3, ...]}, ...]};
clover.srcFileLines = [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]
|
cm-is-dog/rapidminer-studio-core
|
report/html/com/rapidminer/tools/expression/internal/function/text/EscapeHTML.js
|
JavaScript
|
agpl-3.0
| 697
|
using wServer.networking.packets;
using wServer.networking.packets.incoming;
using wServer.realm;
namespace wServer.networking.handlers
{
class PongHandler : PacketHandlerBase<Pong>
{
public override PacketId ID => PacketId.PONG;
protected override void HandlePacket(Client client, Pong packet)
{
client.Manager.Logic.AddPendingAction(t => Handle(client, packet, t));
}
private void Handle(Client client, Pong packet, RealmTime t)
{
client.Player?.Pong(t, packet);
}
}
}
|
cp-nilly/NR-CORE
|
wServer/networking/handlers/PongHandler.cs
|
C#
|
agpl-3.0
| 569
|
/*
* opencog/spatial/math/Plane.h
*
* Copyright (C) 2002-2009 Novamente LLC
* All Rights Reserved
* Author(s): Samir Araujo
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef _SPATIAL_MATH_PLANE_H_
#define _SPATIAL_MATH_PLANE_H_
#include <string>
#include <opencog/util/exceptions.h>
#include <opencog/spatial/math/Vector3.h>
#include <opencog/spatial/math/Matrix4.h>
namespace opencog
{
/** \addtogroup grp_spatial
* @{
*/
namespace spatial
{
namespace math {
class Plane
{
public:
/**
* Classifies the sides of the plane
*/
enum SIDE {
NEGATIVE,
POSITIVE,
INTERSECT
};
/**
* Simple constructor
*/
Plane( void );
/**
* Copy constructor
* @param plane
*/
Plane( const Plane& plane );
/**
* Use a normal and a distance from origin to build a plane
* @param normal
* @param distance
*/
Plane( const Vector3& normal, double distance );
/**
* Build a plane using three arbitrary points
* @param pointA
* @param pointB
* @param pointC
*/
Plane( const Vector3& pointA, const Vector3& pointB, const Vector3& pointC );
/**
* Set new normal and distance values to this plane
* @param normal
* @param distance
*/
void set( const Vector3& normal, double distance );
/**
* Get a 4 dimension vector that represents this plane
* @return
*/
Vector4 getVector4( void );
/**
* Get the distance between this plane and a given point
* @param point
* @return
*/
double getDistance( const Vector3& point );
/**
* Identifies the side of the plane a given point is positioned
* @param point
* @return
*/
SIDE getSide( const Vector3& point );
/**
* Apply a transformation matrix to this plane
* @param transformation
*/
void transformSelf( const Matrix4& transformation );
/**
* Get the intersection point between this plane and other two
* @param plane2
* @param plane3
* @return
*/
Vector3 getIntersectionPoint( const Plane& plane2, const Plane& plane3 );
/*
*
*/
bool operator==( const Plane& other ) const;
/*
*
*/
std::string toString(void) const;
inline virtual ~Plane( void ) { }
Vector3 normal;
double distanceFromOrigo;
}; // Plane
} // math
} // spatial
/** @}*/
} // opencog
#endif // _SPATIAL_MATH_PLANE_H_
|
misgeatgit/opencog
|
opencog/spatial/math/Plane.h
|
C
|
agpl-3.0
| 4,162
|
.ColorButton-transparency {
background-color: #ccc;
background-position: 50% 50%;
border-radius: 3px;
}
.ColorButton-color {
height: 100%;
position: relative;
border-radius: 3px;
}
.ColorButton-opaque {
position: absolute;
top: 0;
right: 0;
bottom: 0;
width: 50%;
border-radius: 0 3px 3px 0;
}
|
qliavi/touch-paint
|
run/css/ColorButton.css
|
CSS
|
agpl-3.0
| 344
|
spree_commerce
==============
Required fields for Spree Commerce endpoint integration
|
OpenSolutionsFinland/spree_commerce
|
README.md
|
Markdown
|
agpl-3.0
| 87
|
/*
* This file is part of Splice Machine.
* Splice Machine 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, or (at your option) any later version.
* Splice Machine 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 Splice Machine.
* If not, see <http://www.gnu.org/licenses/>.
*
* Some parts of this source code are based on Apache Derby, and the following notices apply to
* Apache Derby:
*
* Apache Derby is a subproject of the Apache DB project, and is licensed under
* the Apache License, Version 2.0 (the "License"); you may not use these files
* 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.
*
* Splice Machine, Inc. has modified the Apache Derby code in this file.
*
* All such Splice Machine modifications are Copyright 2012 - 2020 Splice Machine, Inc.,
* and are licensed to you under the GNU Affero General Public License.
*/
package com.splicemachine.dbTesting.functionTests.tests.jdbc4;
import junit.framework.*;
import com.splicemachine.dbTesting.junit.BaseJDBCTestCase;
import com.splicemachine.dbTesting.junit.CleanDatabaseTestSetup;
import com.splicemachine.dbTesting.junit.JDBC;
import com.splicemachine.dbTesting.functionTests.util.streams.LoopingAlphabetStream;
import com.splicemachine.dbTesting.junit.TestConfiguration;
import java.io.*;
import java.sql.*;
import com.splicemachine.db.iapi.services.io.DerbyIOException;
import com.splicemachine.db.impl.jdbc.EmbedSQLException;
/**
* This class is used to test JDBC4 specific methods in the PreparedStatement(s)
* object.
*
* A number of methods and variables are in place to aid the writing of tests:
* <ul><li>setBinaryStreamOnBlob
* <li>setAsciiStream
* <li>key - an id. One is generated each time setUp is run.
* <li>reqeustKey() - generate a new unique id.
* <li>psInsertX - prepared statements for insert.
* <li>psFetchX - prepared statements for fetching values.
* </ul>
*
* For table creation, see the <code>suite</code>-method.
*/
public class PreparedStatementTest extends BaseJDBCTestCase {
private static final String BLOBTBL = "BlobTestTable";
private static final String CLOBTBL = "ClobTestTable";
private static final String LONGVARCHAR = "LongVarcharTestTable";
/** Key used to id data inserted into the database. */
private static int globalKey = 1;
/** Byte array passed in to the database. **/
private static final byte[] BYTES = {
0x65, 0x66, 0x67, 0x68, 0x69,
0x69, 0x68, 0x67, 0x66, 0x65
};
// Default connection and prepared statements that are used by the tests.
/**
* Default key to use for insertions.
* Is unique for each fixture. More keys can be fetched by calling
* <link>requestKey</link>.
*/
private int key;
/** Default connection object. */
/** PreparedStatement object with no positional arguments. */
private PreparedStatement ps = null;
/** PreparedStatement to fetch BLOB with specified id. */
private PreparedStatement psFetchBlob = null;
/** PreparedStatement to insert a BLOB with specified id. */
private PreparedStatement psInsertBlob = null;
/** PreparedStatement to fetch CLOB with specified id. */
private PreparedStatement psFetchClob = null;
/** PreparedStatement to insert a CLOB with specified id. */
private PreparedStatement psInsertClob = null;
/** PreparedStatement to insert a LONG VARCHAR with specified id. */
private PreparedStatement psInsertLongVarchar = null;
//Statement object
private Statement s = null;
/**
* Create a test with the given name.
*
* @param name name of the test.
*/
public PreparedStatementTest(String name) {
super(name);
}
/**
*
* Obtain a "regular" connection and PreparedStatement that the tests
* can use.
*
* @throws SQLException
*/
public void setUp()
throws SQLException {
key = requestKey();
//create the statement object
s = createStatement();
//Create the PreparedStatement that will then be used as the basis
//throughout this test henceforth
//This prepared statement will however NOT be used for testing
//setClob and setBlob
ps = prepareStatement("select count(*) from sys.systables");
// Prepare misc statements.
psFetchBlob = prepareStatement("SELECT dBlob FROM " +
BLOBTBL + " WHERE sno = ?");
psInsertBlob = prepareStatement("INSERT INTO " + BLOBTBL +
" VALUES (?, ?)");
psFetchClob = prepareStatement("SELECT dClob FROM " +
CLOBTBL + " WHERE sno = ?");
psInsertClob = prepareStatement("INSERT INTO " + CLOBTBL +
" VALUES (?, ?)");
psInsertLongVarchar = prepareStatement("INSERT INTO " + LONGVARCHAR +
" VALUES (?, ?)");
}
/**
*
* Release the resources that are used in this test
*
* @throws SQLException
*
*/
public void tearDown()
throws Exception {
s.close();
ps.close();
s = null;
ps = null;
psFetchBlob.close();
psFetchClob.close();
psInsertBlob.close();
psInsertClob.close();
psInsertLongVarchar.close();
psFetchBlob = null;
psFetchClob = null;
psInsertBlob = null;
psInsertClob = null;
psInsertLongVarchar = null;
super.tearDown();
}
public static Test suite() {
TestSuite suite = new TestSuite("PreparedStatementTest suite");
suite.addTest(baseSuite("PreparedStatementTest:embedded"));
suite.addTest(
TestConfiguration.connectionXADecorator(
baseSuite("PreparedStatementTest:embedded XADataSource")));
suite.addTest(TestConfiguration.clientServerDecorator(
baseSuite("PreparedStatementTest:client")));
// Tests for the client side JDBC statement cache.
suite.addTest(TestConfiguration.clientServerDecorator(
statementCachingSuite()));
suite.addTest(
TestConfiguration.clientServerDecorator(
TestConfiguration.connectionXADecorator(
baseSuite("PreparedStatementTest:client XXXXADataSource"))));
return suite;
}
private static Test baseSuite(String name) {
TestSuite suite = new TestSuite(name);
suite.addTestSuite(PreparedStatementTest.class);
return new CleanDatabaseTestSetup(suite) {
protected void decorateSQL(Statement stmt) throws SQLException
{
stmt.execute("create table " + BLOBTBL +
" (sno int, dBlob BLOB(1M))");
stmt.execute("create table " + CLOBTBL +
" (sno int, dClob CLOB(1M))");
stmt.execute("create table " + LONGVARCHAR +
" (sno int, dLongVarchar LONG VARCHAR)");
}
};
}
/**
* Returns a suite for tests that need JDBC statement caching to be enabled.
*/
private static Test statementCachingSuite() {
TestSuite suite = new TestSuite("JDBC statement caching suite");
suite.addTest(new PreparedStatementTest("cpTestIsPoolableHintFalse"));
suite.addTest(new PreparedStatementTest("cpTestIsPoolableHintTrue"));
return TestConfiguration.connectionCPDecorator(
new CleanDatabaseTestSetup(suite) {
protected void decorateSQL(Statement stmt)
throws SQLException {
stmt.execute("create table " + BLOBTBL +
" (sno int, dBlob BLOB(1M))");
stmt.execute("create table " + CLOBTBL +
" (sno int, dClob CLOB(1M))");
stmt.execute("create table " + LONGVARCHAR +
" (sno int, dLongVarchar LONG VARCHAR)");
}
});
}
//--------------------------------------------------------------------------
//BEGIN THE TEST OF THE METHODS THAT THROW AN UNIMPLEMENTED EXCEPTION IN
//THIS CLASS
/**
* Tests the setRowId method of the PreparedStatement interface
*
* @throws SQLException upon any failure that occurs in the
* call to the method.
*/
public void testSetRowId() throws SQLException{
try {
RowId rowid = null;
ps.setRowId(0,rowid);
fail("setRowId should not be implemented");
}
catch(SQLFeatureNotSupportedException sqlfne) {
//Do Nothing, This happens as expected
}
}
/**
* Tests the setNString method of the PreparedStatement interface
*
* @throws SQLException upon any failure that occurs in the
* call to the method.
*/
public void testSetNString() throws SQLException{
try {
String str = null;
ps.setNString(0,str);
fail("setNString should not be implemented");
}
catch(SQLFeatureNotSupportedException sqlfne) {
//Do Nothing, This happens as expected
}
}
/**
* Tests the setNCharacterStream method of the PreparedStatement interface
*
* @throws SQLException upon any failure that occurs in the
* call to the method.
*/
public void testSetNCharacterStream() throws SQLException{
try {
Reader r = null;
ps.setNCharacterStream(0,r,0);
fail("setNCharacterStream should not be implemented");
}
catch(SQLFeatureNotSupportedException sqlfne) {
//Do Nothing, This happens as expected
}
}
public void testSetNCharacterStreamLengthlessNotImplemented()
throws SQLException {
try {
ps.setNCharacterStream(1, new StringReader("A string"));
fail("setNCharacterStream(int,Reader) should not be implemented");
} catch (SQLFeatureNotSupportedException sfnse) {
// Do nothing, this is expected behavior.
}
}
public void testSetNClobLengthlessNotImplemented()
throws SQLException {
try {
ps.setNClob(1, new StringReader("A string"));
fail("setNClob(int,Reader) should not be implemented");
} catch (SQLFeatureNotSupportedException sfnse) {
// Do nothing, this is expected behaviour.
}
}
/**
* Tests the setNClob method of the PreparedStatement interface
*
* @throws SQLException upon any failure that occurs in the
* call to the method.
*/
public void testSetNClob1() throws SQLException{
try {
NClob nclob = null;
ps.setNClob(0,nclob);
fail("setNClob should not be implemented");
}
catch(SQLFeatureNotSupportedException sqlfne) {
//Do Nothing, This happens as expected
}
}
/**
* Tests the setNClob method of the PreparedStatement interface
*
* @throws SQLException upon any failure that occurs in the
* call to the method.
*/
public void testSetNClob2() throws SQLException{
try {
Reader reader = null;
ps.setNClob(0,reader,0);
fail("setNClob should not be implemented");
}
catch(SQLFeatureNotSupportedException sqlfne) {
//Do Nothing, This happens as expected
}
}
/**
* Tests the setSQLXML method of the PreparedStatement interface
*
* @throws SQLException upon any failure that occurs in the
* call to the method.
*/
public void testSetSQLXML() throws SQLException{
try {
SQLXML sqlxml = null;
ps.setSQLXML(0,sqlxml);
fail("setNClob should not be implemented");
}
catch(SQLFeatureNotSupportedException sqlfne) {
//Do Nothing, This happens as expected
}
}
//--------------------------------------------------------------------------
//Now test the methods that are implemented in the PreparedStatement
//interface
public void testIsWrapperForStatement() throws SQLException {
assertTrue(ps.isWrapperFor(Statement.class));
}
public void testIsWrapperForPreparedStatement() throws SQLException {
assertTrue(ps.isWrapperFor(PreparedStatement.class));
}
public void testIsNotWrapperForCallableStatement() throws SQLException {
assertFalse(ps.isWrapperFor(CallableStatement.class));
}
public void testIsNotWrapperForResultSet() throws SQLException {
assertFalse(ps.isWrapperFor(ResultSet.class));
}
public void testUnwrapStatement() throws SQLException {
Statement stmt = ps.unwrap(Statement.class);
assertSame("Unwrap returned wrong object.", ps, stmt);
}
public void testUnwrapPreparedStatement() throws SQLException {
PreparedStatement ps2 = ps.unwrap(PreparedStatement.class);
assertSame("Unwrap returned wrong object.", ps, ps2);
}
public void testUnwrapCallableStatement() {
try {
CallableStatement cs = ps.unwrap(CallableStatement.class);
fail("Unwrap didn't fail.");
} catch (SQLException e) {
assertSQLState("XJ128", e);
}
}
public void testUnwrapResultSet() {
try {
ResultSet rs = ps.unwrap(ResultSet.class);
fail("Unwrap didn't fail.");
} catch (SQLException e) {
assertSQLState("XJ128", e);
}
}
//-----------------------------------------------------------------------
// Begin test for setClob and setBlob
/*
we need a table in which a Clob or a Blob can be stored. We basically
need to write tests for the setClob and the setBlob methods.
Proper process would be
a) Do a createClob or createBlob
b) Populate data in the LOB
c) Store in Database
But the createClob and createBlob implementations are not
available on the EmbeddedServer. So instead the workaround adopted
is
a) store a Clob or Blob in Database.
b) Retrieve it from the database.
c) store it back using setClob or setBlob
*/
/**
*
* Test the setClob() method
*
* @throws SQLException if a failure occurs during the call to setClob
*
*/
public void testSetClob()
throws IOException, SQLException {
// Life span of Clob objects are limited by the transaction. Need
// autocommit off so Clob objects survive execution of next statement.
getConnection().setAutoCommit(false);
//insert default values into the table
String str = "Test data for the Clob object";
StringReader is = new StringReader("Test data for the Clob object");
is.reset();
//initially insert the data
psInsertClob.setInt(1, key);
psInsertClob.setClob(2, is, str.length());
psInsertClob.executeUpdate();
//Now query to retrieve the Clob
psFetchClob.setInt(1, key);
ResultSet rs = psFetchClob.executeQuery();
rs.next();
Clob clobToBeInserted = rs.getClob(1);
rs.close();
//Now use the setClob method
int secondKey = requestKey();
psInsertClob.setInt(1, secondKey);
psInsertClob.setClob(2, clobToBeInserted);
psInsertClob.execute();
psInsertClob.close();
//Now test to see that the Clob has been stored correctly
psFetchClob.setInt(1, secondKey);
rs = psFetchClob.executeQuery();
rs.next();
Clob clobRetrieved = rs.getClob(1);
assertEquals(clobToBeInserted,clobRetrieved);
}
/**
* Insert <code>Clob</code> without specifying length and read it back
* for verification.
*
* @throws IOException If an IOException during the close operation on the
* reader.
* @throws SQLException If an SQLException occurs.
*/
public void testSetClobLengthless()
throws IOException, SQLException {
// Life span of Clob objects are the transaction. Need autocommit off
// to have Clob objects survive execution of next statement.
getConnection().setAutoCommit(false);
//Create the Clob and insert data into it.
Clob insertClob = getConnection().createClob();
OutputStream os = insertClob.setAsciiStream(1);
os.write(BYTES);
//Insert the Clob created above into the
//database.
psInsertClob.setInt(1, key);
psInsertClob.setClob(2, insertClob);
psInsertClob.execute();
// Read back test data from database.
psFetchClob.setInt(1, key);
ResultSet rs = psFetchClob.executeQuery();
assertTrue("No results retrieved", rs.next());
Clob clobRetrieved = rs.getClob(1);
// Verify test data.
assertEquals(insertClob, clobRetrieved);
}
/**
*
* Test the setBlob() method
*
* @throws SQLException if a failure occurs during the call to setBlob
*
*/
public void testSetBlob()
throws IOException, SQLException {
// Life span of Blob objects are limited by the transaction. Need
// autocommit off so Blob objects survive execution of next statement.
getConnection().setAutoCommit(false);
//insert default values into the table
InputStream is = new java.io.ByteArrayInputStream(BYTES);
is.reset();
//initially insert the data
psInsertBlob.setInt(1, key);
psInsertBlob.setBlob(2, is, BYTES.length);
psInsertBlob.executeUpdate();
//Now query to retrieve the Blob
psFetchBlob.setInt(1, key);
ResultSet rs = psFetchBlob.executeQuery();
rs.next();
Blob blobToBeInserted = rs.getBlob(1);
rs.close();
//Now use the setBlob method
int secondKey = requestKey();
psInsertBlob.setInt(1, secondKey);
psInsertBlob.setBlob(2, blobToBeInserted);
psInsertBlob.execute();
psInsertBlob.close();
//Now test to see that the Blob has been stored correctly
psFetchBlob.setInt(1, secondKey);
rs = psFetchBlob.executeQuery();
rs.next();
Blob blobRetrieved = rs.getBlob(1);
assertEquals(blobToBeInserted, blobRetrieved);
}
/**
* Insert <code>Blob</code> without specifying length and read it back
* for verification.
*/
public void testSetBlobLengthless()
throws IOException, SQLException {
// Life span of Blob objects are the transaction. Need autocommit off
// to have Blob objects survive execution of next statement.
getConnection().setAutoCommit(false);
// Create Blob to be inserted
Blob insertBlob = getConnection().createBlob();
OutputStream os = insertBlob.setBinaryStream(1);
os.write(BYTES);
int secondKey = requestKey();
psInsertBlob.setInt(1, secondKey);
psInsertBlob.setBlob(2, insertBlob);
psInsertBlob.execute();
os.close();
psInsertBlob.close();
// Read back test data from database.
psFetchBlob.setInt(1, secondKey);
ResultSet rs = psFetchBlob.executeQuery();
assertTrue("No results retrieved", rs.next());
Blob blobRetrieved = rs.getBlob(1);
// Verify test data.
assertEquals(insertBlob, blobRetrieved);
}
//-------------------------------------------------
//Test the methods used to test poolable statements
/**
*
* Tests the PreparedStatement interface method setPoolable
*
* @throws SQLException
*/
public void testSetPoolable() throws SQLException {
// Set the poolable statement hint to false
ps.setPoolable(false);
assertFalse("Expected a non-poolable statement", ps.isPoolable());
// Set the poolable statement hint to true
ps.setPoolable(true);
assertTrue("Expected a non-poolable statement", ps.isPoolable());
}
/**
*
* Tests the PreparedStatement interface method setPoolable on a closed
* PreparedStatement
*
* @throws SQLException
*/
public void testSetPoolableOnClosed() throws SQLException {
try {
ps.close();
// Set the poolable statement hint to false
ps.setPoolable(false);
fail("Expected an exception on closed statement");
} catch(SQLException sqle) {
// Check which SQLException state we've got and if it is
// expected, do not print a stackTrace
// Embedded uses XJ012, client uses XCL31.
if (sqle.getSQLState().equals("XJ012") ||
sqle.getSQLState().equals("XCL31")) {
// All is good and is expected
} else {
fail("Unexpected SQLException " + sqle);
}
}
}
/**
*
* Tests the PreparedStatement interface method isPoolable
*
* @throws SQLException
*
*/
public void testIsPoolableDefault() throws SQLException {
// By default a prepared statement is poolable
assertTrue("Expected a poolable statement", ps.isPoolable());
}
/**
* Tests that the {@code isPoolable}-hint works by exploiting the fact that
* the client cannot prepare a statement referring to a deleted table
* (unless the statement is already in the statement cache).
*
* @throws SQLException if something goes wrong...
*/
public void cpTestIsPoolableHintFalse()
throws SQLException {
getConnection().setAutoCommit(false);
// Create a table, insert a row, then create a statement selecting it.
Statement stmt = createStatement();
stmt.executeUpdate("create table testispoolablehint (id int)");
stmt.executeUpdate("insert into testispoolablehint values 1");
PreparedStatement ps = prepareStatement(
"select * from testispoolablehint");
ps.setPoolable(false);
JDBC.assertSingleValueResultSet(ps.executeQuery(), "1");
// Close statement, which should be discarded.
ps.close();
// Now delete the table.
stmt.executeUpdate("drop table testispoolablehint");
stmt.close();
// Since there is no cached statement, we'll get exception here.
try {
ps = prepareStatement("select * from testispoolablehint");
fail("Prepared statement not valid, referring non-existing table");
} catch (SQLException sqle) {
assertSQLState("42X05", sqle);
}
}
/**
* Tests that the {@code isPoolable}-hint works by exploiting the fact that
* the client can prepare a statement referring to a deleted table if JDBC
* statement caching is enabled and the statement is already in the cache.
*
* @throws SQLException if something goes wrong...
*/
public void cpTestIsPoolableHintTrue()
throws SQLException {
getConnection().setAutoCommit(false);
// Create a table, insert a row, then create a statement selecting it.
Statement stmt = createStatement();
stmt.executeUpdate("create table testispoolablehint (id int)");
stmt.executeUpdate("insert into testispoolablehint values 1");
PreparedStatement ps = prepareStatement(
"select * from testispoolablehint");
ps.setPoolable(true);
JDBC.assertSingleValueResultSet(ps.executeQuery(), "1");
// Put the statement into the cache.
ps.close();
// Now delete the table and fetch the cached prepared statement.
stmt.executeUpdate("drop table testispoolablehint");
stmt.close();
ps = prepareStatement("select * from testispoolablehint");
// If we get this far, there is a big change we have fetched an
// invalid statement from the cache, but we won't get the exception
// until we try to execute it.
try {
ps.executeQuery();
fail("Prepared statement not valid, referring non-existing table");
} catch (SQLException sqle) {
assertSQLState("42X05", sqle);
}
}
/**
*
* Tests the PreparedStatement interface method isPoolable on closed
* PreparedStatement
*
* @throws SQLException
*
*/
public void testIsPoolableOnClosed() throws SQLException {
try {
ps.close();
boolean p = ps.isPoolable();
fail("Should throw exception on closed statement");
} catch(SQLException sqle) {
// Check which SQLException state we've got and if it is
// expected, do not print a stackTrace
// Embedded uses XJ012, client uses XCL31.
if (sqle.getSQLState().equals("XJ012") ||
sqle.getSQLState().equals("XCL31")) {
// All is good and is expected
} else {
fail("Unexpected SQLException " + sqle);
}
}
}
/**
*
* Tests the PreparedStatement interface method setCharacterStream
*
* @throws SQLException
*
*/
public void testSetCharacterStream() throws Exception {
String str = "Test data for the Clob object";
StringReader is = new StringReader("Test data for the Clob object");
is.reset();
//initially insert the data
psInsertClob.setInt(1, key);
psInsertClob.setCharacterStream(2, is, str.length());
psInsertClob.executeUpdate();
//Now query to retrieve the Clob
psFetchClob.setInt(1, key);
ResultSet rs = psFetchClob.executeQuery();
rs.next();
Clob clobRetrieved = rs.getClob(1);
String str_out = clobRetrieved.getSubString(1L,(int)clobRetrieved.length());
assertEquals("Error in inserting data into the Clob object",str,str_out);
psInsertClob.close();
//Since auto-commit is true in this test
//this will invalidate the clob object
//Hence closing the ResultSet after
//accessing the Clob object.
//follows the same pattern as testSetBinaryStream().
rs.close();
}
public void testSetCharacterStreamLengthless()
throws IOException, SQLException {
// Insert test data.
String testString = "Test string for setCharacterStream\u1A00";
Reader reader = new StringReader(testString);
psInsertClob.setInt(1, key);
psInsertClob.setCharacterStream(2, reader);
psInsertClob.execute();
reader.close();
// Read back test data from database.
psFetchClob.setInt(1, key);
ResultSet rs = psFetchClob.executeQuery();
assertTrue("No results retrieved", rs.next());
Clob clobRetrieved = rs.getClob(1);
// Verify test data.
assertEquals("Mismatch test data in/out", testString,
clobRetrieved.getSubString(1, testString.length()));
}
/**
*
* Tests the PreparedStatement interface method setAsciiStream
*
* @throws SQLException
*
*/
public void testSetAsciiStream() throws Exception {
//insert default values into the table
byte [] bytes1 = new byte[10];
InputStream is = new java.io.ByteArrayInputStream(BYTES);
is.reset();
//initially insert the data
psInsertClob.setInt(1, key);
psInsertClob.setAsciiStream(2, is, BYTES.length);
psInsertClob.executeUpdate();
//Now query to retrieve the Clob
psFetchClob.setInt(1, key);
ResultSet rs = psFetchClob.executeQuery();
rs.next();
Clob ClobRetrieved = rs.getClob(1);
try {
InputStream is_ret = ClobRetrieved.getAsciiStream();
is_ret.read(bytes1);
} catch(IOException ioe) {
fail("IOException while reading the Clob from the database");
}
for(int i=0;i<BYTES.length;i++) {
assertEquals("Error in inserting data into the Clob",BYTES[i],bytes1[i]);
}
psInsertClob.close();
//Since auto-commit is true in this test
//this will invalidate the clob object
//Hence closing the ResultSet after
//accessing the Clob object.
//follows the same pattern as testSetBinaryStream().
rs.close();
}
public void testSetAsciiStreamLengthless()
throws IOException, SQLException {
// Insert test data.
InputStream is = new ByteArrayInputStream(BYTES);
psInsertClob.setInt(1, key);
psInsertClob.setAsciiStream(2, is);
psInsertClob.execute();
is.close();
// Read back test data from database.
psFetchClob.setInt(1, key);
ResultSet rs = psFetchClob.executeQuery();
assertTrue("No results retrieved", rs.next());
Clob clobRetrieved = rs.getClob(1);
// Verify read back data.
byte[] dbBytes = new byte[10];
InputStream isRetrieved = clobRetrieved.getAsciiStream();
assertEquals("Unexpected number of bytes read", BYTES.length,
isRetrieved.read(dbBytes));
assertEquals("Stream should be exhausted", -1, isRetrieved.read());
for (int i=0; i < BYTES.length; i++) {
assertEquals("Byte mismatch in/out", BYTES[i], dbBytes[i]);
}
// Cleanup
isRetrieved.close();
psInsertClob.close();
}
/**
*
* Tests the PreparedStatement interface method setBinaryStream
*
* @throws SQLException
*
*/
public void testSetBinaryStream() throws Exception {
//insert default values into the table
byte [] bytes1 = new byte[10];
InputStream is = new java.io.ByteArrayInputStream(BYTES);
is.reset();
//initially insert the data
psInsertBlob.setInt(1, key);
psInsertBlob.setBinaryStream(2, is, BYTES.length);
psInsertBlob.executeUpdate();
// Now query to retrieve the Blob
psFetchBlob.setInt(1, key);
ResultSet rs = psFetchBlob.executeQuery();
rs.next();
Blob blobRetrieved = rs.getBlob(1);
try {
InputStream is_ret = blobRetrieved.getBinaryStream();
is_ret.read(bytes1);
} catch(IOException ioe) {
fail("IOException while reading the Clob from the database");
}
rs.close(); // Because of autocommit, this will invalidate blobRetrieved
for(int i=0;i<BYTES.length;i++) {
assertEquals("Error in inserting data into the Blob",BYTES[i],bytes1[i]);
}
psInsertBlob.close();
}
public void testSetBinaryStreamLengthless()
throws IOException, SQLException {
// Insert test data.
InputStream is = new ByteArrayInputStream(BYTES);
psInsertBlob.setInt(1, key);
psInsertBlob.setBinaryStream(2, is);
psInsertBlob.execute();
is.close();
// Read back test data from database.
psFetchBlob.setInt(1, key);
ResultSet rs = psFetchBlob.executeQuery();
assertTrue("No results retrieved", rs.next());
Blob blobRetrieved = rs.getBlob(1);
// Verify read back data.
byte[] dbBytes = new byte[10];
InputStream isRetrieved = blobRetrieved.getBinaryStream();
assertEquals("Unexpected number of bytes read", BYTES.length,
isRetrieved.read(dbBytes));
assertEquals("Stream should be exhausted", -1, isRetrieved.read());
for (int i=0; i < BYTES.length; i++) {
assertEquals("Byte mismatch in/out", BYTES[i], dbBytes[i]);
}
// Cleanup
isRetrieved.close();
psInsertBlob.close();
}
public void testSetBinaryStreamLengthLess1KOnBlob()
throws IOException, SQLException {
int length = 1*1024;
setBinaryStreamOnBlob(key, length, -1, 0, true);
psFetchBlob.setInt(1, key);
ResultSet rs = psFetchBlob.executeQuery();
assertTrue("Empty resultset", rs.next());
assertEquals(new LoopingAlphabetStream(length),
rs.getBinaryStream(1));
assertFalse("Resultset should have been exhausted", rs.next());
rs.close();
}
public void testSetBinaryStreamLengthLess32KOnBlob()
throws IOException, SQLException {
int length = 32*1024;
setBinaryStreamOnBlob(key, length, -1, 0, true);
psFetchBlob.setInt(1, key);
ResultSet rs = psFetchBlob.executeQuery();
assertTrue("Empty resultset", rs.next());
assertEquals(new LoopingAlphabetStream(length),
rs.getBinaryStream(1));
assertFalse("Resultset should have been exhausted", rs.next());
rs.close();
}
public void testSetBinaryStreamLengthLess65KOnBlob()
throws IOException, SQLException {
int length = 65*1024;
setBinaryStreamOnBlob(key, length, -1, 0, true);
psFetchBlob.setInt(1, key);
ResultSet rs = psFetchBlob.executeQuery();
assertTrue("Empty resultset", rs.next());
LoopingAlphabetStream s1 = new LoopingAlphabetStream(length);
assertEquals(new LoopingAlphabetStream(length),
rs.getBinaryStream(1));
assertFalse("Resultset should have been exhausted", rs.next());
rs.close();
}
public void testSetBinaryStreamLengthLessOnBlobTooLong() {
int length = 1*1024*1024+512;
try {
setBinaryStreamOnBlob(key, length, -1, 0, true);
} catch (SQLException sqle) {
if (usingEmbedded() ||
usingDerbyNetClient() ) {
assertSQLState("XSDA4", sqle);
} else {
assertSQLState("22001", sqle);
}
}
}
public void testExceptionPathOnePage_bs()
throws SQLException {
int length = 11;
try {
setBinaryStreamOnBlob(key, length -1, length, 0, false);
fail("Inserted a BLOB with fewer bytes than specified");
} catch (SQLException sqle) {
if (usingEmbedded()) {
assertSQLState("XSDA4", sqle);
} else {
assertSQLState("XN017", sqle);
}
}
}
public void testExceptionPathMultiplePages_bs()
throws SQLException {
int length = 1*1024*1024;
try {
setBinaryStreamOnBlob(key, length -1, length, 0, false);
fail("Inserted a BLOB with fewer bytes than specified");
} catch (SQLException sqle) {
if (usingEmbedded()) {
assertSQLState("XSDA4", sqle);
} else {
assertSQLState("XN017", sqle);
}
}
}
public void testBlobExceptionDoesNotRollbackOtherStatements()
throws IOException, SQLException {
getConnection().setAutoCommit(false);
int[] keys = {key, requestKey(), requestKey()};
for (int i=0; i < keys.length; i++) {
psInsertBlob.setInt(1, keys[i]);
psInsertBlob.setNull(2, Types.BLOB);
assertEquals(1, psInsertBlob.executeUpdate());
}
// Now insert a BLOB that fails because the stream is too short.
int failedKey = requestKey();
int length = 1*1024*1024;
try {
setBinaryStreamOnBlob(failedKey, length -1, length, 0, false);
fail("Inserted a BLOB with less data than specified");
} catch (SQLException sqle) {
if (usingEmbedded()) {
assertSQLState("XSDA4", sqle);
} else {
assertSQLState("XN017", sqle);
}
}
// Now make sure the previous statements are there, and that the last
// BLOB is not.
ResultSet rs;
for (int i=0; i < keys.length; i++) {
psFetchBlob.setInt(1, keys[i]);
rs = psFetchBlob.executeQuery();
assertTrue(rs.next());
assertFalse(rs.next());
rs.close();
}
psFetchBlob.setInt(1, failedKey);
rs = psFetchBlob.executeQuery();
assertFalse(rs.next());
rs.close();
rollback();
// Make sure all data is gone after the rollback.
for (int i=0; i < keys.length; i++) {
psFetchBlob.setInt(1, keys[i]);
rs = psFetchBlob.executeQuery();
assertFalse(rs.next());
rs.close();
}
// Make sure the failed insert has not "reappeared" somehow...
psFetchBlob.setInt(1, failedKey);
rs = psFetchBlob.executeQuery();
assertFalse(rs.next());
}
public void testSetAsciiStreamLengthLess1KOnClob()
throws IOException, SQLException {
int length = 1*1024;
setAsciiStream(psInsertClob, key, length, -1, 0, true);
psFetchClob.setInt(1, key);
ResultSet rs = psFetchClob.executeQuery();
assertTrue("Empty resultset", rs.next());
assertEquals(new LoopingAlphabetStream(length),
rs.getAsciiStream(1));
assertFalse("Resultset should have been exhausted", rs.next());
rs.close();
}
public void testSetAsciiStreamLengthLess32KOnClob()
throws IOException, SQLException {
int length = 32*1024;
setAsciiStream(psInsertClob, key, length, -1, 0, true);
psFetchClob.setInt(1, key);
ResultSet rs = psFetchClob.executeQuery();
assertTrue("Empty resultset", rs.next());
assertEquals(new LoopingAlphabetStream(length),
rs.getAsciiStream(1));
assertFalse("Resultset should have been exhausted", rs.next());
rs.close();
}
public void testSetAsciiStreamLengthLess65KOnClob()
throws IOException, SQLException {
int length = 65*1024;
setAsciiStream(psInsertClob, key, length, -1, 0, true);
psFetchClob.setInt(1, key);
ResultSet rs = psFetchClob.executeQuery();
assertTrue("Empty resultset", rs.next());
assertEquals(new LoopingAlphabetStream(length),
rs.getAsciiStream(1));
assertFalse("Resultset should have been exhausted", rs.next());
rs.close();
}
public void testSetAsciiStreamLengthLessOnClobTooLong() {
int length = 1*1024*1024+512;
try {
setAsciiStream(psInsertClob, key, length, -1, 0, true);
} catch (SQLException sqle) {
if (usingEmbedded() ||
usingDerbyNetClient() ){
assertSQLState("XSDA4", sqle);
} else {
assertSQLState("22001", sqle);
}
}
}
public void testSetAsciiStreamLengthLessOnClobTooLongTruncate()
throws SQLException {
int trailingBlanks = 512;
int length = 1*1024*1024 + trailingBlanks;
setAsciiStream(psInsertClob, key, length, -1, trailingBlanks, true);
}
public void testSetAsciiStreamLengthlessOnLongVarCharTooLong() {
int length = 32700+512;
try {
setAsciiStream(psInsertLongVarchar, key, length, -1, 0, true);
fail("Inserted a LONG VARCHAR that is too long");
} catch (SQLException sqle) {
if (usingEmbedded()){
assertInternalDerbyIOExceptionState("XCL30", "22001", sqle);
} else if ( usingDerbyNetClient() ) {
assertSQLState("XCL30", sqle);
} else {
assertSQLState("22001", sqle);
}
}
}
public void testSetAsciiStreamLengthlessOnLongVarCharDontTruncate() {
int trailingBlanks = 2000;
int length = 32000 + trailingBlanks;
try {
setAsciiStream(psInsertLongVarchar, key, length, -1,
trailingBlanks, true);
fail("Truncation is not allowed for LONG VARCHAR");
} catch (SQLException sqle) {
if (usingEmbedded()){
assertInternalDerbyIOExceptionState("XCL30", "22001", sqle);
} else if( usingDerbyNetClient() ) {
assertSQLState("XCL30", sqle);
} else {
assertSQLState("22001", sqle);
}
}
}
/************************************************************************
* A U X I L I A R Y M E T H O D S *
************************************************************************/
/**
* Insert data into a Blob column with setBinaryStream.
*
* @param id unique id for inserted row
* @param actualLength the actual length of the stream
* @param specifiedLength the specified length of the stream
* @param trailingBlanks number of characters at the end that is blank
* @param lengthLess whether to use the length less overloads or not
*/
private void setBinaryStreamOnBlob(int id,
int actualLength,
int specifiedLength,
int trailingBlanks,
boolean lengthLess)
throws SQLException {
psInsertBlob.setInt(1, id);
if (lengthLess) {
psInsertBlob.setBinaryStream(2, new LoopingAlphabetStream(
actualLength,
trailingBlanks));
} else {
psInsertBlob.setBinaryStream(2,
new LoopingAlphabetStream(
actualLength,
trailingBlanks),
specifiedLength);
}
assertEquals("Insert with setBinaryStream failed",
1, psInsertBlob.executeUpdate());
}
/**
* Insert data into a column with setAsciiStream.
* The prepared statement passed must have two positional parameters;
* one int and one more. Depending on the last parameter, the execute
* might succeed or it might fail. This is intended behavior, and should
* be handled by the caller. For instance, calling this method on an
* INT-column would fail, calling it on a CLOB-column would succeed.
*
* @param id unique id for inserted row
* @param actualLength the actual length of the stream
* @param specifiedLength the specified length of the stream
* @param trailingBlanks number of characters at the end that is blank
* @param lengthLess whether to use the length less overloads or not
*/
private void setAsciiStream(PreparedStatement ps,
int id,
int actualLength,
int specifiedLength,
int trailingBlanks,
boolean lengthLess)
throws SQLException {
ps.setInt(1, id);
if (lengthLess) {
ps.setAsciiStream(2,
new LoopingAlphabetStream(
actualLength,
trailingBlanks));
} else {
ps.setAsciiStream(2,
new LoopingAlphabetStream(
actualLength,
trailingBlanks),
specifiedLength);
}
assertEquals("Insert with setAsciiStream failed",
1, ps.executeUpdate());
}
/**
* Get next key to id inserted data with.
*/
private static int requestKey() {
return globalKey++;
}
/**
* This methods is not to be used, but sometimes you have to!
*
* @param preSQLState the expected outer SQL state
* @param expectedInternal the expected internal SQL state
* @param sqle the outer SQLException
*/
private void assertInternalDerbyIOExceptionState(
String preSQLState,
String expectedInternal,
SQLException sqle) {
assertSQLState("Outer/public SQL state incorrect",
preSQLState, sqle);
// We need to dig a little with the current way exceptions are
// being reported. We can use getCause because we always run with
// Mustang/Java SE 6.
Throwable cause = getLastSQLException(sqle).getCause();
assertTrue("Exception not an EmbedSQLException",
cause instanceof EmbedSQLException);
cause = cause.getCause();
assertTrue("Exception not a DerbyIOException",
cause instanceof DerbyIOException);
DerbyIOException dioe = (DerbyIOException)cause;
assertEquals("Incorrect internal SQL state", expectedInternal,
dioe.getSQLState());
}
}
|
splicemachine/spliceengine
|
db-testing/src/test/java/com/splicemachine/dbTesting/functionTests/tests/jdbc4/PreparedStatementTest.java
|
Java
|
agpl-3.0
| 46,865
|
/* Warning: This is just the same as the old one_column-deprecated.css.
One day, we'll probably want to review this and clean it up. */
body.one_column #main { float: none; }
body.one_column #main .submodule .head h3 { font-weight: normal; font-size: 11pt; }
body.one_column #main .submodule .body, #main .submodule .foot { padding: 3% 5%; float: left; }
/* SKINNY SUBMODULE */
body.one_column #main .submodule.skinny { width: 25%; margin-right: 20px; }
body.one_column #main .submodule.skinny .submodule-head { width: 82.5%; }
body.one_column #main .submodule.skinny .submodule-head h3 { width: 95%; }
body.one_column #main .submodule.skinny .submodule-body { width: 90%; }
/* FAT SUBMODULE */
body.one_column #main .submodule.fat { width: 67%; }
body.one_column #main .submodule.fat .submodule-head { width: 93.8%; }
body.one_column #main .submodule.fat .submodule-head h3 { width: 100%; }
body.one_column #main .submodule.fat .submodule-body { width: 90%; }
body.one_column #main .submodule.fat .submodule-foot { width: 90%; }
body.one_column #main .equal-width { width: 45%; }
body.one_column #main .equal-width .submodule { width: 45%; }
body.one_column #main .equal-width .submodule .submodule-head { width: 90.5%; }
body.one_column #main .equal-width .submodule .submodule-head h3,
body.one_column #main .equal-width .submodule .submodule-body, #main .equal-width .submodule .submodule-foot { width: 90.5%; }
body.one_column #main .submodule.left { margin-right: 20px; }
|
mzdaniel/oh-mainline
|
mysite/static/css/base/one_column.css
|
CSS
|
agpl-3.0
| 1,554
|
<?php
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
return [
'availability' => [
'disabled' => 'Hiện tại beatmap này không có sẵn để tải xuống.',
'parts-removed' => 'Một phần của beatmap này đã bị xóa bỏ theo yêu cầu của người tạo lập hoặc bên người có quyền bên thứ ba.',
'more-info' => 'Nhấp vào đây để biết thêm thông tin.',
],
'index' => [
'title' => 'Danh Sách Beatmap',
'guest_title' => 'Beatmaps',
],
'panel' => [
'download' => [
'all' => '',
'video' => '',
'no_video' => '',
'direct' => '',
],
],
'show' => [
'discussion' => 'Góc Thảo Luận',
'details' => [
'favourite' => 'Yêu thích beatmapset này',
'logged-out' => 'Bạn cần phải đăng nhập trước khi tải xuống beatmap!',
'mapped_by' => 'được tạo bởi :mapper',
'unfavourite' => 'Bỏ yêu thích beatmapset này',
'updated_timeago' => 'cập nhật lần cuối vào :timeago',
'download' => [
'_' => 'Tải Xuống',
'direct' => 'osu!direct',
'no-video' => 'không Video',
'video' => 'cùng Video',
],
'login_required' => [
'bottom' => 'để truy cập vào nhiều tính năng hơn',
'top' => 'Đăng Nhập',
],
],
'details_date' => [
'approved' => 'được chấp nhận :timeago',
'loved' => 'được yêu thích :timeago',
'qualified' => '',
'ranked' => 'được xếp hạng :timeago',
'submitted' => 'được đăng :timeago',
'updated' => 'cập nhật lần cuối :timeago',
],
'favourites' => [
'limit_reached' => 'Bạn có quá nhiều beatmap yêu thích! Hãy hũy yêu thích vài beatmap và thử lại sau.',
],
'hype' => [
'action' => 'Hype nếu bạn thích map này để giúp nó tiến tới trạng thái <strong>Được xếp hạng</strong>.',
'current' => [
'_' => 'Map này đang ở trạng thái :status.',
'status' => [
'pending' => 'chờ',
'qualified' => 'qualified',
'wip' => 'đang thực hiện',
],
],
'disqualify' => [
'_' => '',
],
'report' => [
'_' => '',
'button' => 'Báo cáo vấn đề',
'link' => 'đây',
],
],
'info' => [
'description' => 'Mô Tả',
'genre' => 'Thể Loại',
'language' => 'Ngôn Ngữ',
'no_scores' => 'Vẫn đang tính toán dữ liệu...',
'points-of-failure' => 'Tỉ Lệ Thất Bại',
'source' => 'Nguồn',
'success-rate' => 'Tỉ Lệ Thành Công',
'tags' => 'Tags',
],
'scoreboard' => [
'achieved' => 'đạt được :when',
'country' => 'Hạng Quốc Gia',
'friend' => 'Hạng Bạn Bè',
'global' => 'Hạng Toàn Cầu',
'supporter-link' => 'Nhấp vào <a href=":link">đây</a> để biết thêm những tính năng bạn có thể nhận!',
'supporter-only' => 'Bạn cần là người ủng hộ để truy cập xếp hạng bạn bè và quốc gia!',
'title' => 'Bảng Xếp hạng',
'headers' => [
'accuracy' => 'Độ Chính Xác',
'combo' => 'Combo Tối Đa',
'miss' => 'Miss',
'mods' => 'Mods',
'player' => 'Người Chơi',
'pp' => 'pp',
'rank' => 'Xếp Hạng',
'score_total' => 'Tổng Điểm',
'score' => 'Điểm',
'time' => '',
],
'no_scores' => [
'country' => 'Chưa có ai từ quốc gia của bạn lập điểm số tại beatmap này!',
'friend' => 'Chưa có bạn bè nào của bạn lập điểm số tại beatmap này!',
'global' => 'Chưa có điểm số. Hãy thử lập một vài điểm số xem?',
'loading' => 'Đang tải điểm số...',
'unranked' => 'Beatmap chưa được xếp hạng.',
],
'score' => [
'first' => 'Dẫn Đầu',
'own' => 'Tốt Nhất Của Bạn',
],
],
'stats' => [
'cs' => 'Kích Cỡ Nốt',
'cs-mania' => 'Số Phím',
'drain' => 'Độ Giảm HP',
'accuracy' => 'Độ Chính Xác',
'ar' => 'Tốc Độ Tiếp Cận',
'stars' => 'Độ Khó',
'total_length' => 'Độ Dài',
'bpm' => 'BPM',
'count_circles' => 'Số Nốt Bấm',
'count_sliders' => 'Số Nốt Trượt',
'user-rating' => 'Đánh Giá',
'rating-spread' => 'Phân Loại Đánh Giá',
'nominations' => 'Đề cử',
'playcount' => 'Đã chơi',
],
'status' => [
'ranked' => 'Đã được xếp hạng',
'approved' => 'Được Chấp Nhận',
'loved' => 'Được yêu thích',
'qualified' => 'Qualified',
'wip' => '',
'pending' => 'Đang Chờ',
'graveyard' => 'Graveyard',
],
],
];
|
nekodex/osu-web
|
resources/lang/vi/beatmapsets.php
|
PHP
|
agpl-3.0
| 5,925
|
/**
* @author Olaf Radicke <briefkasten@olaf-rdicke.de>
* @date 2013-2014
* @copyright
* Copyright (C) 2013 Olaf Radicke <briefkasten@olaf-rdicke.de>
*
* 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 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/>.
*/
#ifndef CORE_PROJECTRESETCONTROLLER_H
#define CORE_PROJECTRESETCONTROLLER_H
#include <core/model/MakefileData.h>
#include <core/model/ProjectData.h>
#include <core/model/UserSession.h>
#include <tnt/httprequest.h>
#include <tnt/httpreply.h>
#include <string>
namespace Tww {
namespace Core {
/**
* @class ProjectResetController This class is the controller of the
* Site core_projectreset. In this site the user can reset the project data.
*/
class ProjectResetController {
public:
ProjectResetController(
Tww::Core::UserSession& _userSession,
Tww::Core::ProjectData& _projectData,
Tww::Core::MakefileData& _makefileData
):
warning(false),
makefileData( _makefileData ),
projectData( _projectData ),
userSession( _userSession )
{};
/**
* This function is called when the site ist (re-)loaded.
*/
void worker (
tnt::HttpRequest& request,
tnt::HttpReply& reply,
tnt::QueryParams& qparam
);
std::string feedback;
/**
* If this set true than the feeback text get a warning css stile.
*/
bool warning;
private:
/**
* Represent the makefile data.
*/
Tww::Core::MakefileData& makefileData;
/**
* Class with project data.
*/
Tww::Core::ProjectData& projectData;
/**
* Session information.
*/
Tww::Core::UserSession& userSession;
/**
* Get the path to file "./tntwebwizard.pro".
*/
std::string getProjectFilePath();
/**
* Get the path to file "./Makefile.tnt".
*/
std::string getMakefilePath();
};
} // namespace core
} // namespace Tww
#endif
|
OlafRadicke/tntwebwizard
|
src/core/controller/ProjectResetController.h
|
C
|
agpl-3.0
| 2,476
|
<?php
/**
# Copyright 2003-2015 Opmantek Limited (www.opmantek.com)
#
# ALL CODE MODIFICATIONS MUST BE SENT TO CODE@OPMANTEK.COM
#
# This file is part of Open-AudIT.
#
# Open-AudIT 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.
#
# Open-AudIT 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 Open-AudIT (most likely in a file named LICENSE).
# If not, see <http://www.gnu.org/licenses/>
#
# For further information on Open-AudIT or for a license other than AGPL please see
# www.opmantek.com or email contact@opmantek.com
#
# *****************************************************************************
*
* PHP version 5.3.3
*
* @category Controller
* @package Logon
* @author Mark Unwin <marku@opmantek.com>
* @copyright 2014 Opmantek
* @license http://www.gnu.org/licenses/agpl-3.0.html aGPL v3
* @version GIT: Open-AudIT_4.3.2
* @link http://www.open-audit.org
*/
/**
* Base Object Login
*
* @access public
* @category Controller
* @package Logon
* @author Mark Unwin <marku@opmantek.com>
* @license http://www.gnu.org/licenses/agpl-3.0.html aGPL v3
* @link http://www.open-audit.org
*/
class Login extends CI_Controller
{
/**
* Constructor
*
* @access public
*/
public function __construct()
{
parent::__construct();
$this->load->helper('url');
redirect('logon');
}
}
|
Opmantek/open-audit
|
code_igniter/application/controllers/login.php
|
PHP
|
agpl-3.0
| 1,842
|
package com.surgingsystems.etl.filter.transformer;
public class OutputCondition extends ConditionalOutputConfiguration {
}
|
objectuser/pneumatic
|
pneumatic/src/main/java/com/surgingsystems/etl/filter/transformer/OutputCondition.java
|
Java
|
agpl-3.0
| 126
|
<?php
/*********************************************************************************
* Zurmo is a customer relationship management program developed by
* Zurmo, Inc. Copyright (C) 2013 Zurmo Inc.
*
* Zurmo is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* Zurmo 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 or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact Zurmo, Inc. with a mailing address at 27 North Wacker Drive
* Suite 370 Chicago, IL 60606. or at email address contact@zurmo.com.
*
* The interactive user interfaces in original and modified versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the Zurmo
* logo and Zurmo copyright notice. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display the words
* "Copyright Zurmo Inc. 2013. All rights reserved".
********************************************************************************/
/**
* Display email message content.
*/
class EmailMessageToRecipientsElement extends Element implements DerivedElementInterface
{
protected function renderControlNonEditable()
{
assert('$this->model instanceof EmailMessage');
$recipientsContent = EmailMessageMashableActivityRules::
getRecipientsContent($this->model->recipients, EmailMessageRecipient::TYPE_TO);
if ($recipientsContent == null && $this->form != null)
{
$recipientsContent = ' ';
}
return Yii::app()->format->html($recipientsContent);
}
protected function renderControlEditable()
{
return $this->renderControlNonEditable();
}
protected function renderError()
{
}
protected function renderLabel()
{
return $this->resolveNonActiveFormFormattedLabel(Zurmo::t('EmailMessagesModule', 'To'));
}
public static function getDisplayName()
{
return Zurmo::t('EmailMessagesModule', 'To Recipients');
}
public static function getModelAttributeNames()
{
return array();
}
}
?>
|
zurmo/Zurmo
|
app/protected/modules/emailMessages/elements/derived/EmailMessageToRecipientsElement.php
|
PHP
|
agpl-3.0
| 3,402
|
require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper")
require 'zlib'
describe "Javascript API", "error handling" do
describe "author" do
def create_new_topic
admin = FactoryGirl.create(:admin)
site = FactoryGirl.create(:hatsuneshima, :user_id => admin.id)
topic = FactoryGirl.create(:topic,:site_id => site.id)
end
def show_topic(site_key, topic_key, options = {})
super(site_key, topic_key, options.merge(
:pre_js => %Q{
var Juvia = { supportsCors: false };
})
)
end
describe "js format" do
describe "author" do
it "should on email notification " , :js => true do
Author.delete_all
create_new_topic
topic = Topic.last
show_topic(topic.site.key, topic.key)
find("#juvia-setting").click
find("#juvia-author-setting").text.should include("Email Notification is OFF")
find("#author_email_setting").click
find("#juvia-setting").click
find("#juvia-author-setting").text.should include("Email Notification is ON")
within(".juvia_email_notification") do
find(".alert").text.should include("Email notifications were successfully saved.")
end
end
it "should off email notification " , :js => true do
create_new_topic
author = FactoryGirl.create(:author, :author_email => 'user@mail.com', :notify_me => true)
topic = Topic.last
show_topic(topic.site.key, topic.key)
find("#juvia-setting").click
find("#juvia-author-setting").text.should include("Email Notification is ON")
find("#author_email_setting").click
find("#juvia-setting").click
find("#juvia-author-setting").text.should include("Email Notification is OFF")
within(".juvia_email_notification") do
find(".alert").text.should include("Email notifications were successfully saved.")
end
end
it "should on email notificaiton on topic" , :js => true do
create_new_topic
topic = Topic.last
author = FactoryGirl.create(:author, :author_email => 'user@mail.com', :notify_me => true)
topic_notification = FactoryGirl.create(:topic_notification, :author_id => author.id, :topic_id => topic.id)
show_topic(topic.site.key, topic.key)
find("#subscriber_email").text.should include("Notified this topic")
find("#subscriber_email").click
within(".juvia_email_notification") do
find(".alert").text.should include("Email notifications were successfully saved.")
end
end
it "should off email notificaiton on topic" , :js => true do
create_new_topic
topic = Topic.last
show_topic(topic.site.key, topic.key)
find("#subscriber_email").text.should include("Notification about this topic")
end
end
end
end
end
|
asharma-ror/bbc
|
spec/requests/javascript_api/author_spec.rb
|
Ruby
|
agpl-3.0
| 3,077
|
# -*- encoding : utf-8 -*-
# This program is free software: you can redistribute it and/or modify
# it under the terms of the Affero GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# (c) 2010 by Hannes Georg
#
module Splash
class Lazy::Fetcher
def initialize(collection,id,path,slices={})
@collection, @id = collection, id
real_path = []
@slices = {}
fetch_path = []
DotNotation.parse_path(path).each do |part|
if part.kind_of? Numeric
current_path = real_path.join('.')
part += slices[current_path] if slices.key? current_path
@slices[current_path] = {'$slice'=>[part,1]}
fetch_path << 0
else
real_path << part
fetch_path << part
end
end
@path = real_path.join('.')
@fetch_path = fetch_path.join('.')
end
def [](*args)
raise "This method is abstract. Please implement `[]` on #{self.to_s}."
end
def all
docs = @collection.find_without_lazy({'_id'=>@id},{:fields=>field_slices({@path => 1})})
if docs.has_next?
return self.get_result(docs.next_document)
end
return ::NA
end
protected
def field_slices(base)
return base.merge(@slices)
end
def get_result(doc)
DotNotation.get(doc,@fetch_path)
end
end
end
|
hannesg/splash
|
lib/splash/lazy/fetcher.rb
|
Ruby
|
agpl-3.0
| 1,882
|
// Append only, write once, non-volatile memory vector
#pragma once
#include <sse/schemes/abstractio/scheduler.hpp>
#include <sse/schemes/utils/logger.hpp>
#include <sse/schemes/utils/utils.hpp>
#include <cassert>
#include <cerrno>
#include <cstring>
#include <unistd.h>
#include <atomic>
#include <exception>
#include <future>
#include <iostream>
#include <string>
#include <type_traits>
namespace sse {
namespace abstractio {
template<typename T, size_t ALIGNMENT = alignof(T)>
class awonvm_vector
{
public:
static constexpr size_t kTypeAlignment = ALIGNMENT;
static constexpr size_t kValueSize = sizeof(T);
static_assert(kTypeAlignment <= kValueSize,
"Invalid alignment for the type size");
using get_callback_type = std::function<void(std::unique_ptr<T>)>;
struct GetRequest
{
size_t index;
get_callback_type callback;
GetRequest(size_t index, get_callback_type callback)
: index(index), callback(std::move(callback))
{
}
};
// cppcheck-suppress noExplicitConstructor
awonvm_vector(const std::string& path,
std::unique_ptr<Scheduler>&& scheduler,
bool direct_io);
explicit awonvm_vector(const std::string& path, bool direct_io = false);
~awonvm_vector();
awonvm_vector(awonvm_vector&& vec) noexcept;
size_t push_back(const T& val);
size_t async_push_back(const T& val);
void reserve(size_t n);
void commit() noexcept;
size_t size() const noexcept
{
return m_size;
}
T get(size_t index);
void async_get(size_t index, get_callback_type get_callback);
void async_gets(const std::vector<GetRequest>& requests);
bool is_committed() const noexcept
{
return m_is_committed.load();
}
bool use_direct_access() const noexcept
{
return m_use_direct_io;
}
void set_use_direct_access(bool flag);
private:
static size_t async_io_page_size(int fd);
const std::string m_filename;
bool m_use_direct_io{false};
int m_fd{0};
const size_t m_device_page_size;
std::atomic_size_t m_size{0};
std::atomic<bool> m_is_committed{false};
std::unique_ptr<Scheduler> m_io_scheduler;
bool m_io_warn_flag{false};
};
template<typename T, size_t ALIGNMENT>
constexpr size_t awonvm_vector<T, ALIGNMENT>::kValueSize;
template<typename T, size_t ALIGNMENT>
// cppcheck-suppress uninitMemberVar
// false positive
awonvm_vector<T, ALIGNMENT>::awonvm_vector(
const std::string& path,
std::unique_ptr<Scheduler>&& scheduler,
bool direct_io)
: m_filename(path), m_use_direct_io(direct_io),
m_fd(utility::open_fd(path, m_use_direct_io)),
m_device_page_size(Scheduler::async_io_page_size(m_fd)),
m_io_scheduler(std::move(scheduler))
{
off_t file_size = utility::file_size(m_fd);
if (m_device_page_size == 0) {
sse::logger::logger()->warn(
"Unable to read page size for file {}. Async IOs will "
"most likely be blocking.");
} else if (kValueSize % m_device_page_size != 0) {
sse::logger::logger()->warn("Device page size for file {} ({} "
"bytes) is not aligned with the "
"value size ({} bytes). Async IOs will "
"most likely be blocking.",
path,
m_device_page_size,
kValueSize);
}
if (file_size > 0) {
m_is_committed = true;
m_size.store(file_size / sizeof(T));
}
}
template<typename T, size_t ALIGNMENT>
// cppcheck-suppress uninitMemberVar
// false positive
awonvm_vector<T, ALIGNMENT>::awonvm_vector(const std::string& path,
bool direct_io)
: m_filename(path), m_use_direct_io(direct_io),
m_fd(utility::open_fd(path, m_use_direct_io)),
m_device_page_size(Scheduler::async_io_page_size(m_fd)),
m_io_scheduler(make_default_aio_scheduler(m_device_page_size))
{
off_t file_size = utility::file_size(m_fd);
if (m_device_page_size == 0) {
sse::logger::logger()->warn(
"Unable to read page size for file {}. Async IOs will "
"most likely be blocking.");
} else if (kValueSize % m_device_page_size != 0) {
sse::logger::logger()->warn("Device page size for file {} ({} "
"bytes) is not aligned with the "
"value size ({} bytes). Async IOs will "
"most likely be blocking.",
path,
m_device_page_size,
kValueSize);
}
if (file_size > 0) {
m_is_committed = true;
m_size.store(file_size / sizeof(T));
}
}
template<typename T, size_t ALIGNMENT>
awonvm_vector<T, ALIGNMENT>::awonvm_vector(awonvm_vector&& vec) noexcept
: m_filename(vec.m_filename), m_use_direct_io(vec.m_use_direct_io),
m_fd(vec.m_fd), m_device_page_size(vec.m_device_page_size),
m_io_scheduler(std::move(vec.m_io_scheduler))
{
vec.m_fd = 0;
}
template<typename T, size_t ALIGNMENT>
awonvm_vector<T, ALIGNMENT>::~awonvm_vector()
{
if (!m_is_committed) {
commit();
} else {
if (m_io_scheduler) {
m_io_scheduler->wait_completions();
}
}
close(m_fd);
}
template<typename T, size_t ALIGNMENT>
void awonvm_vector<T, ALIGNMENT>::reserve(size_t n)
{
if (!m_is_committed && n > size()) {
int ret = ftruncate(m_fd, n * sizeof(T));
if (ret != 0) {
sse::logger::logger()->warn(
"Unable to reserver space for "
"awonvm_vector. ftrunctate returned {}. Error: {}",
ret,
strerror(errno));
}
}
}
template<typename T, size_t ALIGNMENT>
size_t awonvm_vector<T, ALIGNMENT>::push_back(const T& val)
{
if (m_is_committed) {
throw std::runtime_error(
"Invalid state during write: the vector is committed");
}
if (m_use_direct_io && !utility::is_aligned(&val, kTypeAlignment)) {
throw std::invalid_argument("Input is not correctly aligned");
}
size_t pos = m_size.fetch_add(1);
// off_t off = pos * sizeof(T);
// fix issue with the alignment of val
// int res = pwrite(m_fd, &val, sizeof(T), off);
int res = write(m_fd, &val, sizeof(T));
if (res != sizeof(T)) {
std::cerr << "Error during pwrite: " << res << "\n";
std::cerr << "errno " + std::to_string(errno) << "(" << strerror(errno)
<< ")\n";
throw std::runtime_error("Error during pwrite: " + std::to_string(res));
}
return pos;
}
template<typename T, size_t ALIGNMENT>
size_t awonvm_vector<T, ALIGNMENT>::async_push_back(const T& val)
{
if (!m_io_scheduler) {
throw std::runtime_error("No IO Scheduler set");
}
if (!m_use_direct_io && !m_io_warn_flag) {
std::cerr << "awonvm_vector uses buffered IOs. Calls for async IOs "
"will be synchronous.\n";
m_io_warn_flag = true;
}
// we have to copy the data so it does not get destructed by the caller
void* buf;
int ret = posix_memalign((&buf), ALIGNMENT, std::max(ALIGNMENT, sizeof(T)));
if (ret != 0 || buf == nullptr) {
throw std::runtime_error("Error when allocating aligned memory: errno "
+ std::to_string(ret) + "(" + strerror(ret)
+ ")");
}
memcpy(buf, &val, sizeof(T));
auto cb = [](void* b, size_t /*res*/) {
// std::cerr << (int)((uint8_t*)b)[0] << "\t" << res << "\n";
// if (buf != b) {
// std::cerr << "Issue: inconsistent buffer\n";
// }
free(b);
// m_completed_writes.fetch_add(1);
};
size_t pos = m_size.fetch_add(1);
off_t off = pos * sizeof(T);
ret = m_io_scheduler->submit_pwrite(m_fd, buf, sizeof(T), off, buf, cb);
if (ret != 1) {
// we should have a specific exception type here to be able to return
// which position was corrupted
throw std::runtime_error("Error when submitting the read async IO: "
+ std::to_string(ret));
}
return pos;
}
template<typename T, size_t ALIGNMENT>
void awonvm_vector<T, ALIGNMENT>::commit() noexcept
{
if (!m_is_committed) {
if (m_io_scheduler) {
m_io_scheduler->wait_completions();
Scheduler* new_sched = m_io_scheduler->duplicate();
m_io_scheduler.reset(
new_sched); // this will block until the completion of write
// queries and then create a new scheduler for
// future async read queries
} else {
fsync(m_fd);
}
}
m_is_committed = true;
}
template<typename T, size_t ALIGNMENT>
void awonvm_vector<T, ALIGNMENT>::set_use_direct_access(bool flag)
{
if (flag != m_use_direct_io) {
// wait for unfinished async IOs
m_io_scheduler->wait_completions();
// close the current file descriptor
close(m_fd);
// reopen a file descriptor
m_fd = utility::open_fd(m_filename, flag);
// recreate an async scheduler
Scheduler* new_sched = m_io_scheduler->duplicate();
m_io_scheduler.reset(new_sched);
m_use_direct_io = flag;
m_io_warn_flag = false;
}
}
template<typename T, size_t ALIGNMENT>
T awonvm_vector<T, ALIGNMENT>::get(size_t index)
{
if (index > m_size.load()) {
throw std::invalid_argument("Index (" + std::to_string(index)
+ ") out of bounds (size="
+ std::to_string(m_size.load()) + ")");
}
if (!m_is_committed) {
throw std::runtime_error(
"Invalid state during read: the vector is not committed");
}
alignas(kTypeAlignment) T v;
int res = pread(m_fd, &v, sizeof(T), index * sizeof(T));
if (res != sizeof(T)) {
std::cerr << "Error during pread: " << res << "\n";
throw std::runtime_error("Error during pread: " + std::to_string(res));
}
return v;
}
template<typename T, size_t ALIGNMENT>
void awonvm_vector<T, ALIGNMENT>::async_get(size_t index,
get_callback_type get_callback)
{
if (!m_io_scheduler) {
throw std::runtime_error("No IO Scheduler set");
}
if (!m_is_committed) {
throw std::runtime_error(
"Invalid state during read: the vector is not committed");
}
if (!m_use_direct_io && !m_io_warn_flag) {
std::cerr << "awonvm_vector uses buffered IOs. Calls for async IOs "
"will be synchronous.\n";
m_io_warn_flag = true;
}
if (index > m_size.load()) {
throw std::invalid_argument("Index (" + std::to_string(index)
+ ") out of bounds (size="
+ std::to_string(m_size.load()) + ")");
}
void* buffer;
int ret
= posix_memalign((&buffer), ALIGNMENT, std::max(ALIGNMENT, sizeof(T)));
if (ret != 0 || buffer == nullptr) {
throw std::runtime_error("Error when allocating aligned memory: errno "
+ std::to_string(ret) + "(" + strerror(ret)
+ ")");
}
auto inner_cb = [get_callback](void* buf, int64_t res) {
std::unique_ptr<T> result(nullptr);
if (res == sizeof(T)) {
result.reset(reinterpret_cast<T*>(buf));
} else {
free(buf); // avoid memory leaks
}
get_callback(std::move(result));
};
ret = m_io_scheduler->submit_pread(
m_fd, buffer, sizeof(T), index * sizeof(T), buffer, inner_cb);
if (ret != 1) {
free(buffer);
throw std::runtime_error(
"Error when submitting the read async IO: errno "
+ std::to_string(ret) + "(" + strerror(ret) + ")");
}
}
template<typename T, size_t ALIGNMENT>
void awonvm_vector<T, ALIGNMENT>::async_gets(
const std::vector<GetRequest>& requests)
{
if (!m_io_scheduler) {
throw std::runtime_error("No IO Scheduler set");
}
if (!m_is_committed) {
throw std::runtime_error(
"Invalid state during read: the vector is not committed");
}
if (!m_use_direct_io && !m_io_warn_flag) {
std::cerr << "awonvm_vector uses buffered IOs. Calls for async IOs "
"will be synchronous.\n";
m_io_warn_flag = true;
}
std::vector<Scheduler::PReadSumission> submissions;
submissions.reserve(requests.size());
for (const auto& req : requests) {
if (req.index > m_size.load()) {
throw std::invalid_argument("Index (" + std::to_string(req.index)
+ ") out of bounds (size="
+ std::to_string(m_size.load()) + ")");
}
void* buffer;
int ret = posix_memalign(
(&buffer), ALIGNMENT, std::max(ALIGNMENT, sizeof(T)));
if (ret != 0 || buffer == nullptr) {
throw std::runtime_error(
"Error when allocating aligned memory: errno "
+ std::to_string(ret) + "(" + strerror(ret) + ")");
}
auto get_callback = req.callback;
auto inner_cb = [get_callback](void* buf, int64_t res) {
std::unique_ptr<T> result(nullptr);
if (res == sizeof(T)) {
result.reset(reinterpret_cast<T*>(buf));
}
get_callback(std::move(result));
};
submissions.push_back(Scheduler::PReadSumission(
m_fd, buffer, sizeof(T), req.index * sizeof(T), buffer, inner_cb));
}
int ret = m_io_scheduler->submit_preads(submissions);
if (ret < 0 || static_cast<size_t>(ret) != submissions.size()) {
for (auto& sub : submissions) {
free(sub.buf);
}
throw std::runtime_error(
"Error when submitting the read async IO: errno "
+ std::to_string(ret) + "(" + strerror(ret) + ")");
}
}
} // namespace abstractio
} // namespace sse
|
OpenSSE/opensse-schemes
|
lib/include/sse/schemes/abstractio/awonvm_vector.hpp
|
C++
|
agpl-3.0
| 14,702
|
<?php
OC_JSON::callCheck();
//OC_JSON::checkSubAdminUser();
//$groupname = 'test';
if (isset($_POST['groupname'])) {
$groupname = $_POST['groupname'];
} else {
OC_JSON::error(array("data" => array( "message" => "No group." )));
}
if (OC_User::isAdminUser(OC_User::getUser())) {
$result = \OCP\MC_Group::getGroupInfo($groupname);
OC_JSON::success(array('data' => $result ));
//OC_JSON::success(array('data' => $result['publicKey'] ));
} else {
$result = \OCP\MC_Group::getGroupInfo($groupname);
OC_JSON::success(array('data' => $result ));
//OC_JSON::success(array('data' => $result['publicKey'] ));
//if user allowed to see it then
}
|
ipit-international/learning-environment
|
owncloud/settings/ajax/getpkey.php
|
PHP
|
agpl-3.0
| 645
|
# -*- coding: utf-8 -*-
# © 2015 Elico corp (www.elico-corp.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import base64
import random
import string
from binascii import hexlify, unhexlify
from openerp import api, fields, models
try:
from captcha.image import ImageCaptcha
except ImportError:
pass
try:
from simplecrypt import decrypt, encrypt
except ImportError:
pass
class Website(models.Model):
_inherit = 'website'
captcha = fields.Text('Captcha', compute="_captcha", store=False)
captcha_crypt_challenge = fields.Char(
'Crypt', compute="_captcha", store=False)
captcha_crypt_password = fields.Char(
default=lambda self: self._default_salt(),
required=True, help='''
The secret value used as the basis for a key.
This should be as long as varied as possible.
Try to avoid common words.''')
captcha_length = fields.Selection(
'_captcha_length', default='4', required=True)
captcha_chars = fields.Selection(
'_captcha_chars', default='digits', required=True)
def is_captcha_valid(self, crypt_challenge, response):
challenge = decrypt(
self.captcha_crypt_password, unhexlify(crypt_challenge))
if response.upper() == challenge:
return True
return False
@api.depends('captcha_length', 'captcha_chars')
@api.one
def _captcha(self):
captcha = ImageCaptcha()
captcha_challenge = self._generate_random_str(
self._get_captcha_chars(), int(self.captcha_length))
self.captcha_crypt_challenge = hexlify(
encrypt(self.captcha_crypt_password, captcha_challenge))
out = captcha.generate(captcha_challenge).getvalue()
self.captcha = base64.b64encode(out)
def _generate_random_str(self, chars, size):
return ''.join(random.choice(chars) for _ in range(size))
def _default_salt(self):
return self._generate_random_str(
string.digits + string.letters + string.punctuation, 100)
# generate a random salt
def _captcha_length(self):
return [(str(i), str(i)) for i in range(1, 11)]
def _captcha_chars(self):
return [
('digits', 'Digits only'),
('hexadecimal', 'Hexadecimal'),
('all', 'Letters and Digits')]
def _get_captcha_chars(self):
chars = string.digits
if self.captcha_chars == 'hexadecimal':
# do not use the default string.hexdigits because it contains
# lowercase
chars += 'ABCDEF'
elif self.captcha_chars == 'all':
chars += string.uppercase
return chars
|
Elico-Corp/odoo-addons
|
website_captcha_nogoogle/website.py
|
Python
|
agpl-3.0
| 2,704
|
/**
* app.js
*
* Use `app.js` to run your app without `sails lift`.
* To start the server, run: `node app.js`.
*
* This is handy in situations where the sails CLI is not relevant or useful.
*
* For example:
* => `node app.js`
* => `forever start app.js`
* => `node debug app.js`
* => `modulus deploy`
* => `heroku scale`
*
*
* The same command-line arguments are supported, e.g.:
* `node app.js --silent --port=80 --prod`
*/
// Ensure we're in the project directory, so relative paths work as expected
// no matter where we actually lift from.
process.chdir(__dirname);
// Ensure a "sails" can be located:
(function() {
var sails;
try {
sails = require('sails');
} catch (e) {
console.error('To run an app using `node app.js`, you usually need to have a version of `sails` installed in the same directory as your app.');
console.error('To do that, run `npm install sails`');
console.error('');
console.error('Alternatively, if you have sails installed globally (i.e. you did `npm install -g sails`), you can use `sails lift`.');
console.error('When you run `sails lift`, your app will still use a local `./node_modules/sails` dependency if it exists,');
console.error('but if it doesn\'t, the app will run with the global sails instead!');
return;
}
// Try to get `rc` dependency
var rc;
try {
rc = require('rc');
} catch (e0) {
try {
rc = require('sails/node_modules/rc');
} catch (e1) {
console.error('Could not find dependency: `rc`.');
console.error('Your `.sailsrc` file(s) will be ignored.');
console.error('To resolve this, run:');
console.error('npm install rc --save');
rc = function () { return {}; };
}
}
// Start server
sails.lift(rc('sails'));
})();
|
Scalair-OpenSource/occi-board
|
app.js
|
JavaScript
|
agpl-3.0
| 1,766
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* 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 General Public License, v. 2.0.
*
* 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,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.restcomm.protocols.ss7.map.service.mobility.subscriberInformation;
import java.io.IOException;
import org.mobicents.protocols.asn.AsnException;
import org.mobicents.protocols.asn.AsnInputStream;
import org.mobicents.protocols.asn.AsnOutputStream;
import org.mobicents.protocols.asn.Tag;
import org.restcomm.protocols.ss7.map.api.MAPException;
import org.restcomm.protocols.ss7.map.api.MAPMessageType;
import org.restcomm.protocols.ss7.map.api.MAPOperationCode;
import org.restcomm.protocols.ss7.map.api.MAPParsingComponentException;
import org.restcomm.protocols.ss7.map.api.MAPParsingComponentExceptionReason;
import org.restcomm.protocols.ss7.map.api.primitives.ISDNAddressString;
import org.restcomm.protocols.ss7.map.api.primitives.MAPExtensionContainer;
import org.restcomm.protocols.ss7.map.api.primitives.SubscriberIdentity;
import org.restcomm.protocols.ss7.map.api.service.mobility.subscriberInformation.AnyTimeInterrogationRequest;
import org.restcomm.protocols.ss7.map.api.service.mobility.subscriberInformation.RequestedInfo;
import org.restcomm.protocols.ss7.map.primitives.ISDNAddressStringImpl;
import org.restcomm.protocols.ss7.map.primitives.MAPAsnPrimitive;
import org.restcomm.protocols.ss7.map.primitives.MAPExtensionContainerImpl;
import org.restcomm.protocols.ss7.map.primitives.SubscriberIdentityImpl;
import org.restcomm.protocols.ss7.map.service.mobility.MobilityMessageImpl;
/**
* @author amit bhayani
*
*/
public class AnyTimeInterrogationRequestImpl extends MobilityMessageImpl implements AnyTimeInterrogationRequest,
MAPAsnPrimitive {
private static final int _TAG_SUBSCRIBER_IDENTITY = 0;
private static final int _TAG_REQUESTED_INFO = 1;
private static final int _TAG_EXTENSION_CONTAINER = 2;
private static final int _TAG_GSM_SCF_ADDRESS = 3;
public static final String _PrimitiveName = "AnyTimeInterrogationRequest";
private SubscriberIdentity subscriberIdentity;
private RequestedInfo requestedInfo;
private ISDNAddressString gsmSCFAddress;
private MAPExtensionContainer extensionContainer;
public AnyTimeInterrogationRequestImpl() {
}
public AnyTimeInterrogationRequestImpl(SubscriberIdentity subscriberIdentity, RequestedInfo requestedInfo,
ISDNAddressString gsmSCFAddress, MAPExtensionContainer extensionContainer) {
this.subscriberIdentity = subscriberIdentity;
this.requestedInfo = requestedInfo;
this.gsmSCFAddress = gsmSCFAddress;
this.extensionContainer = extensionContainer;
}
/*
* (non-Javadoc)
*
* @see org.restcomm.protocols.ss7.map.primitives.MAPAsnPrimitive#getTag()
*/
public int getTag() throws MAPException {
return Tag.SEQUENCE;
}
/*
* (non-Javadoc)
*
* @see org.restcomm.protocols.ss7.map.primitives.MAPAsnPrimitive#getTagClass()
*/
public int getTagClass() {
return Tag.CLASS_UNIVERSAL;
}
/*
* (non-Javadoc)
*
* @see org.restcomm.protocols.ss7.map.primitives.MAPAsnPrimitive#getIsPrimitive ()
*/
public boolean getIsPrimitive() {
return false;
}
/*
* (non-Javadoc)
*
* @see org.restcomm.protocols.ss7.map.primitives.MAPAsnPrimitive#decodeAll( org.mobicents.protocols.asn.AsnInputStream)
*/
public void decodeAll(AsnInputStream ansIS) throws MAPParsingComponentException {
try {
int length = ansIS.readLength();
this._decode(ansIS, length);
} catch (IOException e) {
throw new MAPParsingComponentException("IOException when decoding " + _PrimitiveName + ": " + e.getMessage(), e,
MAPParsingComponentExceptionReason.MistypedParameter);
} catch (AsnException e) {
throw new MAPParsingComponentException("AsnException when decoding " + _PrimitiveName + ": " + e.getMessage(), e,
MAPParsingComponentExceptionReason.MistypedParameter);
}
}
/*
* (non-Javadoc)
*
* @see org.restcomm.protocols.ss7.map.primitives.MAPAsnPrimitive#decodeData (org.mobicents.protocols.asn.AsnInputStream,
* int)
*/
public void decodeData(AsnInputStream ansIS, int length) throws MAPParsingComponentException {
try {
this._decode(ansIS, length);
} catch (IOException e) {
throw new MAPParsingComponentException("IOException when decoding " + _PrimitiveName + ": " + e.getMessage(), e,
MAPParsingComponentExceptionReason.MistypedParameter);
} catch (AsnException e) {
throw new MAPParsingComponentException("AsnException when decoding " + _PrimitiveName + ": " + e.getMessage(), e,
MAPParsingComponentExceptionReason.MistypedParameter);
}
}
private void _decode(AsnInputStream ansIS, int length) throws MAPParsingComponentException, IOException, AsnException {
AsnInputStream ais = ansIS.readSequenceStreamData(length);
this.subscriberIdentity = null;
this.requestedInfo = null;
this.gsmSCFAddress = null;
this.extensionContainer = null;
while (true) {
if (ais.available() == 0)
break;
int tag = ais.readTag();
if (ais.getTagClass() == Tag.CLASS_CONTEXT_SPECIFIC) {
switch (tag) {
case _TAG_SUBSCRIBER_IDENTITY:
// decode SubscriberIdentity
if (ais.isTagPrimitive())
throw new MAPParsingComponentException("Error while decoding " + _PrimitiveName
+ ": Parameter subscriberIdentity is primitive",
MAPParsingComponentExceptionReason.MistypedParameter);
this.subscriberIdentity = new SubscriberIdentityImpl();
AsnInputStream ais2 = ais.readSequenceStream();
ais2.readTag();
((SubscriberIdentityImpl) this.subscriberIdentity).decodeAll(ais2);
break;
case _TAG_REQUESTED_INFO:
// decode RequestedInfo
if (ais.isTagPrimitive())
throw new MAPParsingComponentException("Error while decoding " + _PrimitiveName
+ ": Parameter requestedInfo is primitive",
MAPParsingComponentExceptionReason.MistypedParameter);
this.requestedInfo = new RequestedInfoImpl();
((RequestedInfoImpl) this.requestedInfo).decodeAll(ais);
break;
case _TAG_EXTENSION_CONTAINER:
// decode extensionContainer
if (ais.isTagPrimitive())
throw new MAPParsingComponentException("Error while decoding " + _PrimitiveName
+ ": Parameter extensionContainer is primitive",
MAPParsingComponentExceptionReason.MistypedParameter);
extensionContainer = new MAPExtensionContainerImpl();
((MAPExtensionContainerImpl) extensionContainer).decodeAll(ais);
break;
case _TAG_GSM_SCF_ADDRESS:
// decode gsmSCF-Address
if (!ais.isTagPrimitive())
throw new MAPParsingComponentException("Error while decoding " + _PrimitiveName
+ ": Parameter gsmSCFAddress is not primitive",
MAPParsingComponentExceptionReason.MistypedParameter);
this.gsmSCFAddress = new ISDNAddressStringImpl();
((ISDNAddressStringImpl) this.gsmSCFAddress).decodeAll(ais);
break;
default:
ais.advanceElement();
break;
}
} else {
ais.advanceElement();
}
}
if (this.subscriberIdentity == null || this.requestedInfo == null || this.gsmSCFAddress == null)
throw new MAPParsingComponentException(
"Error while decoding "
+ _PrimitiveName
+ ": subscriberIdentity, requestedInfo and gsmSCFAddress parameters are mandatory but some of them are not found",
MAPParsingComponentExceptionReason.MistypedParameter);
}
/*
* (non-Javadoc)
*
* @see org.restcomm.protocols.ss7.map.primitives.MAPAsnPrimitive#encodeAll( org.mobicents.protocols.asn.AsnOutputStream)
*/
public void encodeAll(AsnOutputStream asnOs) throws MAPException {
this.encodeAll(asnOs, this.getTagClass(), this.getTag());
}
/*
* (non-Javadoc)
*
* @see org.restcomm.protocols.ss7.map.primitives.MAPAsnPrimitive#encodeAll( org.mobicents.protocols.asn.AsnOutputStream,
* int, int)
*/
public void encodeAll(AsnOutputStream asnOs, int tagClass, int tag) throws MAPException {
try {
asnOs.writeTag(tagClass, this.getIsPrimitive(), tag);
int pos = asnOs.StartContentDefiniteLength();
this.encodeData(asnOs);
asnOs.FinalizeContent(pos);
} catch (AsnException e) {
throw new MAPException("AsnException when encoding " + _PrimitiveName + ": " + e.getMessage(), e);
}
}
/*
* (non-Javadoc)
*
* @see org.restcomm.protocols.ss7.map.primitives.MAPAsnPrimitive#encodeData (org.mobicents.protocols.asn.AsnOutputStream)
*/
public void encodeData(AsnOutputStream asnOs) throws MAPException {
if (this.subscriberIdentity == null) {
throw new MAPException("Error while encoding " + _PrimitiveName
+ " the mandatory parameter subscriberIdentity is not defined");
}
if (this.requestedInfo == null) {
throw new MAPException("Error while encoding " + _PrimitiveName
+ " the mandatory parameter requestedInfo is not defined");
}
if (this.gsmSCFAddress == null) {
throw new MAPException("Error while encoding " + _PrimitiveName
+ " the mandatory parameter gsmSCF-Address is not defined");
}
try {
asnOs.writeTag(Tag.CLASS_CONTEXT_SPECIFIC, false, _TAG_SUBSCRIBER_IDENTITY);
int pos = asnOs.StartContentDefiniteLength();
((SubscriberIdentityImpl) this.subscriberIdentity).encodeAll(asnOs);
asnOs.FinalizeContent(pos);
} catch (AsnException e) {
throw new MAPException("AsnException while encoding " + _PrimitiveName
+ " parameter subscriberIdentity [0] SubscriberIdentity");
}
((RequestedInfoImpl) this.requestedInfo).encodeAll(asnOs, Tag.CLASS_CONTEXT_SPECIFIC, _TAG_REQUESTED_INFO);
((ISDNAddressStringImpl) this.gsmSCFAddress).encodeAll(asnOs, Tag.CLASS_CONTEXT_SPECIFIC, _TAG_GSM_SCF_ADDRESS);
if (this.extensionContainer != null) {
((MAPExtensionContainerImpl) this.extensionContainer).encodeAll(asnOs, Tag.CLASS_CONTEXT_SPECIFIC,
_TAG_EXTENSION_CONTAINER);
}
}
/*
* (non-Javadoc)
*
* @see org.restcomm.protocols.ss7.map.api.service.subscriberInformation.
* AnyTimeInterrogationRequestIndication#getSubscriberIdentity()
*/
public SubscriberIdentity getSubscriberIdentity() {
return this.subscriberIdentity;
}
/*
* (non-Javadoc)
*
* @see org.restcomm.protocols.ss7.map.api.service.subscriberInformation.
* AnyTimeInterrogationRequestIndication#getRequestedInfo()
*/
public RequestedInfo getRequestedInfo() {
return this.requestedInfo;
}
/*
* (non-Javadoc)
*
* @see org.restcomm.protocols.ss7.map.api.service.subscriberInformation.
* AnyTimeInterrogationRequestIndication#getGsmSCFAddress()
*/
public ISDNAddressString getGsmSCFAddress() {
return this.gsmSCFAddress;
}
/*
* (non-Javadoc)
*
* @see org.restcomm.protocols.ss7.map.api.service.subscriberInformation.
* AnyTimeInterrogationRequestIndication#getExtensionContainer()
*/
public MAPExtensionContainer getExtensionContainer() {
return this.extensionContainer;
}
/*
* (non-Javadoc)
*
* @see org.restcomm.protocols.ss7.map.api.MAPMessage#getMessageType()
*/
public MAPMessageType getMessageType() {
return MAPMessageType.anyTimeInterrogation_Request;
}
/*
* (non-Javadoc)
*
* @see org.restcomm.protocols.ss7.map.api.MAPMessage#getOperationCode()
*/
public int getOperationCode() {
return MAPOperationCode.anyTimeInterrogation;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(_PrimitiveName);
sb.append(" [");
if (this.subscriberIdentity != null) {
sb.append("subscriberIdentity=");
sb.append(this.subscriberIdentity);
}
if (this.requestedInfo != null) {
sb.append(", requestedInfo=");
sb.append(this.requestedInfo);
}
if (this.gsmSCFAddress != null) {
sb.append(", gsmSCFAddress=");
sb.append(this.gsmSCFAddress);
}
if (this.extensionContainer != null) {
sb.append(", extensionContainer=");
sb.append(this.extensionContainer);
}
sb.append("]");
return sb.toString();
}
}
|
RestComm/jss7
|
map/map-impl/src/main/java/org/restcomm/protocols/ss7/map/service/mobility/subscriberInformation/AnyTimeInterrogationRequestImpl.java
|
Java
|
agpl-3.0
| 14,805
|
# Generated by Django 2.2.15 on 2020-12-01 13:12
from django.db import migrations
import djmoney.models.fields
class Migration(migrations.Migration):
dependencies = [
("projects", "0008_auto_20190220_1133"),
]
operations = [
migrations.AddField(
model_name="project",
name="amount_invoiced",
field=djmoney.models.fields.MoneyField(
blank=True,
decimal_places=2,
default_currency="CHF",
max_digits=10,
null=True,
),
),
migrations.AddField(
model_name="project",
name="amount_invoiced_currency",
field=djmoney.models.fields.CurrencyField(
choices=[
("XUA", "ADB Unit of Account"),
("AFN", "Afghani"),
("DZD", "Algerian Dinar"),
("ARS", "Argentine Peso"),
("AMD", "Armenian Dram"),
("AWG", "Aruban Guilder"),
("AUD", "Australian Dollar"),
("AZN", "Azerbaijanian Manat"),
("BSD", "Bahamian Dollar"),
("BHD", "Bahraini Dinar"),
("THB", "Baht"),
("PAB", "Balboa"),
("BBD", "Barbados Dollar"),
("BYN", "Belarussian Ruble"),
("BYR", "Belarussian Ruble"),
("BZD", "Belize Dollar"),
("BMD", "Bermudian Dollar (customarily known as Bermuda Dollar)"),
("BTN", "Bhutanese ngultrum"),
("VEF", "Bolivar Fuerte"),
("BOB", "Boliviano"),
("XBA", "Bond Markets Units European Composite Unit (EURCO)"),
("BRL", "Brazilian Real"),
("BND", "Brunei Dollar"),
("BGN", "Bulgarian Lev"),
("BIF", "Burundi Franc"),
("XOF", "CFA Franc BCEAO"),
("XAF", "CFA franc BEAC"),
("XPF", "CFP Franc"),
("CAD", "Canadian Dollar"),
("CVE", "Cape Verde Escudo"),
("KYD", "Cayman Islands Dollar"),
("CLP", "Chilean peso"),
("XTS", "Codes specifically reserved for testing purposes"),
("COP", "Colombian peso"),
("KMF", "Comoro Franc"),
("CDF", "Congolese franc"),
("BAM", "Convertible Marks"),
("NIO", "Cordoba Oro"),
("CRC", "Costa Rican Colon"),
("HRK", "Croatian Kuna"),
("CUP", "Cuban Peso"),
("CUC", "Cuban convertible peso"),
("CZK", "Czech Koruna"),
("GMD", "Dalasi"),
("DKK", "Danish Krone"),
("MKD", "Denar"),
("DJF", "Djibouti Franc"),
("STD", "Dobra"),
("DOP", "Dominican Peso"),
("VND", "Dong"),
("XCD", "East Caribbean Dollar"),
("EGP", "Egyptian Pound"),
("SVC", "El Salvador Colon"),
("ETB", "Ethiopian Birr"),
("EUR", "Euro"),
("XBB", "European Monetary Unit (E.M.U.-6)"),
("XBD", "European Unit of Account 17(E.U.A.-17)"),
("XBC", "European Unit of Account 9(E.U.A.-9)"),
("FKP", "Falkland Islands Pound"),
("FJD", "Fiji Dollar"),
("HUF", "Forint"),
("GHS", "Ghana Cedi"),
("GIP", "Gibraltar Pound"),
("XAU", "Gold"),
("XFO", "Gold-Franc"),
("PYG", "Guarani"),
("GNF", "Guinea Franc"),
("GYD", "Guyana Dollar"),
("HTG", "Haitian gourde"),
("HKD", "Hong Kong Dollar"),
("UAH", "Hryvnia"),
("ISK", "Iceland Krona"),
("INR", "Indian Rupee"),
("IRR", "Iranian Rial"),
("IQD", "Iraqi Dinar"),
("IMP", "Isle of Man Pound"),
("JMD", "Jamaican Dollar"),
("JOD", "Jordanian Dinar"),
("KES", "Kenyan Shilling"),
("PGK", "Kina"),
("LAK", "Kip"),
("KWD", "Kuwaiti Dinar"),
("AOA", "Kwanza"),
("MMK", "Kyat"),
("GEL", "Lari"),
("LVL", "Latvian Lats"),
("LBP", "Lebanese Pound"),
("ALL", "Lek"),
("HNL", "Lempira"),
("SLL", "Leone"),
("LSL", "Lesotho loti"),
("LRD", "Liberian Dollar"),
("LYD", "Libyan Dinar"),
("SZL", "Lilangeni"),
("LTL", "Lithuanian Litas"),
("MGA", "Malagasy Ariary"),
("MWK", "Malawian Kwacha"),
("MYR", "Malaysian Ringgit"),
("TMM", "Manat"),
("MUR", "Mauritius Rupee"),
("MZN", "Metical"),
("MXV", "Mexican Unidad de Inversion (UDI)"),
("MXN", "Mexican peso"),
("MDL", "Moldovan Leu"),
("MAD", "Moroccan Dirham"),
("BOV", "Mvdol"),
("NGN", "Naira"),
("ERN", "Nakfa"),
("NAD", "Namibian Dollar"),
("NPR", "Nepalese Rupee"),
("ANG", "Netherlands Antillian Guilder"),
("ILS", "New Israeli Sheqel"),
("RON", "New Leu"),
("TWD", "New Taiwan Dollar"),
("NZD", "New Zealand Dollar"),
("KPW", "North Korean Won"),
("NOK", "Norwegian Krone"),
("PEN", "Nuevo Sol"),
("MRO", "Ouguiya"),
("TOP", "Paanga"),
("PKR", "Pakistan Rupee"),
("XPD", "Palladium"),
("MOP", "Pataca"),
("PHP", "Philippine Peso"),
("XPT", "Platinum"),
("GBP", "Pound Sterling"),
("BWP", "Pula"),
("QAR", "Qatari Rial"),
("GTQ", "Quetzal"),
("ZAR", "Rand"),
("OMR", "Rial Omani"),
("KHR", "Riel"),
("MVR", "Rufiyaa"),
("IDR", "Rupiah"),
("RUB", "Russian Ruble"),
("RWF", "Rwanda Franc"),
("XDR", "SDR"),
("SHP", "Saint Helena Pound"),
("SAR", "Saudi Riyal"),
("RSD", "Serbian Dinar"),
("SCR", "Seychelles Rupee"),
("XAG", "Silver"),
("SGD", "Singapore Dollar"),
("SBD", "Solomon Islands Dollar"),
("KGS", "Som"),
("SOS", "Somali Shilling"),
("TJS", "Somoni"),
("SSP", "South Sudanese Pound"),
("LKR", "Sri Lanka Rupee"),
("XSU", "Sucre"),
("SDG", "Sudanese Pound"),
("SRD", "Surinam Dollar"),
("SEK", "Swedish Krona"),
("CHF", "Swiss Franc"),
("SYP", "Syrian Pound"),
("BDT", "Taka"),
("WST", "Tala"),
("TZS", "Tanzanian Shilling"),
("KZT", "Tenge"),
(
"XXX",
"The codes assigned for transactions where no currency is involved",
),
("TTD", "Trinidad and Tobago Dollar"),
("MNT", "Tugrik"),
("TND", "Tunisian Dinar"),
("TRY", "Turkish Lira"),
("TMT", "Turkmenistan New Manat"),
("TVD", "Tuvalu dollar"),
("AED", "UAE Dirham"),
("XFU", "UIC-Franc"),
("USD", "US Dollar"),
("USN", "US Dollar (Next day)"),
("UGX", "Uganda Shilling"),
("CLF", "Unidad de Fomento"),
("COU", "Unidad de Valor Real"),
("UYI", "Uruguay Peso en Unidades Indexadas (URUIURUI)"),
("UYU", "Uruguayan peso"),
("UZS", "Uzbekistan Sum"),
("VUV", "Vatu"),
("CHE", "WIR Euro"),
("CHW", "WIR Franc"),
("KRW", "Won"),
("YER", "Yemeni Rial"),
("JPY", "Yen"),
("CNY", "Yuan Renminbi"),
("ZMK", "Zambian Kwacha"),
("ZMW", "Zambian Kwacha"),
("ZWD", "Zimbabwe Dollar A/06"),
("ZWN", "Zimbabwe dollar A/08"),
("ZWL", "Zimbabwe dollar A/09"),
("PLN", "Zloty"),
],
default="CHF",
editable=False,
max_length=3,
),
),
migrations.AddField(
model_name="project",
name="amount_offered",
field=djmoney.models.fields.MoneyField(
blank=True,
decimal_places=2,
default_currency="CHF",
max_digits=10,
null=True,
),
),
migrations.AddField(
model_name="project",
name="amount_offered_currency",
field=djmoney.models.fields.CurrencyField(
choices=[
("XUA", "ADB Unit of Account"),
("AFN", "Afghani"),
("DZD", "Algerian Dinar"),
("ARS", "Argentine Peso"),
("AMD", "Armenian Dram"),
("AWG", "Aruban Guilder"),
("AUD", "Australian Dollar"),
("AZN", "Azerbaijanian Manat"),
("BSD", "Bahamian Dollar"),
("BHD", "Bahraini Dinar"),
("THB", "Baht"),
("PAB", "Balboa"),
("BBD", "Barbados Dollar"),
("BYN", "Belarussian Ruble"),
("BYR", "Belarussian Ruble"),
("BZD", "Belize Dollar"),
("BMD", "Bermudian Dollar (customarily known as Bermuda Dollar)"),
("BTN", "Bhutanese ngultrum"),
("VEF", "Bolivar Fuerte"),
("BOB", "Boliviano"),
("XBA", "Bond Markets Units European Composite Unit (EURCO)"),
("BRL", "Brazilian Real"),
("BND", "Brunei Dollar"),
("BGN", "Bulgarian Lev"),
("BIF", "Burundi Franc"),
("XOF", "CFA Franc BCEAO"),
("XAF", "CFA franc BEAC"),
("XPF", "CFP Franc"),
("CAD", "Canadian Dollar"),
("CVE", "Cape Verde Escudo"),
("KYD", "Cayman Islands Dollar"),
("CLP", "Chilean peso"),
("XTS", "Codes specifically reserved for testing purposes"),
("COP", "Colombian peso"),
("KMF", "Comoro Franc"),
("CDF", "Congolese franc"),
("BAM", "Convertible Marks"),
("NIO", "Cordoba Oro"),
("CRC", "Costa Rican Colon"),
("HRK", "Croatian Kuna"),
("CUP", "Cuban Peso"),
("CUC", "Cuban convertible peso"),
("CZK", "Czech Koruna"),
("GMD", "Dalasi"),
("DKK", "Danish Krone"),
("MKD", "Denar"),
("DJF", "Djibouti Franc"),
("STD", "Dobra"),
("DOP", "Dominican Peso"),
("VND", "Dong"),
("XCD", "East Caribbean Dollar"),
("EGP", "Egyptian Pound"),
("SVC", "El Salvador Colon"),
("ETB", "Ethiopian Birr"),
("EUR", "Euro"),
("XBB", "European Monetary Unit (E.M.U.-6)"),
("XBD", "European Unit of Account 17(E.U.A.-17)"),
("XBC", "European Unit of Account 9(E.U.A.-9)"),
("FKP", "Falkland Islands Pound"),
("FJD", "Fiji Dollar"),
("HUF", "Forint"),
("GHS", "Ghana Cedi"),
("GIP", "Gibraltar Pound"),
("XAU", "Gold"),
("XFO", "Gold-Franc"),
("PYG", "Guarani"),
("GNF", "Guinea Franc"),
("GYD", "Guyana Dollar"),
("HTG", "Haitian gourde"),
("HKD", "Hong Kong Dollar"),
("UAH", "Hryvnia"),
("ISK", "Iceland Krona"),
("INR", "Indian Rupee"),
("IRR", "Iranian Rial"),
("IQD", "Iraqi Dinar"),
("IMP", "Isle of Man Pound"),
("JMD", "Jamaican Dollar"),
("JOD", "Jordanian Dinar"),
("KES", "Kenyan Shilling"),
("PGK", "Kina"),
("LAK", "Kip"),
("KWD", "Kuwaiti Dinar"),
("AOA", "Kwanza"),
("MMK", "Kyat"),
("GEL", "Lari"),
("LVL", "Latvian Lats"),
("LBP", "Lebanese Pound"),
("ALL", "Lek"),
("HNL", "Lempira"),
("SLL", "Leone"),
("LSL", "Lesotho loti"),
("LRD", "Liberian Dollar"),
("LYD", "Libyan Dinar"),
("SZL", "Lilangeni"),
("LTL", "Lithuanian Litas"),
("MGA", "Malagasy Ariary"),
("MWK", "Malawian Kwacha"),
("MYR", "Malaysian Ringgit"),
("TMM", "Manat"),
("MUR", "Mauritius Rupee"),
("MZN", "Metical"),
("MXV", "Mexican Unidad de Inversion (UDI)"),
("MXN", "Mexican peso"),
("MDL", "Moldovan Leu"),
("MAD", "Moroccan Dirham"),
("BOV", "Mvdol"),
("NGN", "Naira"),
("ERN", "Nakfa"),
("NAD", "Namibian Dollar"),
("NPR", "Nepalese Rupee"),
("ANG", "Netherlands Antillian Guilder"),
("ILS", "New Israeli Sheqel"),
("RON", "New Leu"),
("TWD", "New Taiwan Dollar"),
("NZD", "New Zealand Dollar"),
("KPW", "North Korean Won"),
("NOK", "Norwegian Krone"),
("PEN", "Nuevo Sol"),
("MRO", "Ouguiya"),
("TOP", "Paanga"),
("PKR", "Pakistan Rupee"),
("XPD", "Palladium"),
("MOP", "Pataca"),
("PHP", "Philippine Peso"),
("XPT", "Platinum"),
("GBP", "Pound Sterling"),
("BWP", "Pula"),
("QAR", "Qatari Rial"),
("GTQ", "Quetzal"),
("ZAR", "Rand"),
("OMR", "Rial Omani"),
("KHR", "Riel"),
("MVR", "Rufiyaa"),
("IDR", "Rupiah"),
("RUB", "Russian Ruble"),
("RWF", "Rwanda Franc"),
("XDR", "SDR"),
("SHP", "Saint Helena Pound"),
("SAR", "Saudi Riyal"),
("RSD", "Serbian Dinar"),
("SCR", "Seychelles Rupee"),
("XAG", "Silver"),
("SGD", "Singapore Dollar"),
("SBD", "Solomon Islands Dollar"),
("KGS", "Som"),
("SOS", "Somali Shilling"),
("TJS", "Somoni"),
("SSP", "South Sudanese Pound"),
("LKR", "Sri Lanka Rupee"),
("XSU", "Sucre"),
("SDG", "Sudanese Pound"),
("SRD", "Surinam Dollar"),
("SEK", "Swedish Krona"),
("CHF", "Swiss Franc"),
("SYP", "Syrian Pound"),
("BDT", "Taka"),
("WST", "Tala"),
("TZS", "Tanzanian Shilling"),
("KZT", "Tenge"),
(
"XXX",
"The codes assigned for transactions where no currency is involved",
),
("TTD", "Trinidad and Tobago Dollar"),
("MNT", "Tugrik"),
("TND", "Tunisian Dinar"),
("TRY", "Turkish Lira"),
("TMT", "Turkmenistan New Manat"),
("TVD", "Tuvalu dollar"),
("AED", "UAE Dirham"),
("XFU", "UIC-Franc"),
("USD", "US Dollar"),
("USN", "US Dollar (Next day)"),
("UGX", "Uganda Shilling"),
("CLF", "Unidad de Fomento"),
("COU", "Unidad de Valor Real"),
("UYI", "Uruguay Peso en Unidades Indexadas (URUIURUI)"),
("UYU", "Uruguayan peso"),
("UZS", "Uzbekistan Sum"),
("VUV", "Vatu"),
("CHE", "WIR Euro"),
("CHW", "WIR Franc"),
("KRW", "Won"),
("YER", "Yemeni Rial"),
("JPY", "Yen"),
("CNY", "Yuan Renminbi"),
("ZMK", "Zambian Kwacha"),
("ZMW", "Zambian Kwacha"),
("ZWD", "Zimbabwe Dollar A/06"),
("ZWN", "Zimbabwe dollar A/08"),
("ZWL", "Zimbabwe dollar A/09"),
("PLN", "Zloty"),
],
default="CHF",
editable=False,
max_length=3,
),
),
migrations.AddField(
model_name="task",
name="amount_invoiced",
field=djmoney.models.fields.MoneyField(
blank=True,
decimal_places=2,
default_currency="CHF",
max_digits=10,
null=True,
),
),
migrations.AddField(
model_name="task",
name="amount_invoiced_currency",
field=djmoney.models.fields.CurrencyField(
choices=[
("XUA", "ADB Unit of Account"),
("AFN", "Afghani"),
("DZD", "Algerian Dinar"),
("ARS", "Argentine Peso"),
("AMD", "Armenian Dram"),
("AWG", "Aruban Guilder"),
("AUD", "Australian Dollar"),
("AZN", "Azerbaijanian Manat"),
("BSD", "Bahamian Dollar"),
("BHD", "Bahraini Dinar"),
("THB", "Baht"),
("PAB", "Balboa"),
("BBD", "Barbados Dollar"),
("BYN", "Belarussian Ruble"),
("BYR", "Belarussian Ruble"),
("BZD", "Belize Dollar"),
("BMD", "Bermudian Dollar (customarily known as Bermuda Dollar)"),
("BTN", "Bhutanese ngultrum"),
("VEF", "Bolivar Fuerte"),
("BOB", "Boliviano"),
("XBA", "Bond Markets Units European Composite Unit (EURCO)"),
("BRL", "Brazilian Real"),
("BND", "Brunei Dollar"),
("BGN", "Bulgarian Lev"),
("BIF", "Burundi Franc"),
("XOF", "CFA Franc BCEAO"),
("XAF", "CFA franc BEAC"),
("XPF", "CFP Franc"),
("CAD", "Canadian Dollar"),
("CVE", "Cape Verde Escudo"),
("KYD", "Cayman Islands Dollar"),
("CLP", "Chilean peso"),
("XTS", "Codes specifically reserved for testing purposes"),
("COP", "Colombian peso"),
("KMF", "Comoro Franc"),
("CDF", "Congolese franc"),
("BAM", "Convertible Marks"),
("NIO", "Cordoba Oro"),
("CRC", "Costa Rican Colon"),
("HRK", "Croatian Kuna"),
("CUP", "Cuban Peso"),
("CUC", "Cuban convertible peso"),
("CZK", "Czech Koruna"),
("GMD", "Dalasi"),
("DKK", "Danish Krone"),
("MKD", "Denar"),
("DJF", "Djibouti Franc"),
("STD", "Dobra"),
("DOP", "Dominican Peso"),
("VND", "Dong"),
("XCD", "East Caribbean Dollar"),
("EGP", "Egyptian Pound"),
("SVC", "El Salvador Colon"),
("ETB", "Ethiopian Birr"),
("EUR", "Euro"),
("XBB", "European Monetary Unit (E.M.U.-6)"),
("XBD", "European Unit of Account 17(E.U.A.-17)"),
("XBC", "European Unit of Account 9(E.U.A.-9)"),
("FKP", "Falkland Islands Pound"),
("FJD", "Fiji Dollar"),
("HUF", "Forint"),
("GHS", "Ghana Cedi"),
("GIP", "Gibraltar Pound"),
("XAU", "Gold"),
("XFO", "Gold-Franc"),
("PYG", "Guarani"),
("GNF", "Guinea Franc"),
("GYD", "Guyana Dollar"),
("HTG", "Haitian gourde"),
("HKD", "Hong Kong Dollar"),
("UAH", "Hryvnia"),
("ISK", "Iceland Krona"),
("INR", "Indian Rupee"),
("IRR", "Iranian Rial"),
("IQD", "Iraqi Dinar"),
("IMP", "Isle of Man Pound"),
("JMD", "Jamaican Dollar"),
("JOD", "Jordanian Dinar"),
("KES", "Kenyan Shilling"),
("PGK", "Kina"),
("LAK", "Kip"),
("KWD", "Kuwaiti Dinar"),
("AOA", "Kwanza"),
("MMK", "Kyat"),
("GEL", "Lari"),
("LVL", "Latvian Lats"),
("LBP", "Lebanese Pound"),
("ALL", "Lek"),
("HNL", "Lempira"),
("SLL", "Leone"),
("LSL", "Lesotho loti"),
("LRD", "Liberian Dollar"),
("LYD", "Libyan Dinar"),
("SZL", "Lilangeni"),
("LTL", "Lithuanian Litas"),
("MGA", "Malagasy Ariary"),
("MWK", "Malawian Kwacha"),
("MYR", "Malaysian Ringgit"),
("TMM", "Manat"),
("MUR", "Mauritius Rupee"),
("MZN", "Metical"),
("MXV", "Mexican Unidad de Inversion (UDI)"),
("MXN", "Mexican peso"),
("MDL", "Moldovan Leu"),
("MAD", "Moroccan Dirham"),
("BOV", "Mvdol"),
("NGN", "Naira"),
("ERN", "Nakfa"),
("NAD", "Namibian Dollar"),
("NPR", "Nepalese Rupee"),
("ANG", "Netherlands Antillian Guilder"),
("ILS", "New Israeli Sheqel"),
("RON", "New Leu"),
("TWD", "New Taiwan Dollar"),
("NZD", "New Zealand Dollar"),
("KPW", "North Korean Won"),
("NOK", "Norwegian Krone"),
("PEN", "Nuevo Sol"),
("MRO", "Ouguiya"),
("TOP", "Paanga"),
("PKR", "Pakistan Rupee"),
("XPD", "Palladium"),
("MOP", "Pataca"),
("PHP", "Philippine Peso"),
("XPT", "Platinum"),
("GBP", "Pound Sterling"),
("BWP", "Pula"),
("QAR", "Qatari Rial"),
("GTQ", "Quetzal"),
("ZAR", "Rand"),
("OMR", "Rial Omani"),
("KHR", "Riel"),
("MVR", "Rufiyaa"),
("IDR", "Rupiah"),
("RUB", "Russian Ruble"),
("RWF", "Rwanda Franc"),
("XDR", "SDR"),
("SHP", "Saint Helena Pound"),
("SAR", "Saudi Riyal"),
("RSD", "Serbian Dinar"),
("SCR", "Seychelles Rupee"),
("XAG", "Silver"),
("SGD", "Singapore Dollar"),
("SBD", "Solomon Islands Dollar"),
("KGS", "Som"),
("SOS", "Somali Shilling"),
("TJS", "Somoni"),
("SSP", "South Sudanese Pound"),
("LKR", "Sri Lanka Rupee"),
("XSU", "Sucre"),
("SDG", "Sudanese Pound"),
("SRD", "Surinam Dollar"),
("SEK", "Swedish Krona"),
("CHF", "Swiss Franc"),
("SYP", "Syrian Pound"),
("BDT", "Taka"),
("WST", "Tala"),
("TZS", "Tanzanian Shilling"),
("KZT", "Tenge"),
(
"XXX",
"The codes assigned for transactions where no currency is involved",
),
("TTD", "Trinidad and Tobago Dollar"),
("MNT", "Tugrik"),
("TND", "Tunisian Dinar"),
("TRY", "Turkish Lira"),
("TMT", "Turkmenistan New Manat"),
("TVD", "Tuvalu dollar"),
("AED", "UAE Dirham"),
("XFU", "UIC-Franc"),
("USD", "US Dollar"),
("USN", "US Dollar (Next day)"),
("UGX", "Uganda Shilling"),
("CLF", "Unidad de Fomento"),
("COU", "Unidad de Valor Real"),
("UYI", "Uruguay Peso en Unidades Indexadas (URUIURUI)"),
("UYU", "Uruguayan peso"),
("UZS", "Uzbekistan Sum"),
("VUV", "Vatu"),
("CHE", "WIR Euro"),
("CHW", "WIR Franc"),
("KRW", "Won"),
("YER", "Yemeni Rial"),
("JPY", "Yen"),
("CNY", "Yuan Renminbi"),
("ZMK", "Zambian Kwacha"),
("ZMW", "Zambian Kwacha"),
("ZWD", "Zimbabwe Dollar A/06"),
("ZWN", "Zimbabwe dollar A/08"),
("ZWL", "Zimbabwe dollar A/09"),
("PLN", "Zloty"),
],
default="CHF",
editable=False,
max_length=3,
),
),
migrations.AddField(
model_name="task",
name="amount_offered",
field=djmoney.models.fields.MoneyField(
blank=True,
decimal_places=2,
default_currency="CHF",
max_digits=10,
null=True,
),
),
migrations.AddField(
model_name="task",
name="amount_offered_currency",
field=djmoney.models.fields.CurrencyField(
choices=[
("XUA", "ADB Unit of Account"),
("AFN", "Afghani"),
("DZD", "Algerian Dinar"),
("ARS", "Argentine Peso"),
("AMD", "Armenian Dram"),
("AWG", "Aruban Guilder"),
("AUD", "Australian Dollar"),
("AZN", "Azerbaijanian Manat"),
("BSD", "Bahamian Dollar"),
("BHD", "Bahraini Dinar"),
("THB", "Baht"),
("PAB", "Balboa"),
("BBD", "Barbados Dollar"),
("BYN", "Belarussian Ruble"),
("BYR", "Belarussian Ruble"),
("BZD", "Belize Dollar"),
("BMD", "Bermudian Dollar (customarily known as Bermuda Dollar)"),
("BTN", "Bhutanese ngultrum"),
("VEF", "Bolivar Fuerte"),
("BOB", "Boliviano"),
("XBA", "Bond Markets Units European Composite Unit (EURCO)"),
("BRL", "Brazilian Real"),
("BND", "Brunei Dollar"),
("BGN", "Bulgarian Lev"),
("BIF", "Burundi Franc"),
("XOF", "CFA Franc BCEAO"),
("XAF", "CFA franc BEAC"),
("XPF", "CFP Franc"),
("CAD", "Canadian Dollar"),
("CVE", "Cape Verde Escudo"),
("KYD", "Cayman Islands Dollar"),
("CLP", "Chilean peso"),
("XTS", "Codes specifically reserved for testing purposes"),
("COP", "Colombian peso"),
("KMF", "Comoro Franc"),
("CDF", "Congolese franc"),
("BAM", "Convertible Marks"),
("NIO", "Cordoba Oro"),
("CRC", "Costa Rican Colon"),
("HRK", "Croatian Kuna"),
("CUP", "Cuban Peso"),
("CUC", "Cuban convertible peso"),
("CZK", "Czech Koruna"),
("GMD", "Dalasi"),
("DKK", "Danish Krone"),
("MKD", "Denar"),
("DJF", "Djibouti Franc"),
("STD", "Dobra"),
("DOP", "Dominican Peso"),
("VND", "Dong"),
("XCD", "East Caribbean Dollar"),
("EGP", "Egyptian Pound"),
("SVC", "El Salvador Colon"),
("ETB", "Ethiopian Birr"),
("EUR", "Euro"),
("XBB", "European Monetary Unit (E.M.U.-6)"),
("XBD", "European Unit of Account 17(E.U.A.-17)"),
("XBC", "European Unit of Account 9(E.U.A.-9)"),
("FKP", "Falkland Islands Pound"),
("FJD", "Fiji Dollar"),
("HUF", "Forint"),
("GHS", "Ghana Cedi"),
("GIP", "Gibraltar Pound"),
("XAU", "Gold"),
("XFO", "Gold-Franc"),
("PYG", "Guarani"),
("GNF", "Guinea Franc"),
("GYD", "Guyana Dollar"),
("HTG", "Haitian gourde"),
("HKD", "Hong Kong Dollar"),
("UAH", "Hryvnia"),
("ISK", "Iceland Krona"),
("INR", "Indian Rupee"),
("IRR", "Iranian Rial"),
("IQD", "Iraqi Dinar"),
("IMP", "Isle of Man Pound"),
("JMD", "Jamaican Dollar"),
("JOD", "Jordanian Dinar"),
("KES", "Kenyan Shilling"),
("PGK", "Kina"),
("LAK", "Kip"),
("KWD", "Kuwaiti Dinar"),
("AOA", "Kwanza"),
("MMK", "Kyat"),
("GEL", "Lari"),
("LVL", "Latvian Lats"),
("LBP", "Lebanese Pound"),
("ALL", "Lek"),
("HNL", "Lempira"),
("SLL", "Leone"),
("LSL", "Lesotho loti"),
("LRD", "Liberian Dollar"),
("LYD", "Libyan Dinar"),
("SZL", "Lilangeni"),
("LTL", "Lithuanian Litas"),
("MGA", "Malagasy Ariary"),
("MWK", "Malawian Kwacha"),
("MYR", "Malaysian Ringgit"),
("TMM", "Manat"),
("MUR", "Mauritius Rupee"),
("MZN", "Metical"),
("MXV", "Mexican Unidad de Inversion (UDI)"),
("MXN", "Mexican peso"),
("MDL", "Moldovan Leu"),
("MAD", "Moroccan Dirham"),
("BOV", "Mvdol"),
("NGN", "Naira"),
("ERN", "Nakfa"),
("NAD", "Namibian Dollar"),
("NPR", "Nepalese Rupee"),
("ANG", "Netherlands Antillian Guilder"),
("ILS", "New Israeli Sheqel"),
("RON", "New Leu"),
("TWD", "New Taiwan Dollar"),
("NZD", "New Zealand Dollar"),
("KPW", "North Korean Won"),
("NOK", "Norwegian Krone"),
("PEN", "Nuevo Sol"),
("MRO", "Ouguiya"),
("TOP", "Paanga"),
("PKR", "Pakistan Rupee"),
("XPD", "Palladium"),
("MOP", "Pataca"),
("PHP", "Philippine Peso"),
("XPT", "Platinum"),
("GBP", "Pound Sterling"),
("BWP", "Pula"),
("QAR", "Qatari Rial"),
("GTQ", "Quetzal"),
("ZAR", "Rand"),
("OMR", "Rial Omani"),
("KHR", "Riel"),
("MVR", "Rufiyaa"),
("IDR", "Rupiah"),
("RUB", "Russian Ruble"),
("RWF", "Rwanda Franc"),
("XDR", "SDR"),
("SHP", "Saint Helena Pound"),
("SAR", "Saudi Riyal"),
("RSD", "Serbian Dinar"),
("SCR", "Seychelles Rupee"),
("XAG", "Silver"),
("SGD", "Singapore Dollar"),
("SBD", "Solomon Islands Dollar"),
("KGS", "Som"),
("SOS", "Somali Shilling"),
("TJS", "Somoni"),
("SSP", "South Sudanese Pound"),
("LKR", "Sri Lanka Rupee"),
("XSU", "Sucre"),
("SDG", "Sudanese Pound"),
("SRD", "Surinam Dollar"),
("SEK", "Swedish Krona"),
("CHF", "Swiss Franc"),
("SYP", "Syrian Pound"),
("BDT", "Taka"),
("WST", "Tala"),
("TZS", "Tanzanian Shilling"),
("KZT", "Tenge"),
(
"XXX",
"The codes assigned for transactions where no currency is involved",
),
("TTD", "Trinidad and Tobago Dollar"),
("MNT", "Tugrik"),
("TND", "Tunisian Dinar"),
("TRY", "Turkish Lira"),
("TMT", "Turkmenistan New Manat"),
("TVD", "Tuvalu dollar"),
("AED", "UAE Dirham"),
("XFU", "UIC-Franc"),
("USD", "US Dollar"),
("USN", "US Dollar (Next day)"),
("UGX", "Uganda Shilling"),
("CLF", "Unidad de Fomento"),
("COU", "Unidad de Valor Real"),
("UYI", "Uruguay Peso en Unidades Indexadas (URUIURUI)"),
("UYU", "Uruguayan peso"),
("UZS", "Uzbekistan Sum"),
("VUV", "Vatu"),
("CHE", "WIR Euro"),
("CHW", "WIR Franc"),
("KRW", "Won"),
("YER", "Yemeni Rial"),
("JPY", "Yen"),
("CNY", "Yuan Renminbi"),
("ZMK", "Zambian Kwacha"),
("ZMW", "Zambian Kwacha"),
("ZWD", "Zimbabwe Dollar A/06"),
("ZWN", "Zimbabwe dollar A/08"),
("ZWL", "Zimbabwe dollar A/09"),
("PLN", "Zloty"),
],
default="CHF",
editable=False,
max_length=3,
),
),
]
|
adfinis-sygroup/timed-backend
|
timed/projects/migrations/0009_auto_20201201_1412.py
|
Python
|
agpl-3.0
| 38,360
|
export const divides = (y) => (x) => y % x === 0;
export const divisible = (y) => (x) => x % y === 0;
|
aureooms/js-predicate
|
src/numbers.js
|
JavaScript
|
agpl-3.0
| 102
|
'use strict';
var REGEXP = /^(.+)\s+(.+)$/
function parser(str) {
var deps = str.replace(/(\#(.*))/g, '').split("\n").reduce( (accum, line) => {
var match = line.match(REGEXP);
if (!match) return accum;
let name = match[1].trim(), version = match[2].trim()
accum.push({
name: name,
version: version || '*',
type: 'runtime'
});
return accum;
}, []);
return deps;
}
module.exports = parser;
|
librariesio/librarian-parsers
|
lib/parsers/gpm.js
|
JavaScript
|
agpl-3.0
| 446
|
<?php
/*********************************************************************************
* Zurmo is a customer relationship management program developed by
* Zurmo, Inc. Copyright (C) 2013 Zurmo Inc.
*
* Zurmo is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* Zurmo 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 or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact Zurmo, Inc. with a mailing address at 27 North Wacker Drive
* Suite 370 Chicago, IL 60606. or at email address contact@zurmo.com.
*
* The interactive user interfaces in original and modified versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the Zurmo
* logo and Zurmo copyright notice. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display the words
* "Copyright Zurmo Inc. 2013. All rights reserved".
********************************************************************************/
class CampaignsDefaultController extends ZurmoModuleController
{
const USER_REQUIRED_MODULES_ACCESS_FILTER_PATH =
'application.modules.campaigns.controllers.filters.UserCanAccessRequiredModulesForCampaignCheckControllerFilter';
const ZERO_MODELS_CHECK_FILTER_PATH =
'application.modules.campaigns.controllers.filters.CampaignsZeroModelsCheckControllerFilter';
const JOBS_CHECK_FILTER_PATH =
'application.modules.campaigns.controllers.filters.CampaignJobsCheckControllerFilter';
public static function getListBreadcrumbLinks()
{
$title = Zurmo::t('CampaignsModule', 'Campaigns');
return array($title);
}
public static function getDetailsAndEditBreadcrumbLinks()
{
return array(Zurmo::t('CampaignsModule', 'Campaigns') => array('default/list'));
}
public function filters()
{
return array_merge(parent::filters(),
array(
array(
static::USER_REQUIRED_MODULES_ACCESS_FILTER_PATH,
'controller' => $this,
),
array(
static::ZERO_MODELS_CHECK_FILTER_PATH . ' + list, index',
'controller' => $this,
'activeActionElementType' => 'CampaignsMenu',
'breadCrumbLinks' => static::getListBreadcrumbLinks(),
),
array(
static::JOBS_CHECK_FILTER_PATH . ' + create, details, edit',
),
)
);
}
public function actionIndex()
{
$this->actionList();
}
public function actionList()
{
$pageSize = Yii::app()->pagination->resolveActiveForCurrentUserByType(
'listPageSize', get_class($this->getModule()));
$campaign = new Campaign(false);
$searchForm = new CampaignsSearchForm($campaign);
$listAttributesSelector = new ListAttributesSelector('CampaignsListView',
get_class($this->getModule()));
$searchForm->setListAttributesSelector($listAttributesSelector);
$dataProvider = $this->resolveSearchDataProvider(
$searchForm,
$pageSize,
null,
'CampaignsSearchView'
);
if (isset($_GET['ajax']) && $_GET['ajax'] == 'list-view')
{
$mixedView = $this->makeListView(
$searchForm,
$dataProvider
);
$view = new CampaignsPageView($mixedView);
}
else
{
$mixedView = $this->makeActionBarSearchAndListView($searchForm, $dataProvider,
'SecuredActionBarForMarketingListsSearchAndListView', null, 'CampaignsMenu');
$breadCrumbLinks = static::getListBreadcrumbLinks();
$view = new CampaignsPageView(MarketingDefaultViewUtil::
makeViewWithBreadcrumbsForCurrentUser($this, $mixedView, $breadCrumbLinks,
'MarketingBreadCrumbView'));
}
echo $view->render();
}
public function actionCreate()
{
$this->actionCreateByModel(new Campaign());
}
public function actionCreateFromRelation($relationAttributeName, $relationModelId, $relationModuleId, $redirectUrl)
{
$campaign = $this->resolveNewModelByRelationInformation( new Campaign(),
$relationAttributeName,
(int)$relationModelId,
$relationModuleId);
$this->actionCreateByModel($campaign, $redirectUrl);
}
protected function actionCreateByModel(Campaign $campaign, $redirectUrl = null)
{
$breadCrumbLinks = static::getDetailsAndEditBreadcrumbLinks();
$breadCrumbLinks[] = Zurmo::t('Core', 'Create');
$campaign->status = Campaign::STATUS_ACTIVE;
$campaign->supportsRichText = true;
$campaign->enableTracking = true;
$editView = new CampaignEditView($this->getId(), $this->getModule()->getId(),
$this->attemptToSaveModelFromPost($campaign, $redirectUrl),
Zurmo::t('CampaignsModule', 'Create Campaign'));
$view = new CampaignsPageView(MarketingDefaultViewUtil::
makeViewWithBreadcrumbsForCurrentUser($this, $editView,
$breadCrumbLinks, 'MarketingBreadCrumbView'));
echo $view->render();
}
public function actionDetails($id)
{
$campaign = static::getModelAndCatchNotFoundAndDisplayError('Campaign', intval($id));
ControllerSecurityUtil::resolveAccessCanCurrentUserReadModel($campaign);
AuditEvent::logAuditEvent('ZurmoModule', ZurmoModule::AUDIT_EVENT_ITEM_VIEWED,
array(strval($campaign), 'CampaignsModule'), $campaign);
$breadCrumbView = CampaignsStickySearchUtil::
resolveBreadCrumbViewForDetailsControllerAction($this,
'CampaignsSearchView', $campaign);
$detailsAndRelationsView = $this->makeDetailsAndRelationsView($campaign, 'CampaignsModule',
'CampaignDetailsAndRelationsView',
Yii::app()->request->getRequestUri(),
$breadCrumbView);
$view = new CampaignsPageView(MarketingDefaultViewUtil::
makeStandardViewForCurrentUser($this, $detailsAndRelationsView));
echo $view->render();
}
public function actionEdit($id)
{
$campaign = Campaign::getById(intval($id));
ControllerSecurityUtil::resolveAccessCanCurrentUserWriteModel($campaign);
if ($campaign->status != Campaign::STATUS_ACTIVE)
{
Yii::app()->user->setFlash('notification',
Zurmo::t('CampaignsModule', 'This campaign has already started, you can only edit its name, rights and permissions.')
);
}
$breadCrumbLinks = static::getDetailsAndEditBreadcrumbLinks();
$breadCrumbLinks[] = StringUtil::getChoppedStringContent(strval($campaign), 25);
//todo: wizard
$editView = new CampaignEditView($this->getId(), $this->getModule()->getId(),
$this->attemptToSaveModelFromPost($campaign),
strval($campaign));
$view = new CampaignsPageView(MarketingDefaultViewUtil::
makeViewWithBreadcrumbsForCurrentUser($this, $editView,
$breadCrumbLinks, 'MarketingBreadCrumbView'));
echo $view->render();
}
public function actionDelete($id)
{
$campaign = static::getModelAndCatchNotFoundAndDisplayError('Campaign', intval($id));
ControllerSecurityUtil::resolveAccessCanCurrentUserDeleteModel($campaign);
$campaign->delete();
$this->redirect(array($this->getId() . '/index'));
}
public function actionModalList()
{
$modalListLinkProvider = new SelectFromRelatedEditModalListLinkProvider(
$_GET['modalTransferInformation']['sourceIdFieldId'],
$_GET['modalTransferInformation']['sourceNameFieldId'],
$_GET['modalTransferInformation']['modalId']
);
echo ModalSearchListControllerUtil::setAjaxModeAndRenderModalSearchList($this, $modalListLinkProvider);
}
public function actionDrillDownDetails($campaignItemId)
{
$id = (int) $campaignItemId;
$campaignItem = CampaignItem::getById($id);
ControllerSecurityUtil::resolveAccessCanCurrentUserReadModel($campaignItem->campaign);
ControllerSecurityUtil::resolveAccessCanCurrentUserReadModel($campaignItem->contact);
ControllerSecurityUtil::resolveAccessCanCurrentUserReadModel($campaignItem->emailMessage);
echo CampaignItemSummaryListViewColumnAdapter::resolveDrillDownMetricsSummaryContent($campaignItem);
}
protected static function getSearchFormClassName()
{
return 'CampaignsSearchForm';
}
protected static function getZurmoControllerUtil()
{
return new CampaignZurmoControllerUtil();
}
}
?>
|
jhuymaier/zurmo
|
app/protected/modules/campaigns/controllers/DefaultController.php
|
PHP
|
agpl-3.0
| 11,777
|
import React from 'react';
import { IGameDef } from '../../games';
import Card from '@material-ui/core/Card';
import CardActionArea from '@material-ui/core/CardActionArea';
import CardContent from '@material-ui/core/CardContent';
import CardMedia from '@material-ui/core/CardMedia';
import Typography from '@material-ui/core/Typography';
interface IGameCardProps {
game: IGameDef;
}
export class GameCard extends React.Component<IGameCardProps, {}> {
render() {
return (
<Card style={{ marginBottom: '16px' }}>
<CardMedia
style={{ height: '250px' }}
image={this.props.game.imageURL}
title={this.props.game.name}
/>
<CardContent>
<Typography gutterBottom={true} variant="h5" component="h2">
{this.props.game.name}
</Typography>
<Typography component="p">
{this.props.game.description}
</Typography>
</CardContent>
</Card>
);
}
}
|
Felizardo/turnato
|
src/App/Game/GameCard.tsx
|
TypeScript
|
agpl-3.0
| 982
|
/* MAP FUNCTIONS */
var mapStyle = 'Wikimedia';
var mapOverlay = null;
var resultMapLayer = null;
var resultMapOverlay = null;
var resultMapObj = null;
var mapMarkers = {};
var cityLat = null;
var cityLon = null;
function toggleMap() {
backScrollY = null;
if (!resultMapObj) {
if (confirm('Karte laden? (Langsam auf alten Handies!)')) {
initMap();
}
} else {
var ele = document.getElementById('overMap');
if (ele) {
if (ele.style.display/*(!ele.style.left) || (ele.style.left !== '0' && ele.style.left !== '0px')*/) {
unhide(ele);
//ele.style.left = '0px';
ele.style.overflow = "";
document.getElementById('resultMapCtnr').style.left='380px';
document.getElementById('mapBtn').innerText = "Karte";
document.getElementById('hideSideBarBtnIcon').setAttribute('transform', 'rotate(0)');
} else {
hide(ele);
//ele.style.left = "-380px";
ele.style.overflow = "hidden";
document.getElementById('resultMapCtnr').style.left='0px';
document.getElementById('mapBtn').innerText = "Liste";
document.getElementById('hideSideBarBtnIcon').setAttribute('transform', 'rotate(180) translate(-193 -512)');
if ((!searchResult) || ((!searchResult.visible) && (!searchResult.invisible))) {
find();
}
}
}
}
}
function isMapInFront() {
var ele = document.getElementById('overMap');
return ele && ele.style.left && ele.style.left == '-300px';
}
function setMapProvider(newStyle, newOverlay) {
mapStyle = newStyle;
mapOverlay = newOverlay;
if (resultMapObj) {
if (resultMapLayer) {
resultMapObj.removeLayer(resultMapLayer);
}
try {
resultMapLayer = L.tileLayer.provider(mapStyle);
} catch(exception) {
resultMapLayer = L.tileLayer.provider('OpenStreetMap.DE');
}
resultMapObj.addLayer(resultMapLayer);
if (mapStyle == 'Esri.WorldImagery') {
document.getElementById('resultMap').classList.add('darkMap');
} else {
document.getElementById('resultMap').classList.remove('darkMap');
}
if (resultMapOverlay) {
resultMapObj.removeLayer(resultMapOverlay);
}
if (mapOverlay) {
try {
resultMapOverlay = L.tileLayer.provider(mapOverlay);
resultMapObj.addLayer(resultMapOverlay);
} catch(exception) {
resultMapOverlay = null;
mapOverlay = null;
}
}
}
var ablauf = new Date();
var in400Tagen = ablauf.getTime() + (400 * 24 * 60 * 60 * 1000);
ablauf.setTime(in400Tagen);
document.cookie = 'map='+mapStyle+'; path=/; expires=' + ablauf.toGMTString();
document.cookie = 'ovl='+(mapOverlay ? mapOverlay : '') +'; path=/; expires=' + ablauf.toGMTString();
}
function doInitMap() {
document.getElementById('mapBtn').style.display = 'inline-block';
if (resultMapObj != null || (!L) || (!L.tileLayer) || (!L.tileLayer.provider)) {
console.log(resultMapObj == null ?
"Leaflet Scripts not yet loaded." :
"Map is already loaded");
return;
}
resultMapObj = L.map('resultMap', {
center: [lat, lon],
tapTolerance: 30,
tap: true,
zoom: 12,
zoomControl: false
});
L.control.zoom({
position:'bottomright'
}).addTo(resultMapObj);
setMapProvider(mapStyle, mapOverlay);
resultMapObj.fitBounds([[bbox[0], bbox[1]], [bbox[2], bbox[3]]]);
resultMapObj.on('moveend', function (event) {
bbox = [resultMapObj.getBounds().getSouthWest().lat, resultMapObj.getBounds().getSouthWest().lng, resultMapObj.getBounds().getNorthEast().lat, resultMapObj.getBounds().getNorthEast().lng];
lat = resultMapObj.getCenter().lat;
lon = resultMapObj.getCenter().lng;
if (resultMapObj.getZoom() < 15) {
city = lat + ',' + lon;
cityLat = null;
cityLon = null;
document.getElementById('city').placeholder = 'Ort: ' + city;
} else {
if ((!cityLat) || (!cityLon) || Math.abs(resultMapObj.getCenter().lat - cityLat) > 0.01 || Math.abs(resultMapObj.getCenter().lng - cityLon) > 0.018) {
document.getElementById('city').placeholder = 'Ort: ' + lat + ',' + lon;
mapCenter2City();
}
}
disableOverlay = true;
find();
window.setTimeout(function () {
disableOverlay = false;
}, 333);
saveCity();
document.location.hash = ';' + lat + ',' + lon;
});
toggleMap();
find();
}
function initMap() {
var lfcss = document.createElement("LINK");
lfcss.rel = "stylesheet";
lfcss.href = "https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.5.1/leaflet.css";
document.head.appendChild(lfcss);
var facss = document.createElement("LINK");
facss.rel = "stylesheet";
facss.href = "https://wap.kartevonmorgen.org/map-icons/css/map-icons.min.css";
document.head.appendChild(facss);
var lfjs = document.createElement("SCRIPT");
lfjs.type = "text/javascript";
lfjs.src = "https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.5.1/leaflet.js";
lfjs.onload = function() {
var lfjs2 = document.createElement("SCRIPT");
lfjs2.type = "text/javascript";
lfjs2.src = "https://cdnjs.cloudflare.com/ajax/libs/leaflet-providers/1.3.1/leaflet-providers.min.js";
lfjs2.onload = doInitMap;
document.body.appendChild(lfjs2);
};
document.body.appendChild(lfjs);
var mapBtnEle = document.getElementById('btnInitMap');
if (mapBtnEle) {
mapBtnEle.innerText="Karte zeigen";
mapBtnEle.onclick=toggleMap;
}
}
function removeUnnecessaryMapMarkers() {
if (mapMarkers && resultMapObj) {
for (e in mapMarkers) {
var marker = mapMarkers[e];
if (marker && ((!e.match) || !e.match(/^osm_.+/))) {
if ( ((!searchResult['visible']) || (searchResult['visible'] && searchResult['visible'].indexOf(e) < 0))
&& ((!searchResult['invisible']) || (searchResult['invisible'] && searchResult['invisible'].indexOf(e) < 0)) ) {
resultMapObj.removeLayer(marker);
delete mapMarkers[e];
}
} else if (marker && !osmIsResult(e)) {
resultMapObj.removeLayer(marker);
delete mapMarkers[e];
}
}
}
}
function addMapMarker(entry) {
if (resultMapObj && (!mapMarkers[entry.id]) && entry && entry.lat && entry.lng) {
var cat = categories && entry.categories && entry.categories.length
&& entry.categories[0] ? categories[entry.categories[0]] : null;
mapMarkers[entry.id] = L.marker({lat:entry.lat, lng:entry.lng}, {icon: entry.ratings && entry.ratings.total && entry.ratings.total >= 0
? L.divIcon({iconSize: [27,41], iconAnchor: [13,41], className:'mapMarker ' + (cat ? cat.name.replace('#', '') :'unknown'), html:'<i class="map-icon map-icon-map-pin"></i>'})
: L.divIcon({iconSize: [16,17], iconAnchor: [8,8], className:'mapMarkerCircle ' + (cat ? cat.name.replace('#', '') :'unknown'), html:'<i class="map-icon map-icon-circle"></i>'})
});
mapMarkers[entry.id].addTo(resultMapObj);
mapMarkers[entry.id].bindPopup('<a href="#" onclick="displayDetails('+"'"+entry.id+"'"+');if(isMapInFront()){toggleMap();backScrollY=null;}else{backScrollY=-1;}event.preventDefault();return false;">'+entry.title+'</a>', {offset: entry.ratings && entry.ratings.total && entry.ratings.total >= 0 ? [0,10] : [0,30]});
mapMarkers[entry.id].bindTooltip(entry.title, {direction: 'bottom'});
mapMarkers[entry.id].on('click', createOnMarkerClickFunc(entry.id) );
}
}
function createOnMarkerClickFunc(entryId) {
return function(){ displayDetails(entryId);if(isMapInFront()){toggleMap();backScrollY=null;}else{backScrollY=-1;}};
}
function mapCenter2City() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4) {
if (xhttp.status == 200 && xhttp.responseText) {
var res = JSON.parse(xhttp.responseText);
if (res && res.address) {
if (res.address.city || res.address.town || res.address.village) {
city = res.address.city ? res.address.city : res.address.town ? res.address.town : res.address.village;
document.getElementById('city').placeholder = 'Ort: ' + city;
cityLat = res.lat;
cityLon = res.lon;
saveCity();
}
}
}
}
};
xhttp.open("GET",
'https://open.mapquestapi.com/nominatim/v1/reverse.php?key=SJpWKrsbH6PZGQ9KZvyibuGzRkXS1LAw' +
'&format=json&zoom=18&lat=' + lat + '&lon=' + lon, true);
xhttp.send();
}
|
regenduft/mobile.kartevonmorgen
|
map.js
|
JavaScript
|
agpl-3.0
| 10,196
|
import validatePostData from './validatePostData'
describe('validatePostData', () => {
var user, inGroup, notInGroup
before(function () {
inGroup = new Group({slug: 'foo', name: 'Foo', group_data_type: 1 })
notInGroup = new Group({slug: 'bar', name: 'Bar', group_data_type: 1 })
user = new User({name: 'Cat', email: 'a@b.c'})
return Promise.join(
inGroup.save(),
notInGroup.save(),
user.save()
).then(function () {
return user.joinGroup(inGroup)
})
})
it('fails if no name is provided', () => {
const fn = () => validatePostData(null, {})
expect(fn).to.throw(/title can't be blank/)
})
it('fails if an invalid type is provided', () => {
const fn = () => validatePostData(null, {name: 't', type: 'thread'})
expect(fn).to.throw(/not a valid type/)
})
it('fails if no group_ids are provided', () => {
const fn = () => validatePostData(null, {name: 't'})
expect(fn).to.throw(/no communities specified/)
})
it('fails if there is a group_id for a group user is not a member of', () => {
const data = {name: 't', group_ids: [inGroup.id, notInGroup.id]}
return validatePostData(user.id, data)
.catch(function (e) {
expect(e.message).to.match(/unable to post to all those communities/)
})
})
it('fails if a blank name is provided', () => {
const fn = () => validatePostData(null, {name: ' ', group_ids: [inGroup.id]})
expect(fn).to.throw(/title can't be blank/)
})
it('fails if there are more than 3 topicNames', () => {
const fn = () => validatePostData(null, {
name: 't',
group_ids: [inGroup.id],
topicNames: ['la', 'ra', 'bar', 'far']})
expect(fn).to.throw(/too many topics in post, maximum 3/)
})
it('continues the promise chain if name is provided and user is member of communities', () => {
const data = {name: 't', group_ids: [inGroup.id]}
return validatePostData(user.id, data)
.catch(() => expect.fail('should resolve'))
})
it('continues the promise chain if valid type is provided', () => {
const data = {name: 't', type: Post.Type.PROJECT, group_ids: [inGroup.id]}
return validatePostData(user.id, data)
.catch(() => expect.fail('should resolve'))
})
})
|
Hylozoic/hylo-node
|
api/models/post/validatePostData.test.js
|
JavaScript
|
agpl-3.0
| 2,258
|
<?php
namespace Drupal\EECSAdvise\Entity;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityChangedInterface;
use Drupal\user\EntityOwnerInterface;
/**
* Provides an interface defining a Student entity.
* @ingroup EECSAdvise
*/
interface StudentInterface extends ContentEntityInterface, EntityOwnerInterface, EntityChangedInterface {
}
|
Munsy/EECSAdvise
|
src/Entity/StudentInterface.php
|
PHP
|
agpl-3.0
| 369
|
MWF.APPDSMD = MWF.xApplication.query.StatementDesigner;
MWF.APPDSMD.options = {
"multitask": true,
"executable": false
};
MWF.xDesktop.requireApp("query.StatementDesigner", "Statement", null, false);
MWF.xApplication.query.StatementDesigner.Main = new Class({
Extends: MWF.xApplication.Common.Main,
Implements: [Options, Events],
options: {
"style": "default",
"name": "query.StatementDesigner",
"icon": "icon.png",
"title": MWF.APPDSMD.LP.title,
"appTitle": MWF.APPDSMD.LP.title,
"id": "",
"tooltip": {
"unCategory": MWF.APPDSMD.LP.unCategory
},
"actions": null,
"category": null,
"processData": null
},
onQueryLoad: function(){
this.shortcut = true;
if (this.status){
this.options.application = this.status.applicationId;
this.application = this.status.application;
this.options.id = this.status.id;
}
if (!this.options.id){
this.options.desktopReload = false;
this.options.title = this.options.title + "-"+MWF.APPDSMD.LP.newStatement;
}
if (!this.actions) this.actions = MWF.Actions.get("x_query_assemble_designer");
this.lp = MWF.xApplication.query.StatementDesigner.LP;
this.addEvent("queryClose", function(e){
if (this.explorer){
this.explorer.reload();
}
}.bind(this));
},
loadApplication: function(callback){
this.createNode();
if (!this.options.isRefresh){
this.maxSize(function(){
this.openStatement(function(){
if (callback) callback();
});
}.bind(this));
}else{
this.openStatement(function(){
if (callback) callback();
});
}
if (!this.options.readMode) this.addKeyboardEvents();
},
createNode: function(){
this.content.setStyle("overflow", "hidden");
this.node = new Element("div", {
"styles": {"width": "100%", "height": "100%", "overflow": "hidden"}
}).inject(this.content);
},
addKeyboardEvents: function(){
this.addEvent("keySave", function(e){
this.keySave(e);
}.bind(this));
},
keySave: function(e){
if (this.shortcut) {
this.view.save();
e.preventDefault();
}
},
getApplication:function(callback){
if (!this.application){
this.actions.getApplication(this.options.application, function(json){
this.application = {"name": json.data.name, "id": json.data.id};
if (callback) callback();
}.bind(this));
}else{
if (callback) callback();
}
},
openStatement: function(callback){
this.getApplication(function(){
this.loadNodes();
this.loadStatementListNodes();
// this.loadToolbar();
this.loadContentNode();
this.loadProperty();
// this.loadTools();
this.resizeNode();
this.addEvent("resize", this.resizeNode.bind(this));
this.loadStatement(function(){
if (callback) callback();
}.bind(this));
this.setScrollBar(this.designerStatementArea, null, {
"V": {"x": 0, "y": 0},
"H": {"x": 0, "y": 0}
});
}.bind(this));
},
loadNodes: function(){
this.statementListNode = new Element("div", {
"styles": this.css.statementListNode
}).inject(this.node);
this.designerNode = new Element("div", {
"styles": this.css.designerNode
}).inject(this.node);
this.contentNode = new Element("div", {
"styles": this.css.contentNode
}).inject(this.node);
this.formContentNode = this.contentNode;
},
loadStatementListNodes: function(){
this.statementListTitleNode = new Element("div", {
"styles": this.css.statementListTitleNode,
"text": this.lp.statement
}).inject(this.statementListNode);
this.statementListResizeNode = new Element("div", {"styles": this.css.statementListResizeNode}).inject(this.statementListNode);
this.statementListAreaSccrollNode = new Element("div", {"styles": this.css.statementListAreaSccrollNode}).inject(this.statementListNode);
this.statementListAreaNode = new Element("div", {"styles": this.css.statementListAreaNode}).inject(this.statementListAreaSccrollNode);
this.loadStatementListResize();
this.loadStatementList();
},
loadStatementListResize: function(){
this.statementListResize = new Drag(this.statementListResizeNode,{
"snap": 1,
"onStart": function(el, e){
var x = (Browser.name=="firefox") ? e.event.clientX : e.event.x;
var y = (Browser.name=="firefox") ? e.event.clientY : e.event.y;
el.store("position", {"x": x, "y": y});
var size = this.statementListAreaSccrollNode.getSize();
el.store("initialWidth", size.x);
}.bind(this),
"onDrag": function(el, e){
var x = (Browser.name=="firefox") ? e.event.clientX : e.event.x;
var bodySize = this.content.getSize();
var position = el.retrieve("position");
var initialWidth = el.retrieve("initialWidth").toFloat();
var dx = x.toFloat() - position.x.toFloat();
var width = initialWidth+dx;
if (width> bodySize.x/2) width = bodySize.x/2;
if (width<40) width = 40;
this.contentNode.setStyle("margin-left", width+1);
this.statementListNode.setStyle("width", width);
}.bind(this)
});
this.statementListResizeNode.addEvents({
"touchstart": function(e){
el = e.target;
var x = (Browser.name=="firefox") ? e.page.clientX : e.page.x;
var y = (Browser.name=="firefox") ? e.page.clientY : e.page.y;
el.store("position", {"x": x, "y": y});
var size = this.statementListAreaSccrollNode.getSize();
el.store("initialWidth", size.x);
}.bind(this),
"touchmove": function(e){
el = e.target;
var x = (Browser.name=="firefox") ? e.page.clientX : e.page.x;
var bodySize = this.content.getSize();
var position = el.retrieve("position");
var initialWidth = el.retrieve("initialWidth").toFloat();
var dx = x.toFloat() - position.x.toFloat();
var width = initialWidth+dx;
if (width> bodySize.x/2) width = bodySize.x/2;
if (width<40) width = 40;
this.contentNode.setStyle("margin-left", width+1);
this.statementListNode.setStyle("width", width);
}.bind(this)
});
},
loadStatementList: function(){
this.actions.listStatement(this.application.id, function (json) {
json.data.each(function(statement){
this.createListStatementItem(statement);
}.bind(this));
}.bind(this), null, false);
},
//列示所有查询配置列表
createListStatementItem: function(statement, isNew){
var _self = this;
var listStatementItem = new Element("div", {"styles": this.css.listStatementItem}).inject(this.statementListAreaNode, (isNew) ? "top": "bottom");
var listStatementItemIcon = new Element("div", {"styles": this.css.listStatementItemIcon}).inject(listStatementItem);
var listStatementItemText = new Element("div", {"styles": this.css.listStatementItemText, "text": (statement.name) ? statement.name+" ("+statement.alias+")" : this.lp.newStatement}).inject(listStatementItem);
listStatementItem.store("statement", statement);
listStatementItem.addEvents({
"dblclick": function(e){_self.loadStatementByData(this, e);},
"mouseover": function(){if (_self.currentListStatementItem!=this) this.setStyles(_self.css.listStatementItem_over);},
"mouseout": function(){if (_self.currentListStatementItem!=this) this.setStyles(_self.css.listStatementItem);}
});
},
//打开查询配置
loadStatementByData: function(node, e){
var statement = node.retrieve("statement");
if (!statement.isNewStatement){
var _self = this;
var options = {
"appId": "query.StatementDesigner"+statement.id,
"onQueryLoad": function(){
this.actions = _self.actions;
this.category = _self;
this.options.id = statement.id;
this.application = _self.application;
this.explorer = _self.explorer;
}
};
this.desktop.openApplication(e, "query.StatementDesigner", options);
}
},
//loadContentNode-------------------------------------------
loadContentNode: function(){
this.contentToolbarNode = new Element("div", {
"styles": this.css.contentToolbarNode
}).inject(this.contentNode);
if (!this.options.readMode) this.loadContentToolbar();
this.editContentNode = new Element("div", {
"styles": this.css.editContentNode
}).inject(this.contentNode);
this.loadEditContent();
// this.loadEditContent(function(){
// // if (this.designDcoument) this.designDcoument.body.setStyles(this.css.designBody);
// // if (this.designNode) this.designNode.setStyles(this.css.designNode);
// }.bind(this));
},
loadContentToolbar: function(callback){
this.getFormToolbarHTML(function(toolbarNode){
var spans = toolbarNode.getElements("span");
spans.each(function(item, idx){
var img = item.get("MWFButtonImage");
if (img){
item.set("MWFButtonImage", this.path+""+this.options.style+"/toolbar/"+img);
}
}.bind(this));
$(toolbarNode).inject(this.contentToolbarNode);
MWF.require("MWF.widget.Toolbar", function(){
this.toolbar = new MWF.widget.Toolbar(toolbarNode, {"style": "ProcessCategory"}, this);
this.toolbar.load();
if (this.statement) if (this.statement.checkToolbars) this.statement.checkToolbars();
if (callback) callback();
}.bind(this));
}.bind(this));
},
getFormToolbarHTML: function(callback){
var toolbarUrl = this.path+this.options.style+"/toolbars.html";
var r = new Request.HTML({
url: toolbarUrl,
method: "get",
onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript){
var toolbarNode = responseTree[0];
if (callback) callback(toolbarNode);
}.bind(this),
onFailure: function(xhr){
this.notice("request processToolbars error: "+xhr.responseText, "error");
}.bind(this)
});
r.send();
},
loadEditContent: function(callback){
this.designNode = new Element("div.designNode", {
"styles": this.css.designNode
}).inject(this.editContentNode);
},
//loadProperty--------------------------------------
loadProperty: function(){
this.designerTitleNode = new Element("div", {
"styles": this.css.designerTitleNode,
"text": this.lp.property
}).inject(this.designerNode);
this.designerResizeBar = new Element("div", {
"styles": this.css.designerResizeBar
}).inject(this.designerNode);
this.loadDesignerResize();
this.designerContentNode = new Element("div.designerContentNode", {
"styles": this.css.designerContentNode
}).inject(this.designerNode);
this.designerStatementArea = new Element("div.designerStatementArea", {
"styles": this.css.designerStatementArea
}).inject(this.designerContentNode);
this.propertyDomArea = this.designerStatementArea;
this.designerStatementPercent = 0.3;
this.designerContentResizeNode = new Element("div.designerContentResizeNode", {
"styles": this.css.designerContentResizeNode
}).inject(this.designerContentNode);
this.designerContentArea = new Element("div.designerContentArea", {
"styles": this.css.designerContentArea
}).inject(this.designerContentNode);
this.propertyContentArea = this.designerContentArea;
this.loadDesignerStatementResize();
//this.setPropertyContent();
this.designerNode.addEvent("keydown", function(e){e.stopPropagation();});
},
loadDesignerResize: function(){
this.designerResize = new Drag(this.designerResizeBar,{
"snap": 1,
"onStart": function(el, e){
var x = (Browser.name=="firefox") ? e.event.clientX : e.event.x;
var y = (Browser.name=="firefox") ? e.event.clientY : e.event.y;
el.store("position", {"x": x, "y": y});
var size = this.designerNode.getSize();
el.store("initialWidth", size.x);
}.bind(this),
"onDrag": function(el, e){
var x = (Browser.name=="firefox") ? e.event.clientX : e.event.x;
// var y = e.event.y;
var bodySize = this.content.getSize();
var position = el.retrieve("position");
var initialWidth = el.retrieve("initialWidth").toFloat();
var dx = position.x.toFloat()-x.toFloat();
var width = initialWidth+dx;
if (width> bodySize.x/2) width = bodySize.x/2;
if (width<40) width = 40;
var nodeSize = this.node.getSize();
var scale = width/nodeSize.x;
var scale = scale*100;
this.contentNode.setStyle("margin-right", scale+"%");
this.designerNode.setStyle("width", scale+"%");
}.bind(this)
});
},
loadDesignerStatementResize: function(){
this.designerContentResize = new Drag(this.designerContentResizeNode, {
"snap": 1,
"onStart": function(el, e){
var x = (Browser.name=="firefox") ? e.event.clientX : e.event.x;
var y = (Browser.name=="firefox") ? e.event.clientY : e.event.y;
el.store("position", {"x": x, "y": y});
var size = this.designerStatementArea.getSize();
el.store("initialHeight", size.y);
}.bind(this),
"onDrag": function(el, e){
var size = this.designerContentNode.getSize();
// var x = e.event.x;
var y = (Browser.name=="firefox") ? e.event.clientY : e.event.y;
var position = el.retrieve("position");
var dy = y.toFloat()-position.y.toFloat();
var initialHeight = el.retrieve("initialHeight").toFloat();
var height = initialHeight+dy;
if (height<40) height = 40;
if (height> size.y-40) height = size.y-40;
this.designerStatementPercent = height/size.y;
this.setDesignerStatementResize();
}.bind(this)
});
},
setDesignerStatementResize: function(){
var size = this.designerContentNode.getSize();
var contentHeight;
debugger;
if( this.statement && this.statement.selectMode && this.statement.selectMode.contains("view") ){
this.designerContentResizeNode.show();
this.designerStatementArea.show();
var resizeNodeSize = this.designerContentResizeNode.getSize();
var height = size.y-resizeNodeSize.y;
var domHeight = this.designerStatementPercent*height;
contentHeight = height-domHeight;
this.designerStatementArea.setStyle("height", ""+domHeight+"px");
this.designerContentArea.setStyle("height", ""+contentHeight+"px");
}else{
contentHeight = size.y;
this.designerContentResizeNode.hide();
this.designerStatementArea.hide();
this.designerContentArea.setStyle("height", ""+contentHeight+"px");
}
if (this.statement){
if (this.statement.currentSelectedModule){
if (this.statement.currentSelectedModule.property){
var tab = this.statement.currentSelectedModule.property.propertyTab;
if (tab){
var tabTitleSize = tab.tabNodeContainer.getSize();
tab.pages.each(function(page){
var topMargin = page.contentNodeArea.getStyle("margin-top").toFloat();
var bottomMargin = page.contentNodeArea.getStyle("margin-bottom").toFloat();
var tabContentNodeAreaHeight = contentHeight - topMargin - bottomMargin - tabTitleSize.y.toFloat()-15;
page.contentNodeArea.setStyle("height", tabContentNodeAreaHeight);
}.bind(this));
}
}
}
}
},
//resizeNode------------------------------------------------
resizeNode: function(){
var nodeSize = this.node.getSize();
this.contentNode.setStyle("height", ""+nodeSize.y+"px");
this.designerNode.setStyle("height", ""+nodeSize.y+"px");
var contentToolbarMarginTop = this.contentToolbarNode.getStyle("margin-top").toFloat();
var contentToolbarMarginBottom = this.contentToolbarNode.getStyle("margin-bottom").toFloat();
var allContentToolberSize = this.contentToolbarNode.getComputedSize();
var y = nodeSize.y - allContentToolberSize.totalHeight - contentToolbarMarginTop - contentToolbarMarginBottom;
this.editContentNode.setStyle("height", ""+y+"px");
if (this.designNode){
var designMarginTop = this.designNode.getStyle("margin-top").toFloat();
var designMarginBottom = this.designNode.getStyle("margin-bottom").toFloat();
y = nodeSize.y - allContentToolberSize.totalHeight - contentToolbarMarginTop - contentToolbarMarginBottom - designMarginTop - designMarginBottom;
this.designNode.setStyle("height", ""+y+"px");
}
titleSize = this.designerTitleNode.getSize();
titleMarginTop = this.designerTitleNode.getStyle("margin-top").toFloat();
titleMarginBottom = this.designerTitleNode.getStyle("margin-bottom").toFloat();
titlePaddingTop = this.designerTitleNode.getStyle("padding-top").toFloat();
titlePaddingBottom = this.designerTitleNode.getStyle("padding-bottom").toFloat();
y = titleSize.y+titleMarginTop+titleMarginBottom+titlePaddingTop+titlePaddingBottom;
y = nodeSize.y-y;
this.designerContentNode.setStyle("height", ""+y+"px");
this.designerResizeBar.setStyle("height", ""+y+"px");
this.setDesignerStatementResize();
titleSize = this.statementListTitleNode.getSize();
titleMarginTop = this.statementListTitleNode.getStyle("margin-top").toFloat();
titleMarginBottom = this.statementListTitleNode.getStyle("margin-bottom").toFloat();
titlePaddingTop = this.statementListTitleNode.getStyle("padding-top").toFloat();
titlePaddingBottom = this.statementListTitleNode.getStyle("padding-bottom").toFloat();
nodeMarginTop = this.statementListAreaSccrollNode.getStyle("margin-top").toFloat();
nodeMarginBottom = this.statementListAreaSccrollNode.getStyle("margin-bottom").toFloat();
y = titleSize.y+titleMarginTop+titleMarginBottom+titlePaddingTop+titlePaddingBottom+nodeMarginTop+nodeMarginBottom;
y = nodeSize.y-y;
this.statementListAreaSccrollNode.setStyle("height", ""+y+"px");
this.statementListResizeNode.setStyle("height", ""+y+"px");
},
//loadStatement------------------------------------------
loadStatement: function(callback){
debugger;
this.getStatementData(this.options.id, function(vdata){
this.setTitle(this.options.appTitle + "-"+vdata.name);
this.taskitem.setText(this.options.appTitle + "-"+vdata.name);
this.options.appTitle = this.options.appTitle + "-"+vdata.name;
this.statement = new MWF.xApplication.query.StatementDesigner.Statement(this, vdata);
this.statement.load();
if(callback)callback()
}.bind(this));
},
getStatementData: function(id, callback){
if (!this.options.id){
this.loadNewStatementData(callback);
}else{
this.loadStatementData(id, callback);
}
},
loadNewStatementData: function(callback){
var url = "../x_component_query_StatementDesigner/$Statement/statement.json";
MWF.getJSON(url, {
"onSuccess": function(obj){
this.actions.getUUID(function(id){
obj.id=id;
obj.isNewStatement = true;
obj.application = this.application.id;
this.createListStatementItem(obj, true);
if (callback) callback(obj);
}.bind(this));
}.bind(this),
"onerror": function(text){
this.notice(text, "error");
}.bind(this),
"onRequestFailure": function(xhr){
this.notice(xhr.responseText, "error");
}.bind(this)
});
},
loadStatementData: function(id, callback){
this.actions.getStatement(id, function(json){
if (json){
var data = json.data;
if (!this.application){
this.actions.getApplication(data.query, function(json){
this.application = {"name": json.data.name, "id": json.data.id};
if (callback) callback(data);
}.bind(this));
}else{
if (callback) callback(data);
}
}
}.bind(this));
},
preview : function(){
this.statement.preview();
},
saveStatement: function(){
this.statement.save(function(){
var name = this.statement.data.name;
this.setTitle(MWF.APPDSMD.LP.title + "-"+name);
this.options.desktopReload = true;
this.options.id = this.statement.data.id;
}.bind(this));
},
statementHelp: function(){
var content = new Element("div", {"styles": {"margin": "20px"}});
content.set("html", this.lp.tableHelp);
o2.DL.open({
"title": "table help",
"content": content,
"width": 500,
"height": 300,
"buttonList": [
{
"text": "ok",
"action": function(){this.close();}
}
]
});
},
recordStatus: function(){
//if (this.tab){
var openViews = [];
openViews.push(this.statement.data.id);
var currentId = this.statement.data.id;
return {
"id": this.options.id,
"application": this.application,
"openViews": openViews,
"currentId": currentId
};
//}
//return {"id": this.options.id, "application": this.application};
}
// dictionaryExplode: function(){
// this.view.explode();
// },
// dictionaryImplode: function(){
// this.view.implode();
// }
//recordStatus: function(){
// return {"id": this.options.id};
//},
});
|
o2oa/o2oa
|
o2web/source/x_component_query_StatementDesigner/Main.js
|
JavaScript
|
agpl-3.0
| 24,111
|
class RolesController < ApplicationController
load_and_authorize_resource
# GET /roles
def index
@roles = Role.all
respond_to do |format|
format.html # index.html.erb
end
end
# GET /roles/1
def show
@role = Role.find(params[:id])
respond_to do |format|
format.html # show.html.erb
end
end
# GET /roles/new
def new
@role = Role.new
respond_to do |format|
format.html # new.html.erb
end
end
# GET /roles/1/edit
def edit
@role = Role.find(params[:id])
end
# POST /roles
def create
@role = Role.new(params[:role])
respond_to do |format|
if @role.save
format.html { redirect_to @role, notice: 'Role was successfully created.' }
else
format.html { render action: "new" }
end
end
end
# PUT /roles/1
def update
@role = Role.find(params[:id])
respond_to do |format|
if @role.update_attributes(params[:role])
format.html { redirect_to @role, notice: 'Role was successfully updated.' }
else
format.html { render action: "edit" }
end
end
end
# DELETE /roles/1
def destroy
@role = Role.find(params[:id])
@role.destroy
respond_to do |format|
format.html { redirect_to roles_url }
end
end
end
|
iressgrad15/growstuff
|
app/controllers/roles_controller.rb
|
Ruby
|
agpl-3.0
| 1,306
|
<?php
require_once dirname(__FILE__).'/../lib/parcoursGeneratorConfiguration.class.php';
require_once dirname(__FILE__).'/../lib/parcoursGeneratorHelper.class.php';
/**
* parcours actions.
*
* @package sf_sandbox
* @subpackage parcours
* @author Your name here
* @version SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
*/
class parcoursActions extends autoParcoursActions
{
public function executeCopy(sfWebRequest $request)
{
$parcours = $this->getRoute()->getObject();
$interactifs = $parcours->Interactif->getPrimaryKeys();
$parcours_copy = $parcours->copy();
$parcours_copy->setGuid(Guid::generate());
$parcours_copy->setLibelle($parcours->getLibelle()."-copie");
$parcours_copy->setCreatedAt(date('Y-m-d H:i:s'));
$parcours_copy->setUpdatedAt(date('Y-m-d H:i:s'));
$parcours_copy->link('Interactif', array_values($interactifs));
$parcours_copy->save();
return $this->redirect($this->getController()->genUrl('parcours/edit?guid='.$parcours_copy->getGuid()));
}
protected function buildQuery()
{
$query = parent::buildQuery();
if ($this->getUser()->hasPermission('admin'))
{
return $query;
}
else
{
$expositions = $this->getUser()->getGuardUser()->getExposition()->toArray();
$guids = array();
foreach ($expositions as $expo)
{
$guids[] = $expo['guid'];
}
$query->leftJoin('r.Exposition e');
$clause = '(';
if(count($guids))
{
$clause .= 'e.guid IN (\''.join('\', \'', $guids).'\') OR ';
}
$clause .= 'r.created_at > \'' . date('Y-m-d H:i:s', strtotime('-8 hours')).'\'';
$clause .= ')';
$query->andWhere($clause);
return $query;
}
}
public function executeAutocomplete(sfWebRequest $request)
{
$tags = Doctrine::getTable('Parcours')->getForAutocomplete($request->getParameter('term'));
$response = '["'.join($tags,'","').'"]';
return $this->renderText($response);
}
}
|
CapSciences/navinum
|
apps/backend/modules/parcours/actions/actions.class.php
|
PHP
|
agpl-3.0
| 2,030
|
# THIS CONFIG WAS AUTOMATICALLY CREATED FROM TEMPLATE CONFIG FILE TO OPEN A MIDI FILE
# YOU CAN EDIT THIS CONFIG FILE TO OPEN THIS FILE AGAIN
# If you want to change template config file, that is copied each time you open a MIDI file, please go to configs folder in your File browser
# Template configs are not accessible from MGen GUI, you will need to change it outside of the program
# Template config was created by removing Midi_file parameter from source config
include "include/CA2.pl"
# This config was created from default config file configs\GenCA2.pl
# Created at 2018-04-08 11:27:28
Midi_file = music\Counterpoint 2 voices\solution\MTE1110-TP07-Solu.mid
corrections = 0
max_correct_ms = 2000
|
rualark/MGen
|
MGen/configs/GenCA2/MTE1110-TP07-Solu.pl
|
Perl
|
agpl-3.0
| 707
|
<?php
/**
* Website that displays live PHP documentation of classes and functions with the help of reflection.
* Copyright (C) 2015 Marcel Joachim Kloubert <marcel.kloubert@gmx.net>
*
* 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/>.
*/
(isset($this) &&
($this instanceof \Zend\View\Renderer\RendererInterface)) OR die();
|
mkloubert/phpLiveDoc
|
views/common_view_include.php
|
PHP
|
agpl-3.0
| 987
|
{{Extend "layout"}}
{{Block "title"}}{{if HasSuffix URL.Path "_add"}}{{"添加用户"|T}}{{else}}{{"修改用户"|T}}{{end}}{{/Block}}
{{Block "breadcrumb"}}
{{Super}}
<li><a href="{{BackendURL}}/manager/user">{{"用户列表"|T}}</a></li>
<li class="active">{{if HasSuffix URL.Path "_add"}}{{"添加"|T}}{{else}}{{"修改"|T}}{{end}}</li>
{{/Block}}
{{Block "head"}}
<link rel="stylesheet" type="text/css" href="{{AssetsURL}}/js/jquery.select2/select2.css" />
{{/Block}}
{{Block "main"}}
<div class="row">
<div class="col-md-12">
<div class="block-flat">
<div class="header">
<h3>{{if HasSuffix URL.Path "_add"}}{{"添加用户"|T}}{{else}}{{"修改用户"|T}}{{end}}</h3>
</div>
<div class="content">
<form class="form-horizontal group-border-dashed" data-parsley-validate method="POST" id="profile-form" data-secret="{{SM2PublicKey}}" action="">
<div class="form-group">
<label class="col-sm-2 control-label">{{"头像"|T}}</label>
<div class="col-sm-8">
<div class="avatar-upload">
{{$avatar := Form "avatar"}}
<img src="{{if $avatar}}{{AddSuffix $avatar "_200_200"}}{{else}}{{AssetsURL}}/images/user_128.png{{end}}" class="profile-avatar img-thumbnail" onerror="this.onerror=null;this.src='{{AssetsURL}}/images/user_128.png';" />
<input id="fileupload" type="file" name="files[]">
<input type="hidden" id="avatar-image" name="avatar-small" value="{{if $avatar}}{{AddSuffix $avatar "_200_200"}}{{end}}" />
<input type="hidden" id="avatar-image-original" name="avatar" value="{{$avatar}}" />
<div id="progress" class="overlay"></div>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">{{"用户名"|T}}</label>
<div class="col-sm-8">
<input type="text" class="form-control" data-parsley-trigger="change" required name="username" value="{{Form "username"}}">
</div>
</div>
{{if HasSuffix URL.Path "_edit"}}
<div class="form-group">
<label class="col-sm-2 control-label"></label>
<div class="col-sm-8">
<label>
<input type="checkbox" data-parsley-trigger="change" name="modifyPwd" value="1"{{if Form "modifyPwd"}} checked{{end}}>
{{"修改密码"|T}}</label>
</div>
</div>
<div class="form-group new-password">
<label class="col-sm-2 control-label">{{"新密码"|T}}</label>
<div class="col-sm-8">
<input type="password" class="form-control" data-parsley-trigger="change" name="password" value="{{Form "password"}}">
</div>
</div>
<div class="form-group new-password">
<label class="col-sm-2 control-label">{{"确认新密码"|T}}</label>
<div class="col-sm-8">
<input type="password" class="form-control" data-parsley-trigger="change" name="confirmPwd" value="{{Form "confirmPwd"}}">
</div>
</div>
{{else}}
<div class="form-group">
<label class="col-sm-2 control-label">{{"密码"|T}}</label>
<div class="col-sm-8">
<input type="password" class="form-control" data-parsley-trigger="change" required name="password" value="{{Form "password"}}">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">{{"确认密码"|T}}</label>
<div class="col-sm-8">
<input type="password" class="form-control" data-parsley-trigger="change" required name="confirmPwd" value="{{Form "confirmPwd"}}">
</div>
</div>
{{end}}
<div class="form-group">
<label class="col-sm-2 control-label">{{"E-mail"|T}}</label>
<div class="col-sm-8">
<input type="email" class="form-control" data-parsley-trigger="change" required name="email" value="{{Form "email"}}">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">{{"手机号码"|T}}</label>
<div class="col-sm-8">
<input type="text" class="form-control" data-parsley-trigger="change" required name="mobile" value="{{Form "mobile"}}">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">{{"性别"|T}}</label>
<div class="col-sm-8">
{{$v := Form "gendar"}}
<div class="radio radio-primary radio-inline">
<input type="radio" value="secret" name="gendar" id="gendar-secret"{{if or (eq $v "secret") (eq $v "")}} checked{{end}}> <label for="gendar-secret">{{"保密"|T}}</label>
</div>
<div class="radio radio-primary radio-inline">
<input type="radio" value="female" name="gendar" id="gendar-female"{{if eq $v "female"}} checked{{end}}> <label for="gendar-female">{{"女"|T}}</label>
</div>
<div class="radio radio-primary radio-inline">
<input type="radio" value="male" name="gendar" id="gendar-male"{{if eq $v "male"}} checked{{end}}> <label for="gendar-male">{{"男"|T}}</label>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">{{"状态"|T}}</label>
<div class="col-sm-8">
{{$v := Form "disabled"}}
<div class="radio radio-primary radio-inline">
<input type="radio" value="N" id="disabled-N" name="disabled"{{if or (eq $v "N") (eq $v "")}} checked{{end}}><label for="disabled-N">{{"启用"|T}}</label>
</div>
<div class="radio radio-danger radio-inline">
<input type="radio" value="Y" id="disabled-Y" name="disabled"{{if eq $v "Y"}} checked{{end}}><label for="disabled-Y">{{"禁用"|T}}</label>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">{{"角色"|T}}</label>
<div class="col-sm-8">
<select id="select2roles" data-parsley-trigger="change" required name="roleIds" multiple="multiple">
{{range $k, $v := Stored.roleList}}
<option value="{{$v.Id}}"{{if isChecked $v.Id}} selected="selected"{{end}}>{{$v.Name}}</option>
{{end}}
</select>
</div>
</div>
<div class="form-group form-submit-group">
<div class="col-sm-9 col-sm-offset-2">
<button type="submit" class="btn btn-primary btn-lg"><i class="fa fa-save"></i> {{"保存"|T}}</button>
<button type="reset" class="btn btn-default btn-lg"><i class="fa fa-refresh"></i> {{"重置"|T}}</button>
</div>
</div>
</form>
{{Include "modal_crop_image"}}
</div><!-- /.content -->
</div><!-- /.block-flat -->
</div>
</div>
{{/Block}}
{{Block "footer"}}
<script src="{{AssetsURL}}/js/jquery.select2/select2.min.js" type="text/javascript"></script>
<script src="{{AssetsURL}}/js/loader/loader.min.js?t={{BuildTime}}"></script>
<script src="{{AssetsURL}}/js/editor/editor.min.js?t={{BuildTime}}"></script>
<script type="text/javascript" src="{{AssetsURL}}/js/crypto/crypto-js.min.js?t={{BuildTime}}"></script>
<script type="text/javascript" src="{{AssetsURL}}/js/crypto/sm2.min.js?t={{BuildTime}}"></script>
<script type="text/javascript" src="{{AssetsURL}}/js/crypto/helper.js?t={{BuildTime}}"></script>
<script type="text/javascript">
$(function(){
//{{if HasSuffix URL.Path "_edit"}}
$('input[name="modifyPwd"]').on('click',function(){
if($(this).prop('checked')){
$('.new-password').show();
}else{
$('.new-password').hide();
}
});
if($('input[name="modifyPwd"]').prop('checked')){
$('.new-password').show();
}else{
$('.new-password').hide();
}
//{{end}}
$('#select2roles').select2({width:'100%'});
App.editor.cropImage('{{BackendUploadURL "avatar"}}',"#avatar-image",'#avatar-image-original');
submitEncryptedData('#profile-form');
});
</script>
{{/Block}}
|
admpub/nging
|
template/backend/manager/user_edit.html
|
HTML
|
agpl-3.0
| 8,893
|
# frozen-string_literal: true
module Decidim
class RemovedFromGroupEvent < Decidim::Events::SimpleEvent
delegate :url_helpers, to: "Decidim::Core::Engine.routes"
i18n_attributes :user_group_name
def resource_url
url_helpers.group_manage_users_url(
user_group_nickname,
host: user.organization.host
)
end
def resource_path
url_helpers.group_manage_users_path(user_group_nickname)
end
def user_group_nickname
extra.dig("user_group_nickname")
end
def user_group_name
extra.dig("user_group_name")
end
end
end
|
codegram/decidim
|
decidim-core/app/events/decidim/removed_from_group_event.rb
|
Ruby
|
agpl-3.0
| 601
|
using InfinniPlatform.Cache.Clusterization;
using InfinniPlatform.IoC;
using InfinniPlatform.MessageQueue;
namespace InfinniPlatform.Cache.IoC
{
/// <summary>
/// Dependency registration module for <see cref="InfinniPlatform.Cache" />.
/// </summary>
public class TwoLayerCacheContainerModule : IContainerModule
{
/// <summary>
/// Creates new instance of <see cref="TwoLayerCacheContainerModule"/>.
/// </summary>
public TwoLayerCacheContainerModule(TwoLayerCacheOptions options)
{
_options = options;
}
private readonly TwoLayerCacheOptions _options;
/// <inheritdoc />
public void Load(IContainerBuilder builder)
{
builder.RegisterInstance(_options).AsSelf().SingleInstance();
builder.RegisterType<InMemoryCacheFactory>().AsSelf().SingleInstance();
builder.RegisterFactory(CreateInMemoryCacheFactory).As<IInMemoryCacheFactory>().SingleInstance();
builder.RegisterType<SharedCacheFactory>().AsSelf().SingleInstance();
builder.RegisterFactory(CreateSharedCacheFactory).As<ISharedCacheFactory>().SingleInstance();
builder.RegisterType<TwoLayerCacheStateObserver>().AsSelf().SingleInstance();
builder.RegisterType<TwoLayerCacheStateObserverStub>().AsSelf().SingleInstance();
builder.RegisterFactory(CreateTwoLayerCacheStateObserver).As<ITwoLayerCacheStateObserver>().SingleInstance();
builder.RegisterType<TwoLayerCache>().As<ITwoLayerCache>().SingleInstance();
// Clusterization
builder.RegisterType<TwoLayerCacheResetKeyConsumer>().As<IConsumer>().SingleInstance();
}
private IInMemoryCacheFactory CreateInMemoryCacheFactory(IContainerResolver resolver)
{
return _options.InMemoryCacheFactory?.Invoke(resolver) ?? resolver.Resolve<InMemoryCacheFactory>();
}
private ISharedCacheFactory CreateSharedCacheFactory(IContainerResolver resolver)
{
return _options.SharedCacheFactory?.Invoke(resolver) ?? resolver.Resolve<SharedCacheFactory>();
}
private ITwoLayerCacheStateObserver CreateTwoLayerCacheStateObserver(IContainerResolver resolver)
{
var twoLayerCacheStateObserver = _options.TwoLayerCacheStateObserver?.Invoke(resolver);
if (twoLayerCacheStateObserver == null)
{
if (TwoLayerCacheStateObserver.CanBeCreated(resolver))
{
twoLayerCacheStateObserver = resolver.Resolve<TwoLayerCacheStateObserver>();
}
else
{
twoLayerCacheStateObserver = resolver.Resolve<TwoLayerCacheStateObserverStub>();
}
}
return twoLayerCacheStateObserver;
}
}
}
|
InfinniPlatform/InfinniPlatform
|
InfinniPlatform.Cache.TwoLayer/IoC/TwoLayerCacheContainerModule.cs
|
C#
|
agpl-3.0
| 2,913
|
DELETE FROM PROTOCOL_PERSONS WHERE PROTOCOL_PERSON_ROLE_ID='CRC'
/
commit
/
DECLARE
li_ver_nbr NUMBER(8):=1;
li_proto_person_id NUMBER(12,0);
ls_proto_num VARCHAR2(20 BYTE);
li_sequence NUMBER(4,0);
li_seq NUMBER(4,0);
ls_person_id VARCHAR2(40);
li_rolodex_id NUMBER(12,0);
ls_full_name VARCHAR2(90);
li_sequence_num NUMBER(4,0);
li_submission_type NUMBER(3,0);
li_submission_status NUMBER(3,0);
ls_proto VARCHAR2(10);
ls_number VARCHAR2(20):=null;
ls_test_number VARCHAR2(20);
li_flag NUMBER;
li_protocol_id NUMBER(12,0);
li_rolodex_count NUMBER;
ls_protocol_num VARCHAR2(20);
li_seq_num NUMBER(4);
li_mit_seq_num NUMBER(4,0);
CURSOR c_proto is
select PROTOCOL_NUMBER,SEQUENCE_NUMBER FROM PROTOCOL ORDER BY PROTOCOL_NUMBER,SEQUENCE_NUMBER;
r_proto c_proto%ROWTYPE;
CURSOR c_inv(as_protocol_number VARCHAR2,as_sequence NUMBER) IS
SELECT inv.PROTOCOL_NUMBER,inv.SEQUENCE_NUMBER,inv.PERSON_ID,inv.PERSON_NAME,inv.NON_EMPLOYEE_FLAG,inv.CORRESPONDENT_TYPE_CODE,inv.COMMENTS,inv.UPDATE_TIMESTAMP,inv.UPDATE_USER,
p.SSN,p.LAST_NAME,p.FIRST_NAME,p.MIDDLE_NAME,p.PRIOR_NAME,p.USER_NAME,p.EMAIL_ADDRESS,p.DATE_OF_BIRTH,p.AGE,p.AGE_BY_FISCAL_YEAR,p.GENDER,p.RACE,p.EDUCATION_LEVEL,p.DEGREE,p.MAJOR,
p.IS_HANDICAPPED,p.HANDICAP_TYPE,p.IS_VETERAN,p.VETERAN_TYPE,p.VISA_CODE,p.VISA_TYPE,p.VISA_RENEWAL_DATE,p.HAS_VISA,p.OFFICE_LOCATION,p.OFFICE_PHONE,p.SECONDRY_OFFICE_LOCATION,p.SECONDRY_OFFICE_PHONE,
p.SCHOOL,p.YEAR_GRADUATED,p.DIRECTORY_DEPARTMENT,p.SALUTATION,p.COUNTRY_OF_CITIZENSHIP,p.PRIMARY_TITLE,p.DIRECTORY_TITLE,p.HOME_UNIT,p.IS_FACULTY,p.IS_GRADUATE_STUDENT_STAFF,p.IS_RESEARCH_STAFF,p.IS_SERVICE_STAFF,
p.IS_SUPPORT_STAFF,p.IS_OTHER_ACCADEMIC_GROUP,p.IS_MEDICAL_STAFF,p.VACATION_ACCURAL,p.IS_ON_SABBATICAL,p.ID_PROVIDED,p.ID_VERIFIED,p.ADDRESS_LINE_1,p.ADDRESS_LINE_2,p.ADDRESS_LINE_3,p.CITY,p.COUNTY,p.STATE,p.POSTAL_CODE,
p.COUNTRY_CODE,p.FAX_NUMBER,p.PAGER_NUMBER,p.MOBILE_PHONE_NUMBER,p.ERA_COMMONS_USER_NAME FROM OSP$PROTOCOL_CORRESPONDENTS@coeus.kuali inv LEFT JOIN OSP$PERSON@coeus.kuali p ON (inv.PERSON_ID=p.PERSON_ID)
WHERE PROTOCOL_NUMBER=as_protocol_number AND SEQUENCE_NUMBER =(SELECT MAX(Pi.SEQUENCE_NUMBER) FROM OSP$PROTOCOL_CORRESPONDENTS@coeus.kuali pi where pi.PROTOCOL_NUMBER=inv.PROTOCOL_NUMBER and Pi.SEQUENCE_NUMBER<=as_sequence);
r_inv c_inv%rowtype;
BEGIN
IF c_proto%ISOPEN THEN
CLOSE c_proto;
END IF;
OPEN c_proto;
LOOP
FETCH c_proto INTO r_proto;
EXIT WHEN c_proto%NOTFOUND;
ls_protocol_num:=r_proto.PROTOCOL_NUMBER;
li_seq:=r_proto.SEQUENCE_NUMBER;
select FN_GET_SEQ(ls_protocol_num,li_seq) into li_mit_seq_num from dual;
IF c_inv%ISOPEN THEN
CLOSE c_inv;
END IF;
OPEN c_inv(ls_protocol_num,li_mit_seq_num);
LOOP
FETCH c_inv INTO r_inv;
EXIT WHEN c_inv%NOTFOUND;
ls_proto_num:=r_inv.PROTOCOL_NUMBER;
li_sequence:=r_inv.SEQUENCE_NUMBER;
SELECT SEQ_PROTOCOL_ID.NEXTVAL INTO li_proto_person_id FROM DUAL;
begin
SELECT PROTOCOL_ID INTO li_protocol_id FROM PROTOCOL WHERE PROTOCOL_NUMBER=ls_proto_num AND SEQUENCE_NUMBER=li_seq;
exception
when others then
dbms_output.put_line('Error while fetching PROTOCOL_ID using PROTOCOL_NUMBER:'||ls_proto_num||'and SEQUENCE_NUMBER:'||li_seq||'and error is:'||sqlerrm);
end;
li_rolodex_id:=null;
ls_person_id:=null;
IF r_inv.NON_EMPLOYEE_FLAG='Y' THEN
select count(rolodex_id) into li_rolodex_count from ROLODEX where to_char(rolodex_id)=r_inv.PERSON_ID;
if li_rolodex_count>0 then
li_rolodex_id:=r_inv.PERSON_ID;
ls_person_id:=null;
ls_full_name:=r_inv.PERSON_NAME;
else
ls_person_id :=r_inv.PERSON_ID;
li_rolodex_id:=null;
ls_full_name:=r_inv.PERSON_NAME;
end if;
ELSE
ls_full_name:=r_inv.PERSON_NAME;
ls_person_id:=r_inv.PERSON_ID;
END IF;
INSERT INTO PROTOCOL_PERSONS(PROTOCOL_PERSON_ID,PROTOCOL_ID,PROTOCOL_NUMBER,SEQUENCE_NUMBER,PERSON_ID,PERSON_NAME,PROTOCOL_PERSON_ROLE_ID,ROLODEX_ID,AFFILIATION_TYPE_CODE,UPDATE_TIMESTAMP,UPDATE_USER,VER_NBR,OBJ_ID,COMMENTS
,SSN,LAST_NAME,FIRST_NAME,MIDDLE_NAME,FULL_NAME,PRIOR_NAME,USER_NAME,EMAIL_ADDRESS,DATE_OF_BIRTH,AGE,AGE_BY_FISCAL_YEAR,GENDER,RACE,EDUCATION_LEVEL,DEGREE,MAJOR,IS_HANDICAPPED,HANDICAP_TYPE,IS_VETERAN,VETERAN_TYPE,VISA_CODE,VISA_TYPE,VISA_RENEWAL_DATE,HAS_VISA,OFFICE_LOCATION,OFFICE_PHONE,SECONDRY_OFFICE_LOCATION,SECONDRY_OFFICE_PHONE,SCHOOL,YEAR_GRADUATED
,DIRECTORY_DEPARTMENT,SALUTATION,COUNTRY_OF_CITIZENSHIP,PRIMARY_TITLE,DIRECTORY_TITLE,HOME_UNIT,IS_FACULTY,IS_GRADUATE_STUDENT_STAFF,IS_RESEARCH_STAFF,IS_SERVICE_STAFF,IS_SUPPORT_STAFF,IS_OTHER_ACCADEMIC_GROUP,IS_MEDICAL_STAFF,VACATION_ACCURAL,IS_ON_SABBATICAL,ID_PROVIDED,ID_VERIFIED,ADDRESS_LINE_1,ADDRESS_LINE_2,ADDRESS_LINE_3,CITY,COUNTY,STATE,POSTAL_CODE,COUNTRY_CODE,FAX_NUMBER,PAGER_NUMBER,MOBILE_PHONE_NUMBER,ERA_COMMONS_USER_NAME)
VALUES(li_proto_person_id,li_protocol_id,ls_proto_num,li_seq,ls_person_id,r_inv.PERSON_NAME,'CRC',li_rolodex_id,NULL,r_inv.UPDATE_TIMESTAMP,LOWER(r_inv.UPDATE_USER),li_ver_nbr,SYS_GUID(),r_inv.COMMENTS
,r_inv.SSN,r_inv.LAST_NAME,r_inv.FIRST_NAME,r_inv.MIDDLE_NAME,r_inv.PERSON_NAME,r_inv.PRIOR_NAME,r_inv.USER_NAME,r_inv.EMAIL_ADDRESS,r_inv.DATE_OF_BIRTH,r_inv.AGE,r_inv.AGE_BY_FISCAL_YEAR,r_inv.GENDER,r_inv.RACE,r_inv.EDUCATION_LEVEL,r_inv.DEGREE,r_inv.MAJOR,r_inv.IS_HANDICAPPED,r_inv.HANDICAP_TYPE,r_inv.IS_VETERAN,r_inv.VETERAN_TYPE,r_inv.VISA_CODE,r_inv.VISA_TYPE,r_inv.VISA_RENEWAL_DATE,r_inv.HAS_VISA,r_inv.OFFICE_LOCATION,r_inv.OFFICE_PHONE,r_inv.SECONDRY_OFFICE_LOCATION,r_inv.SECONDRY_OFFICE_PHONE,r_inv.SCHOOL,r_inv.YEAR_GRADUATED
,r_inv.DIRECTORY_DEPARTMENT,r_inv.SALUTATION,r_inv.COUNTRY_OF_CITIZENSHIP,r_inv.PRIMARY_TITLE,r_inv.DIRECTORY_TITLE,r_inv.HOME_UNIT,r_inv.IS_FACULTY,r_inv.IS_GRADUATE_STUDENT_STAFF,r_inv.IS_RESEARCH_STAFF,r_inv.IS_SERVICE_STAFF,r_inv.IS_SUPPORT_STAFF,r_inv.IS_OTHER_ACCADEMIC_GROUP,r_inv.IS_MEDICAL_STAFF,r_inv.VACATION_ACCURAL,r_inv.IS_ON_SABBATICAL,r_inv.ID_PROVIDED,r_inv.ID_VERIFIED,r_inv.ADDRESS_LINE_1,r_inv.ADDRESS_LINE_2,r_inv.ADDRESS_LINE_3,r_inv.CITY,r_inv.COUNTY,r_inv.STATE,r_inv.POSTAL_CODE,r_inv.COUNTRY_CODE,r_inv.FAX_NUMBER,r_inv.PAGER_NUMBER,r_inv.MOBILE_PHONE_NUMBER,r_inv.ERA_COMMONS_USER_NAME);
END LOOP;
CLOSE c_inv;
END LOOP;
CLOSE c_proto;
END;
/
commit
/
|
rashikpolus/MIT_KC
|
coeus-db/coeus-db-sql/src/main/resources/edu/mit/kc/sql/migration/DML_MITKC-963_01222015.sql
|
SQL
|
agpl-3.0
| 6,089
|
/* SafeDisk
* Copyright (C) 2014 Frank Laub
*
* 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/>.
*/
#include "CreateDiskDialog.h"
#include "Disk.h"
#include <QMessageBox>
#include <QPushButton>
#include <QFileDialog>
#include <QStandardPaths>
CreateDiskDialog::CreateDiskDialog(QWidget* parent)
: QDialog(parent)
{
setupUi(this);
buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
QStringList paths = QStandardPaths::standardLocations(QStandardPaths::DesktopLocation);
storagePathText->setText(paths[0]);
size_t i = 2;
QString name = "SafeDisk";
while (Disk::collision(storagePath(), name)) {
name = QString("SafeDisk %1").arg(i++);
}
volumeNameLineEdit->setText(name);
}
QString CreateDiskDialog::storagePath() const
{
return storagePathText->text().trimmed();
}
QString CreateDiskDialog::volumeName() const
{
return volumeNameLineEdit->text().trimmed();
}
QString CreateDiskDialog::password() const
{
return passwordLineEdit->text();
}
uint64_t CreateDiskDialog::size() const
{
return volumeSizeDoubleSpinBox->value();
}
void CreateDiskDialog::on_passwordLineEdit_textChanged(const QString&)
{
validate();
}
void CreateDiskDialog::on_repeatLineEdit_textChanged(const QString&)
{
validate();
}
void CreateDiskDialog::on_volumeNameLineEdit_textChanged(const QString&)
{
validate();
}
void CreateDiskDialog::validate()
{
auto button = buttonBox->button(QDialogButtonBox::Ok);
button->setEnabled(false);
if (validateName() && validatePassword()) {
button->setEnabled(true);
}
}
bool CreateDiskDialog::validateName()
{
auto name = volumeNameLineEdit->text().trimmed();
if (name.isEmpty()) {
volumeNameLineEdit->setStyleSheet("background-color: rgb(255, 125, 125)");
return false;
}
if (Disk::collision(storagePath(), name)) {
volumeNameLineEdit->setStyleSheet("background-color: rgb(255, 205, 15)");
return false;
}
volumeNameLineEdit->setStyleSheet("");
return true;
}
bool CreateDiskDialog::validatePassword()
{
auto password = passwordLineEdit->text();
auto repeat = repeatLineEdit->text();
if (password.startsWith(repeat)) {
if (password == repeat) {
repeatLineEdit->setStyleSheet("");
if (!password.isEmpty()) {
return true;
}
}
else {
repeatLineEdit->setStyleSheet("background-color: rgb(255, 205, 15)");
}
}
else if (password != repeat) {
repeatLineEdit->setStyleSheet("background-color: rgb(255, 125, 125)");
}
return false;
}
void CreateDiskDialog::on_choosePushButton_clicked()
{
QString dirName = QFileDialog::getExistingDirectory(this, "Choose Storage Directory", storagePath());
if (dirName.isEmpty()) {
return;
}
storagePathText->setText(dirName);
validate();
}
|
safedisk/safedisk
|
qt/CreateDiskDialog.cpp
|
C++
|
agpl-3.0
| 3,312
|
<?php decorate_with('layout_1col') ?>
<?php use_helper('Date') ?>
<?php slot('title') ?>
<h1 class="multiline">
<?php echo __('Showing %1% results', array('%1%' => $pager->getNbResults())) ?>
<span class="sub"><?php echo __('Rights holder') ?></span>
</h1>
<?php end_slot() ?>
<?php slot('before-content') ?>
<section class="header-options">
<div class="row">
<div class="span6">
<?php echo get_component('search', 'inlineSearch', array(
'label' => __('Search rights holder'))) ?>
</div>
<div class="span6">
<?php echo get_partial('default/sortPicker',
array(
'options' => array(
'lastUpdated' => __('Most recent'),
'alphabetic' => __('Alphabetic'),
'identifier' => __('Identifier')))) ?>
</div>
</div>
</section>
<?php end_slot() ?>
<?php slot('content') ?>
<table class="table table-bordered sticky-enabled">
<thead>
<tr>
<th>
<?php echo __('Name') ?>
</th>
<?php if ('alphabetic' != $sf_request->sort): ?>
<th>
<?php echo __('Updated') ?>
</th>
<?php endif; ?>
</tr>
</thead><tbody>
<?php foreach ($pager->getResults() as $item): ?>
<tr>
<td>
<?php echo link_to(render_title($item), array($item, 'module' => 'rightsholder')) ?>
</td>
<?php if ('alphabetic' != $sf_request->sort): ?>
<td>
<?php echo format_date($item->updatedAt, 'f') ?>
</td>
<?php endif; ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php end_slot() ?>
<?php slot('after-content') ?>
<?php echo get_partial('default/pager', array('pager' => $pager)) ?>
<section class="actions">
<ul>
<li><?php echo link_to(__('Add new'), array('module' => 'rightsholder', 'action' => 'add'), array('class' => 'c-btn')) ?></li>
</ul>
</section>
<?php end_slot() ?>
|
CENDARI/atom
|
apps/qubit/modules/rightsholder/templates/browseSuccess.php
|
PHP
|
agpl-3.0
| 2,009
|
DELETE FROM `weenie` WHERE `class_Id` = 4891;
INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`)
VALUES (4891, 'distillerynectar', 18, '2019-02-10 00:00:00') /* Food */;
INSERT INTO `weenie_properties_int` (`object_Id`, `type`, `value`)
VALUES (4891, 1, 32) /* ItemType - Food */
, (4891, 5, 50) /* EncumbranceVal */
, (4891, 11, 1) /* MaxStackSize */
, (4891, 12, 1) /* StackSize */
, (4891, 13, 50) /* StackUnitEncumbrance */
, (4891, 15, 0) /* StackUnitValue */
, (4891, 16, 8) /* ItemUseable - Contained */
, (4891, 19, 0) /* Value */
, (4891, 33, 1) /* Bonded - Bonded */
, (4891, 89, 4) /* BoosterEnum - Stamina */
, (4891, 90, 8) /* BoostValue */
, (4891, 93, 1044) /* PhysicsState - Ethereal, IgnoreCollisions, Gravity */
, (4891, 114, 1) /* Attuned - Attuned */
, (4891, 8041, 101) /* PCAPRecordedPlacement - Resting */;
INSERT INTO `weenie_properties_bool` (`object_Id`, `type`, `value`)
VALUES (4891, 22, True ) /* Inscribable */
, (4891, 23, True ) /* DestroyOnSell */;
INSERT INTO `weenie_properties_string` (`object_Id`, `type`, `value`)
VALUES (4891, 1, 'Distillery Nectar') /* Name */
, (4891, 14, 'Use this item to drink it.') /* Use */
, (4891, 16, 'A small bottle full of a sweet golden nectar from the lost distillery.') /* LongDesc */
, (4891, 20, 'Bottles of Distillery Nectar') /* PluralName */;
INSERT INTO `weenie_properties_d_i_d` (`object_Id`, `type`, `value`)
VALUES (4891, 1, 0x020000AA) /* Setup */
, (4891, 3, 0x20000014) /* SoundTable */
, (4891, 8, 0x06001012) /* Icon */
, (4891, 22, 0x3400002B) /* PhysicsEffectTable */
, (4891, 8001, 2125841) /* PCAPRecordedWeenieHeader - PluralName, Usable, StackSize, MaxStackSize, Container, Burden */
, (4891, 8003, 32786) /* PCAPRecordedObjectDesc - Inscribable, Attackable, Food */
, (4891, 8005, 137217) /* PCAPRecordedPhysicsDesc - CSetup, STable, PeTable, AnimationFrame */;
INSERT INTO `weenie_properties_i_i_d` (`object_Id`, `type`, `value`)
VALUES (4891, 8000, 0xAE59AFA8) /* PCAPRecordedObjectIID */;
|
ACEmulator/ACE-World
|
Database/3-Core/9 WeenieDefaults/SQL/Food/Food/04891 Distillery Nectar.sql
|
SQL
|
agpl-3.0
| 2,285
|
import * as React from 'react';
import * as styles from './expandable.scss';
interface Props {
content: string;
maxLength: number;
}
interface State {
expanded: boolean;
}
export default class Expandable extends React.Component<Props, State> {
state: State = {
expanded: false
};
toggleExpanded() {
const { expanded } = this.state;
this.setState({
expanded: !expanded
})
}
render() {
const { expanded } = this.state;
const { content, maxLength } = this.props;
let text = content;
if (!expanded) {
text = text.substring(0, maxLength);
}
return (
<span>
{text}
<button
className={styles.button}
onClick={this.toggleExpanded.bind(this)}>
{expanded ? 'Show less' : 'Show more'}
</button>
</span>
)
}
}
|
dutchcoders/marija-web
|
src/app/table/components/expandable/expandable.tsx
|
TypeScript
|
agpl-3.0
| 987
|
h1
{
border-bottom: 0.1em solid #ff5500;
font-size: 2em;
color: #05006e;
margin-top: 0;
padding: 1%;
background-color: #9593b9;
margin-bottom: 0.2em;
width: 100%;
}
#content
{
padding: 1%;
}
h2
{
border-bottom: 0.1em solid #ff5500;
font-size: 1.5em;
color: #05006e;
margin-bottom: 1em;
width: 100%;
}
img
{
margin: 0;
padding: 0.1em;
vertical-align: middle;
}
.horizontal-menu {
clear: both;
}
.horizontal-menu li {
margin: 0.1em;
display: inline;
}
label {
width: 12em;
float: left;
text-align: left;
font-weight: bold;
}
.container {
clear: both;
margin: 0.3em;
text-align: left;
width: 40em;
}
tr.header td
{
background-color: #ffceb9;
padding: 0.3em;
text-align: center;
font-weight: bold;
}
tr.odd td
{
background-color: #f0f1ff;
text-align: center;
}
tr.even td
{
background-color: #dcddfb;
text-align: center;
}
.vertical-menu
{
text-align: right;
}
#main-menu li
{
font-weight: bold;
}
.vertical-menu li
{
margin: 0.5em;
display: inline;
}
.pager {
width: 100%;
text-align: center;
margin: 1em;
clear: both;
}
.pager a, .pager span {
padding: 0.2em;
margin: 0.3em;
border: 1px solid #dcddfb;
background-color: #f0f1ff;
}
.pager span {
background-color: #dcddfb;
font-weight: bold;
}
.pager a:hover {
background-color: #dcddfb;
}
.popup {
padding: 0;
background-color: #d8f5ff;
border: 1px solid #4c85be;
position: absolute;
display: none;
z-index: 10;
color: black;
width: auto;
}
.popup-title {
color: #dcddfb;
font-weight: bold;
background-color: #4c85be;
text-align: right;
}
.popup-title a {
color: #d8f5ff;
}
|
libersoft/BNB
|
web/css/backend.css
|
CSS
|
agpl-3.0
| 1,674
|
<?php
class Advanced_Excerpt {
public $options;
/*
* Some of the following options below are linked to checkboxes on the plugin's option page.
* If any checkbox options are added/removed/modified in the future please ensure you also update
* the $checkbox_options variable in the update_options() method.
*/
public $default_options = array(
'length' => 40,
'length_type' => 'words',
'no_custom' => 1,
'no_shortcode' => 1,
'finish' => 'exact',
'ellipsis' => '…',
'read_more' => 'Read the rest',
'add_link' => 0,
'link_new_tab' => 0,
'link_screen_reader' => 0,
'link_exclude_length' => 0,
'allowed_tags' => array(),
'the_excerpt' => 1,
'the_content' => 1,
'the_content_no_break' => 0,
'exclude_pages' => array(),
'allowed_tags_option' => 'dont_remove_any',
);
public $options_basic_tags; // Basic HTML tags (determines which tags are in the checklist by default)
public $options_all_tags; // Almost all HTML tags (extra options)
public $filter_type; // Determines wether we're filtering the_content or the_excerpt at any given time
function __construct( $plugin_file_path ) {
$this->load_options();
$this->plugin_version = $GLOBALS['advanced_excerpt_version'];
$this->plugin_file_path = $plugin_file_path;
$this->plugin_dir_path = plugin_dir_path( $plugin_file_path );
$this->plugin_folder_name = basename( $this->plugin_dir_path );
$this->plugin_basename = plugin_basename( $plugin_file_path );
$this->plugin_base ='options-general.php?page=advanced-excerpt';
if ( 'POST' == $_SERVER['REQUEST_METHOD'] && isset( $_REQUEST['page'] ) && 'advanced-excerpt' === $_REQUEST['page'] ) {
check_admin_referer( 'advanced_excerpt_update_options' );
$this->update_options();
}
$this->options_basic_tags = apply_filters( 'advanced_excerpt_basic_tags', array(
'a', 'abbr', 'acronym', 'address', 'article', 'aside', 'audio', 'b', 'big',
'blockquote', 'br', 'canvas', 'center', 'cite', 'code', 'dd', 'del', 'div', 'dl', 'dt',
'em', 'embed', 'form', 'footer', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hr', 'i', 'img', 'ins',
'li', 'nav', 'ol', 'p', 'pre', 'q', 's', 'section', 'small', 'span', 'strike', 'strong', 'sub',
'sup', 'svg', 'table', 'td', 'template', 'th', 'time', 'tr', 'u', 'ul', 'video'
) );
$this->options_all_tags = apply_filters( 'advanced_excerpt_all_tags', array(
'a', 'abbr', 'acronym', 'address', 'applet', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big',
'blockquote', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'data',
'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption',
'figure', 'font', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hr',
'i', 'iframe', 'img', 'input', 'ins', 'isindex', 'kbd', 'keygen', 'label', 'legend', 'li', 'main', 'map',
'mark', 'math', 'menu', 'menuitem', 'meter', 'nav', 'noframes', 'noscript', 'object', 'ol', 'optgroup',
'option', 'output', 'p', 'param', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section',
'select', 'small', 'source', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'svg', 'table',
'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var',
'video', 'wbr'
) );
if ( is_admin() ) {
$this->admin_init();
}
add_action( 'loop_start', array( $this, 'hook_content_filters' ) );
}
function hook_content_filters() {
/*
* Allow developers to skip running the advanced excerpt filters on certain page types.
* They can do so by using the "Disable On" checkboxes on the options page or
* by passing in an array of page types they'd like to skip
* e.g. array( 'search', 'author' );
* The filter, when implemented, takes precedence over the options page selection.
*
* WordPress default themes (and others) do not use the_excerpt() or get_the_excerpt()
* and instead use the_content(). As such, we also need to hook into the_content().
* To ensure we're not changing the content of single posts / pages we automatically exclude 'singular' page types.
*/
add_filter( 'wppsac_excerpt', array( $this, 'filter_content' ) );
$page_types = $this->get_current_page_types();
$skip_page_types = array_unique( array_merge( array( 'singular' ), $this->options['exclude_pages'] ) );
$skip_page_types = apply_filters( 'advanced_excerpt_skip_page_types', $skip_page_types );
$page_type_matches = array_intersect( $page_types, $skip_page_types );
if ( !empty( $page_types ) && !empty( $page_type_matches ) ) return;
// skip woocommerce products
if ( in_array( 'woocommerce', $skip_page_types ) && get_post_type( get_the_ID() ) == 'product' ) {
return;
}
// conflict with WPTouch
if ( function_exists( 'wptouch_is_mobile_theme_showing' ) && wptouch_is_mobile_theme_showing() ) {
return;
}
// skip bbpress
if ( function_exists( 'is_bbpress' ) && is_bbpress() ) {
return;
}
if ( 1 == $this->options['the_excerpt'] ) {
remove_all_filters( 'get_the_excerpt' );
remove_all_filters( 'the_excerpt' );
add_filter( 'get_the_excerpt', array( $this, 'filter_excerpt' ) );
}
if ( 1 == $this->options['the_content'] ) {
add_filter( 'the_content', array( $this, 'filter_content' ) );
}
}
function admin_init() {
add_action( 'admin_menu', array( $this, 'add_pages' ) );
add_filter( 'plugin_action_links_' . $this->plugin_basename, array( $this, 'plugin_action_links' ) );
}
function load_options() {
/*
* An older version of this plugin used to individually store each of it's options as a row in wp_options (1 row per option).
* The code below checks if their installations once used an older version of this plugin and attempts to update
* the option storage to the new method (all options stored in a single row in the DB as an array)
*/
$update_options = false;
$update_from_legacy = false;
if ( false !== get_option( 'advancedexcerpt_length' ) ) {
$legacy_options = array( 'length', 'use_words', 'no_custom', 'no_shortcode', 'finish_word', 'finish_sentence', 'ellipsis', 'read_more', 'add_link', 'allowed_tags' );
foreach ( $legacy_options as $legacy_option ) {
$option_name = 'advancedexcerpt_' . $legacy_option;
$this->options[$legacy_option] = get_option( $option_name );
delete_option( $option_name );
}
// filtering the_content() is disabled by default when migrating from version 4.1.1 of the plugin
$this->options['the_excerpt'] = 1;
$this->options['the_content'] = 0;
$update_options = true;
$update_from_legacy = true;
} else {
$this->options = get_option( 'advanced_excerpt' );
}
// convert legacy option use_words to it's udpated equivalent
if ( isset( $this->options['use_words'] ) ) {
$this->options['length_type'] = ( 1 == $this->options['use_words'] ) ? 'words' : 'characters';
unset( $this->options['use_words'] );
$update_options = true;
}
// convert legacy options finish_word & finish_sentence to their udpated equivalents
if ( isset( $this->options['finish_sentence'] ) ) {
if ( 0 == $this->options['finish_word'] && 0 == $this->options['finish_sentence'] ) {
$this->options['finish'] = 'exact';
} else if ( 1 == $this->options['finish_word'] && 1 == $this->options['finish_sentence'] ) {
$this->options['finish'] = 'sentence';
} else if ( 0 == $this->options['finish_word'] && 1 == $this->options['finish_sentence'] ) {
$this->options['finish'] = 'sentence';
} else {
$this->options['finish'] = 'word';
}
unset( $this->options['finish_word'] );
unset( $this->options['finish_sentence'] );
$update_options = true;
}
// convert legacy option '_all' in the allowed_tags option to it's updated equivalent
if ( isset( $this->options['allowed_tags'] ) ) {
if ( false !== ( $all_key = array_search( '_all', $this->options['allowed_tags'] ) ) ) {
unset( $this->options['allowed_tags'][$all_key] );
$this->options['allowed_tags_option'] = 'dont_remove_any';
} elseif( $update_from_legacy ) {
$this->options['allowed_tags_option'] = 'remove_all_tags_except';
}
}
// if no options exist then this is a fresh install, set up some default options
if ( empty( $this->options ) ) {
$this->options = $this->default_options;
$update_options = true;
}
$this->options = wp_parse_args( $this->options, $this->default_options );
if ( $update_options ) {
update_option( 'advanced_excerpt', $this->options );
}
}
function add_pages() {
$options_page = add_options_page( __( "Advanced Excerpt Options", 'advanced-excerpt' ), __( "Excerpt", 'advanced-excerpt' ), 'manage_options', 'advanced-excerpt', array( $this, 'page_options' ) );
// Scripts
add_action( 'admin_print_scripts-' . $options_page, array( $this, 'page_assets' ) );
}
function page_assets() {
$version = defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ? time() : $this->plugin_version;
$plugins_url = trailingslashit( plugins_url() ) . trailingslashit( $this->plugin_folder_name );
// css
$src = $plugins_url . 'asset/css/styles.css';
wp_enqueue_style( 'advanced-excerpt-styles', $src, array(), $version );
$suffix = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
// js
$src = $plugins_url . 'asset/js/advanced-excerpt' . $suffix . '.js';
wp_enqueue_script( 'advanced-excerpt-script', $src, array( 'jquery' ), $version, true );
}
function plugin_action_links( $links ) {
$link = sprintf( '<a href="%s">%s</a>', admin_url( $this->plugin_base ), __( 'Settings', 'advanced-excerpt' ) );
array_unshift( $links, $link );
return $links;
}
function filter_content( $content ) {
$this->filter_type = 'content';
return $this->filter( $content );
}
function filter_excerpt( $content ) {
$this->filter_type = 'excerpt';
return $this->filter( $content );
}
function filter( $content ) {
extract( wp_parse_args( $this->options, $this->default_options ), EXTR_SKIP );
if ( true === apply_filters( 'advanced_excerpt_skip_excerpt_filtering', false ) ) {
return $content;
}
if ( is_post_type_archive( 'tribe_events' ) ) {
return $content;
}
global $post;
if ( $the_content_no_break && false !== strpos( $post->post_content, '<!--more-->' ) && 'content' == $this->filter_type ) {
return $content;
}
// Avoid custom excerpts
if ( !empty( $content ) && !$no_custom ) {
return $content;
}
// prevent recursion on 'the_content' hook
$content_has_filter = false;
if ( has_filter( 'the_content', array( $this, 'filter_content' ) ) ) {
remove_filter( 'the_content', array( $this, 'filter_content' ) );
$content_has_filter = true;
}
$text = get_the_content( '' );
// remove shortcodes
if ( $no_shortcode ) {
$text = strip_shortcodes( $text );
}
$text = apply_filters( 'the_content', $text );
// add our filter back in
if ( $content_has_filter ) {
add_filter( 'the_content', array( $this, 'filter_content' ) );
}
// From the default wp_trim_excerpt():
// Some kind of precaution against malformed CDATA in RSS feeds I suppose
$text = str_replace( ']]>', ']]>', $text );
if ( empty( $allowed_tags ) ) {
$allowed_tags = array();
}
// the $exclude_tags args takes precedence over the $allowed_tags args (only if they're both defined)
if ( ! empty( $exclude_tags ) ) {
$allowed_tags = array_diff( $this->options_all_tags, $exclude_tags );
}
// Strip HTML if $allowed_tags_option is set to 'remove_all_tags_except'
if ( 'remove_all_tags_except' === $allowed_tags_option ) {
if ( count( $allowed_tags ) > 0 ) {
$tag_string = '<' . implode( '><', $allowed_tags ) . '>';
} else {
$tag_string = '';
}
$text = strip_tags( $text, $tag_string );
}
$text_before_trimming = $text;
// Create the excerpt
$text = $this->text_excerpt( $text, $length, $length_type, $finish );
// lengths
$text_length_before = strlen( trim( $text_before_trimming ) );
$text_length_after = strlen( trim( $text ) );
// Add the ellipsis or link
if ( ! apply_filters( 'advanced_excerpt_disable_add_more', false, $text_before_trimming, $this->options ) ) {
if ( ! $link_exclude_length || $text_length_after < $text_length_before ) {
$text = $this->text_add_more( $text, $ellipsis, ( $add_link ) ? $read_more : false, ( $link_new_tab ) ? true : false, ( $link_screen_reader ) ? true : false );
}
}
return apply_filters( 'advanced_excerpt_content', $text );
}
function text_excerpt( $text, $length, $length_type, $finish ) {
$tokens = array();
$out = '';
$w = 0;
// Divide the string into tokens; HTML tags, or words, followed by any whitespace
// (<[^>]+>|[^<>\s]+\s*)
preg_match_all( '/(<[^>]+>|[^<>\s]+)\s*/u', $text, $tokens );
foreach ( $tokens[0] as $t ) { // Parse each token
if ( $w >= $length && 'sentence' != $finish ) { // Limit reached
break;
}
if ( $t[0] != '<' ) { // Token is not a tag
if ( $w >= $length && 'sentence' == $finish && preg_match( '/[\?\.\!].*$/uS', $t ) == 1 ) { // Limit reached, continue until ? . or ! occur at the end
$out .= trim( $t );
break;
}
if ( 'words' == $length_type ) { // Count words
$w++;
} else { // Count/trim characters
if ( $finish == 'exact_w_spaces' ) {
$chars = $t;
} else {
$chars = trim( $t );
}
$c = mb_strlen( $chars );
if ( $c + $w > $length && 'sentence' != $finish ) { // Token is too long
$c = ( 'word' == $finish ) ? $c : $length - $w; // Keep token to finish word
$t = mb_substr( $t, 0, $c );
}
$w += $c;
}
}
// Append what's left of the token
$out .= $t;
}
return trim( force_balance_tags( $out ) );
}
public function text_add_more( $text, $ellipsis, $read_more, $link_new_tab, $link_screen_reader ) {
if ( $read_more ) {
$screen_reader_html = '';
if ( $link_screen_reader ) {
$screen_reader_html = '<span class="screen-reader-text"> “' . get_the_title() . '”</span>';
}
if ( $link_new_tab ) {
$link_template = apply_filters( 'advanced_excerpt_read_more_link_template', ' <a href="%1$s" class="read-more" target="_blank">%2$s %3$s</a>', get_permalink(), $read_more );
} else {
$link_template = apply_filters( 'advanced_excerpt_read_more_link_template', ' <a href="%1$s" class="read-more">%2$s %3$s</a>', get_permalink(), $read_more );
}
$read_more = str_replace( '{title}', get_the_title(), $read_more );
$read_more = do_shortcode( $read_more );
$read_more = apply_filters( 'advanced_excerpt_read_more_text', $read_more );
$ellipsis .= sprintf( $link_template, get_permalink(), $read_more, $screen_reader_html );
}
$pos = strrpos( $text, '</' );
if ( $pos !== false ) {
// get the "clean" name of the last closing tag in the text, e.g. p, a, strong, div
$last_tag = strtolower( trim( str_replace( array( '<', '/', '>' ), '', substr( $text, $pos ) ) ) );
/*
* There was previously a problem where our 'read-more' links were being appending incorrectly into unsuitable HTML tags.
* As such we're now maintaining a whitelist of HTML tags that are suitable for being appended into.
*/
$allow_tags_to_append_into = apply_filters( 'advanced_excerpt_allow_tags_to_append_into', array( 'p', 'article', 'section' ) );
if( !in_array( $last_tag, $allow_tags_to_append_into ) ) {
// After the content
$text .= $ellipsis;
return $text;
}
// Inside last HTML tag
$text = substr_replace( $text, $ellipsis, $pos, 0 );
return $text;
}
// After the content
$text .= $ellipsis;
return $text;
}
function update_options() {
$_POST = stripslashes_deep( $_POST );
$this->options['length'] = (int) $_POST['length'];
$checkbox_options = array( 'no_custom', 'no_shortcode', 'add_link', 'link_new_tab', 'link_screen_reader', 'link_exclude_length', 'the_excerpt', 'the_content', 'the_content_no_break' );
foreach ( $checkbox_options as $checkbox_option ) {
$this->options[$checkbox_option] = ( isset( $_POST[$checkbox_option] ) ) ? 1 : 0;
}
$this->options['length_type'] = $_POST['length_type'];
$this->options['finish'] = $_POST['finish'];
$this->options['ellipsis'] = $_POST['ellipsis'];
$this->options['read_more'] = isset( $_POST['read_more'] ) ? $_POST['read_more'] : $this->options['read_more'];
$this->options['allowed_tags'] = ( isset( $_POST['allowed_tags'] ) ) ? array_unique( (array) $_POST['allowed_tags'] ) : array();
$this->options['exclude_pages'] = ( isset( $_POST['exclude_pages'] ) ) ? array_unique( (array) $_POST['exclude_pages'] ) : array();
$this->options['allowed_tags_option'] = $_POST['allowed_tags_option'];
update_option( 'advanced_excerpt', $this->options );
wp_redirect( admin_url( $this->plugin_base ) . '&settings-updated=1' );
exit;
}
function page_options() {
extract( $this->options, EXTR_SKIP );
$ellipsis = htmlentities( $ellipsis );
$read_more = htmlentities( $read_more );
$tag_list = array_unique( array_merge( $this->options_basic_tags, $allowed_tags ) );
sort( $tag_list );
$tag_cols = 5;
// provides a set of checkboxes allowing the user to exclude the excerpt filter on certain page types
$exclude_pages_list = array(
'home' => __( 'Home Page', 'advanced-excerpt' ),
'feed' => __( 'Posts RSS Feed', 'advanced-excerpt' ),
'search' => __( 'Search Archive', 'advanced-excerpt' ),
'author' => __( 'Author Archive', 'advanced-excerpt' ),
'category' => __( 'Category Archive', 'advanced-excerpt' ),
'tag' => __( 'Tag Archive', 'advanced-excerpt' ),
'woocommerce' => __( 'WooCommerce Products', 'advanced-excerpt' ),
);
$exclude_pages_list = apply_filters( 'advanced_excerpt_exclude_pages_list', $exclude_pages_list );
require_once $this->plugin_dir_path . 'template/options.php';
}
function get_current_page_types() {
global $wp_query;
if ( ! isset( $wp_query ) ) return false;
$wp_query_object_vars = get_object_vars( $wp_query );
$page_types = array();
foreach( $wp_query_object_vars as $key => $value ) {
if ( false === strpos( $key, 'is_' ) ) continue;
if ( true === $value ) {
$page_types[] = str_replace( 'is_', '', $key );
}
}
return $page_types;
}
}
|
akvo/akvo-sites-zz-template
|
code/wp-content/plugins/advanced-excerpt/class/advanced-excerpt.php
|
PHP
|
agpl-3.0
| 18,989
|
<?php namespace Controllers\Admin;
use AdminController;
use Input;
use Lang;
use Accessory;
use Redirect;
use Setting;
use DB;
use Sentry;
use Str;
use Validator;
use View;
use User;
use Actionlog;
use Mail;
use Datatable;
class AccessoriesController extends AdminController
{
/**
* Show a list of all the accessories.
*
* @return View
*/
public function getIndex()
{
return View::make('backend/accessories/index');
}
/**
* Accessory create.
*
* @return View
*/
public function getCreate()
{
// Show the page
$category_list = array('' => '') + DB::table('categories')->where('category_type','=','accessory')->whereNull('deleted_at')->lists('name', 'id');
return View::make('backend/accessories/edit')->with('accessory',new Accessory)->with('category_list',$category_list);
}
/**
* Accessory create form processing.
*
* @return Redirect
*/
public function postCreate()
{
// create a new model instance
$accessory = new Accessory();
$validator = Validator::make(Input::all(), $accessory->rules);
if ($validator->fails())
{
// The given data did not pass validation
return Redirect::back()->withInput()->withErrors($validator->messages());
}
else{
// Update the accessory data
$accessory->name = e(Input::get('name'));
$accessory->category_id = e(Input::get('category_id'));
$accessory->qty = e(Input::get('qty'));
$accessory->user_id = Sentry::getId();
// Was the accessory created?
if($accessory->save()) {
// Redirect to the new accessory page
return Redirect::to("admin/accessories")->with('success', Lang::get('admin/accessories/message.create.success'));
}
}
// Redirect to the accessory create page
return Redirect::to('admin/accessories/create')->with('error', Lang::get('admin/accessories/message.create.error'));
}
/**
* Accessory update.
*
* @param int $accessoryId
* @return View
*/
public function getEdit($accessoryId = null)
{
// Check if the accessory exists
if (is_null($accessory = Accessory::find($accessoryId))) {
// Redirect to the blogs management page
return Redirect::to('admin/accessories')->with('error', Lang::get('admin/accessories/message.does_not_exist'));
}
$category_list = array('' => '') + DB::table('categories')->where('category_type','=','accessory')->whereNull('deleted_at')->lists('name', 'id');
return View::make('backend/accessories/edit', compact('accessory'))->with('category_list',$category_list);
}
/**
* Accessory update form processing page.
*
* @param int $accessoryId
* @return Redirect
*/
public function postEdit($accessoryId = null)
{
// Check if the blog post exists
if (is_null($accessory = Accessory::find($accessoryId))) {
// Redirect to the blogs management page
return Redirect::to('admin/accessories')->with('error', Lang::get('admin/accessories/message.does_not_exist'));
}
// get the POST data
$new = Input::all();
// attempt validation
$validator = Validator::make(Input::all(), $accessory->validationRules($accessoryId));
if ($validator->fails())
{
// The given data did not pass validation
return Redirect::back()->withInput()->withErrors($validator->messages());
}
// attempt validation
else {
// Update the accessory data
$accessory->name = e(Input::get('name'));
$accessory->category_id = e(Input::get('category_id'));
$accessory->qty = e(Input::get('qty'));
// Was the accessory created?
if($accessory->save()) {
// Redirect to the new accessory page
return Redirect::to("admin/accessories")->with('success', Lang::get('admin/accessories/message.update.success'));
}
}
// Redirect to the accessory management page
return Redirect::to("admin/accessories/$accessoryID/edit")->with('error', Lang::get('admin/accessories/message.update.error'));
}
/**
* Delete the given accessory.
*
* @param int $accessoryId
* @return Redirect
*/
public function getDelete($accessoryId)
{
// Check if the blog post exists
if (is_null($accessory = Accessory::find($accessoryId))) {
// Redirect to the blogs management page
return Redirect::to('admin/accessories')->with('error', Lang::get('admin/accessories/message.not_found'));
}
if ($accessory->hasUsers() > 0) {
return Redirect::to('admin/accessories')->with('error', Lang::get('admin/accessories/message.assoc_users', array('count'=> $accessory->hasUsers())));
} else {
$accessory->delete();
// Redirect to the locations management page
return Redirect::to('admin/accessories')->with('success', Lang::get('admin/accessories/message.delete.success'));
}
}
/**
* Get the accessory information to present to the accessory view page
*
* @param int $accessoryId
* @return View
**/
public function getView($accessoryID = null)
{
$accessory = Accessory::find($accessoryID);
if (isset($accessory->id)) {
return View::make('backend/accessories/view', compact('accessory'));
} else {
// Prepare the error message
$error = Lang::get('admin/accessories/message.does_not_exist', compact('id'));
// Redirect to the user management page
return Redirect::route('accessories')->with('error', $error);
}
}
/**
* Check out the accessory to a person
**/
public function getCheckout($accessoryId)
{
// Check if the accessory exists
if (is_null($accessory = Accessory::find($accessoryId))) {
// Redirect to the accessory management page with error
return Redirect::to('accessories')->with('error', Lang::get('admin/accessories/message.not_found'));
}
// Get the dropdown of users and then pass it to the checkout view
$users_list = array('' => 'Select a User') + DB::table('users')->select(DB::raw('concat(last_name,", ",first_name) as full_name, id'))->whereNull('deleted_at')->orderBy('last_name', 'asc')->orderBy('first_name', 'asc')->lists('full_name', 'id');
return View::make('backend/accessories/checkout', compact('accessory'))->with('users_list',$users_list);
}
/**
* Check out the accessory to a person
**/
public function postCheckout($accessoryId)
{
// Check if the accessory exists
if (is_null($accessory = Accessory::find($accessoryId))) {
// Redirect to the accessory management page with error
return Redirect::to('accessories')->with('error', Lang::get('admin/accessories/message.not_found'));
}
$assigned_to = e(Input::get('assigned_to'));
// Declare the rules for the form validation
$rules = array(
'assigned_to' => 'required|min:1'
);
// Create a new validator instance from our validation rules
$validator = Validator::make(Input::all(), $rules);
// If validation fails, we'll exit the operation now.
if ($validator->fails()) {
// Ooops.. something went wrong
return Redirect::back()->withInput()->withErrors($validator);
}
// Check if the user exists
if (is_null($user = User::find($assigned_to))) {
// Redirect to the accessory management page with error
return Redirect::to('admin/accessories')->with('error', Lang::get('admin/accessories/message.user_does_not_exist'));
}
// Update the accessory data
$accessory->assigned_to = e(Input::get('assigned_to'));
$accessory->users()->attach($accessory->id, array(
'accessory_id' => $accessory->id,
'assigned_to' => e(Input::get('assigned_to'))));
$logaction = new Actionlog();
$logaction->accessory_id = $accessory->id;
$logaction->checkedout_to = $accessory->assigned_to;
$logaction->asset_type = 'accessory';
$logaction->location_id = $user->location_id;
$logaction->user_id = Sentry::getUser()->id;
$logaction->note = e(Input::get('note'));
$log = $logaction->logaction('checkout');
$accessory_user = DB::table('accessories_users')->where('assigned_to','=',$accessory->assigned_to)->where('accessory_id','=',$accessory->id)->first();
$data['log_id'] = $logaction->id;
$data['eula'] = $accessory->getEula();
$data['first_name'] = $user->first_name;
$data['item_name'] = $accessory->name;
$data['require_acceptance'] = $accessory->requireAcceptance();
if (($accessory->requireAcceptance()=='1') || ($accessory->getEula())) {
Mail::send('emails.accept-asset', $data, function ($m) use ($user) {
$m->to($user->email, $user->first_name . ' ' . $user->last_name);
$m->subject('Confirm accessory delivery');
});
}
// Redirect to the new accessory page
return Redirect::to("admin/accessories")->with('success', Lang::get('admin/accessories/message.checkout.success'));
}
/**
* Check the accessory back into inventory
*
* @param int $accessoryId
* @return View
**/
public function getCheckin($accessoryUserId = null, $backto = null)
{
// Check if the accessory exists
if (is_null($accessory_user = DB::table('accessories_users')->find($accessoryUserId))) {
// Redirect to the accessory management page with error
return Redirect::to('admin/accessories')->with('error', Lang::get('admin/accessories/message.not_found'));
}
$accessory = Accessory::find($accessory_user->accessory_id);
return View::make('backend/accessories/checkin', compact('accessory'))->with('backto',$backto);
}
/**
* Check in the item so that it can be checked out again to someone else
*
* @param int $accessoryId
* @return View
**/
public function postCheckin($accessoryUserId = null, $backto = null)
{
// Check if the accessory exists
if (is_null($accessory_user = DB::table('accessories_users')->find($accessoryUserId))) {
// Redirect to the accessory management page with error
return Redirect::to('admin/accessories')->with('error', Lang::get('admin/accessories/message.not_found'));
}
$accessory = Accessory::find($accessory_user->accessory_id);
$logaction = new Actionlog();
$logaction->checkedout_to = $accessory_user->assigned_to;
$return_to = $accessory_user->assigned_to;
// Was the accessory updated?
if(DB::table('accessories_users')->where('id', '=', $accessory_user->id)->delete()) {
$logaction->accessory_id = $accessory->id;
$logaction->location_id = NULL;
$logaction->asset_type = 'accessory';
$logaction->user_id = Sentry::getUser()->id;
$log = $logaction->logaction('checkin from');
if ($backto=='user') {
return Redirect::to("admin/users/".$return_to.'/view')->with('success', Lang::get('admin/accessories/message.checkin.success'));
} else {
return Redirect::to("admin/accessories/".$accessory->id."/view")->with('success', Lang::get('admin/accessories/message.checkin.success'));
}
}
// Redirect to the accessory management page with error
return Redirect::to("admin/accessories")->with('error', Lang::get('admin/accessories/message.checkin.error'));
}
public function getDatatable()
{
$accessories = Accessory::select(array('id','name','qty'))
->whereNull('deleted_at')
->orderBy('created_at', 'DESC');
$accessories = $accessories->get();
$actions = new \Chumper\Datatable\Columns\FunctionColumn('actions',function($accessories)
{
return '<a href="'.route('checkout/accessory', $accessories->id).'" style="margin-right:5px;" class="btn btn-info btn-sm" '.(($accessories->numRemaining() > 0 ) ? '' : ' disabled').'>'.Lang::get('general.checkout').'</a><a href="'.route('update/accessory', $accessories->id).'" class="btn btn-warning btn-sm" style="margin-right:5px;"><i class="fa fa-pencil icon-white"></i></a><a data-html="false" class="btn delete-asset btn-danger btn-sm" data-toggle="modal" href="'.route('delete/accessory', $accessories->id).'" data-content="'.Lang::get('admin/accessories/message.delete.confirm').'" data-title="'.Lang::get('general.delete').' '.htmlspecialchars($accessories->name).'?" onClick="return false;"><i class="fa fa-trash icon-white"></i></a>';
});
return Datatable::collection($accessories)
->addColumn('name',function($accessories)
{
return link_to('admin/accessories/'.$accessories->id.'/view', $accessories->name);
})
->addColumn('qty',function($accessories)
{
return $accessories->qty;
})
->addColumn('numRemaining',function($accessories)
{
return $accessories->numRemaining();
})
->addColumn($actions)
->searchColumns('name','qty','numRemaining','actions')
->orderColumns('name','qty','numRemaining','actions')
->make();
}
public function getDataView($accessoryID)
{
$accessory = Accessory::find($accessoryID);
$accessory_users = $accessory->users;
$actions = new \Chumper\Datatable\Columns\FunctionColumn('actions',function($accessory_users){
return '<a href="'.route('checkin/accessory', $accessory_users->pivot->id).'" class="btn-flat info">Checkin</a>';
});
return Datatable::collection($accessory_users)
->addColumn('name',function($accessory_users)
{
return link_to('/admin/users/'.$accessory_users->id.'/view', $accessory_users->fullName());
})
->addColumn($actions)
->make();
}
}
|
ivarne/snipe-it
|
app/controllers/admin/AccessoriesController.php
|
PHP
|
agpl-3.0
| 14,711
|
/**
* Asqatasun - Automated webpage assessment
* Copyright (C) 2008-2020 Asqatasun.org
*
* 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/>.
*
* Contact us by mail: asqatasun AT asqatasun DOT org
*/
package org.asqatasun.rules.rgaa40;
import org.asqatasun.ruleimplementation.AbstractNotTestedRuleImplementation;
/**
* Implementation of rule 10.13.1 (referential RGAA 4.0)
*
* For more details about implementation, refer to <a href="https://gitlab.com/asqatasun/Asqatasun/-/blob/master/documentation/en/90_Rules/rgaa4.0/10.Presentation_of_information/Rule-10-13-1.md">rule 10.13.1 design page</a>.
* @see <a href="https://www.numerique.gouv.fr/publications/rgaa-accessibilite/methode/criteres/#test-10-13-1">10.13.1 rule specification</a>
*/
public class Rgaa40Rule101301 extends AbstractNotTestedRuleImplementation {
/**
* Default constructor
*/
public Rgaa40Rule101301() {
super();
}
}
|
Asqatasun/Asqatasun
|
rules/rules-rgaa4.0/src/main/java/org/asqatasun/rules/rgaa40/Rgaa40Rule101301.java
|
Java
|
agpl-3.0
| 1,549
|
from django.views.decorators.cache import never_cache
from django.views.generic.base import RedirectView
from C4CApplication.views.utils import create_user
class MemberDetailsRedirectView(RedirectView):
url = ""
connected_member = None
def dispatch(self, request, *args, **kwargs):
# Create the object representing the user
if 'email' not in self.request.session:
raise PermissionDenied # HTTP 403
self.connected_member = create_user(self.request.session['email'])
return super(MemberDetailsRedirectView, self).dispatch(request, *args, **kwargs)
@never_cache
def get(self, request, *args, **kwargs):
member_to_ad_as_a_friend_mail = kwargs['pk']
self.url = "/memberdetails/"+str(member_to_ad_as_a_friend_mail)
self.connected_member.add_favorite( member_to_ad_as_a_friend_mail)
return super(MemberDetailsRedirectView, self).get(request, *args, **kwargs)
|
dsarkozi/care4care-sdp-grp4
|
Care4Care/C4CApplication/views/MemberDetailsRedirectView.py
|
Python
|
agpl-3.0
| 1,019
|
"""
Specific overrides to the base prod settings to make development easier.
"""
# Silence noisy logs
import logging
from os.path import abspath, dirname, join
from corsheaders.defaults import default_headers as corsheaders_default_headers
# pylint: enable=unicode-format-string # lint-amnesty, pylint: disable=bad-option-value
#####################################################################
from edx_django_utils.plugins import add_plugins
from openedx.core.djangoapps.plugins.constants import ProjectType, SettingsType
from .production import * # pylint: disable=wildcard-import, unused-wildcard-import
# Don't use S3 in devstack, fall back to filesystem
del DEFAULT_FILE_STORAGE
MEDIA_ROOT = "/edx/var/edxapp/uploads"
ORA2_FILEUPLOAD_BACKEND = 'django'
DEBUG = True
USE_I18N = True
DEFAULT_TEMPLATE_ENGINE['OPTIONS']['debug'] = True
LMS_BASE = 'localhost:18000'
CMS_BASE = 'localhost:18010'
SITE_NAME = LMS_BASE
SESSION_COOKIE_NAME = 'lms_sessionid'
# By default don't use a worker, execute tasks as if they were local functions
CELERY_ALWAYS_EAGER = True
HTTPS = 'off'
LMS_ROOT_URL = f'http://{LMS_BASE}'
LMS_INTERNAL_ROOT_URL = LMS_ROOT_URL
ENTERPRISE_API_URL = f'{LMS_INTERNAL_ROOT_URL}/enterprise/api/v1/'
IDA_LOGOUT_URI_LIST = [
'http://localhost:18130/logout/', # ecommerce
'http://localhost:18150/logout/', # credentials
'http://localhost:18381/logout/', # discovery
'http://localhost:18010/logout/', # studio
]
################################ LOGGERS ######################################
LOG_OVERRIDES = [
('common.djangoapps.track.contexts', logging.CRITICAL),
('common.djangoapps.track.middleware', logging.CRITICAL),
('lms.djangoapps.discussion.django_comment_client.utils', logging.CRITICAL),
]
for log_name, log_level in LOG_OVERRIDES:
logging.getLogger(log_name).setLevel(log_level)
# Docker does not support the syslog socket at /dev/log. Rely on the console.
LOGGING['handlers']['local'] = LOGGING['handlers']['tracking'] = {
'class': 'logging.NullHandler',
}
LOGGING['loggers']['tracking']['handlers'] = ['console']
################################ EMAIL ########################################
EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'
EMAIL_FILE_PATH = '/edx/src/ace_messages/'
############################ PYFS XBLOCKS SERVICE #############################
# Set configuration for Django pyfilesystem
DJFS = {
'type': 'osfs',
'directory_root': 'lms/static/djpyfs',
'url_root': '/static/djpyfs',
}
################################ DEBUG TOOLBAR ################################
INSTALLED_APPS += ['debug_toolbar']
MIDDLEWARE += [
'lms.djangoapps.discussion.django_comment_client.utils.QueryCountDebugMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
]
INTERNAL_IPS = ('127.0.0.1',)
DEBUG_TOOLBAR_PANELS = (
'debug_toolbar.panels.versions.VersionsPanel',
'debug_toolbar.panels.timer.TimerPanel',
'debug_toolbar.panels.settings.SettingsPanel',
'debug_toolbar.panels.headers.HeadersPanel',
'debug_toolbar.panels.request.RequestPanel',
'debug_toolbar.panels.sql.SQLPanel',
'debug_toolbar.panels.signals.SignalsPanel',
'debug_toolbar.panels.logging.LoggingPanel',
'debug_toolbar.panels.history.HistoryPanel',
# ProfilingPanel has been intentionally removed for default devstack.py
# runtimes for performance reasons. If you wish to re-enable it in your
# local development environment, please create a new settings file
# that imports and extends devstack.py.
)
DEBUG_TOOLBAR_CONFIG = {
'SHOW_TOOLBAR_CALLBACK': 'lms.envs.devstack.should_show_debug_toolbar',
}
def should_show_debug_toolbar(request): # lint-amnesty, pylint: disable=missing-function-docstring
# We always want the toolbar on devstack unless running tests from another Docker container
hostname = request.get_host()
if hostname.startswith('edx.devstack.lms:') or hostname.startswith('lms.devstack.edx:'):
return False
return True
########################### PIPELINE #################################
PIPELINE['PIPELINE_ENABLED'] = False
STATICFILES_STORAGE = 'openedx.core.storage.DevelopmentStorage'
# Revert to the default set of finders as we don't want the production pipeline
STATICFILES_FINDERS = [
'openedx.core.djangoapps.theming.finders.ThemeFilesFinder',
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
# Disable JavaScript compression in development
PIPELINE['JS_COMPRESSOR'] = None
# Whether to run django-require in debug mode.
REQUIRE_DEBUG = DEBUG
PIPELINE['SASS_ARGUMENTS'] = '--debug-info'
# Load development webpack donfiguration
WEBPACK_CONFIG_PATH = 'webpack.dev.config.js'
########################### VERIFIED CERTIFICATES #################################
FEATURES['AUTOMATIC_VERIFY_STUDENT_IDENTITY_FOR_TESTING'] = True
########################### External REST APIs #################################
FEATURES['ENABLE_OAUTH2_PROVIDER'] = True
FEATURES['ENABLE_MOBILE_REST_API'] = True
FEATURES['ENABLE_VIDEO_ABSTRACTION_LAYER_API'] = True
########################## SECURITY #######################
FEATURES['ENABLE_MAX_FAILED_LOGIN_ATTEMPTS'] = False
FEATURES['SQUELCH_PII_IN_LOGS'] = False
FEATURES['PREVENT_CONCURRENT_LOGINS'] = False
########################### Milestones #################################
FEATURES['MILESTONES_APP'] = True
########################### Entrance Exams #################################
FEATURES['ENTRANCE_EXAMS'] = True
################################ COURSE LICENSES ################################
FEATURES['LICENSING'] = True
########################## Courseware Search #######################
FEATURES['ENABLE_COURSEWARE_SEARCH'] = False
FEATURES['ENABLE_COURSEWARE_SEARCH_FOR_COURSE_STAFF'] = True
SEARCH_ENGINE = 'search.elastic.ElasticSearchEngine'
########################## Dashboard Search #######################
FEATURES['ENABLE_DASHBOARD_SEARCH'] = False
########################## Certificates Web/HTML View #######################
FEATURES['CERTIFICATES_HTML_VIEW'] = True
########################## Course Discovery #######################
LANGUAGE_MAP = {
'terms': dict(ALL_LANGUAGES),
'name': 'Language',
}
COURSE_DISCOVERY_MEANINGS = {
'org': {
'name': 'Organization',
},
'modes': {
'name': 'Course Type',
'terms': {
'honor': 'Honor',
'verified': 'Verified',
},
},
'language': LANGUAGE_MAP,
}
FEATURES['ENABLE_COURSE_DISCOVERY'] = False
# Setting for overriding default filtering facets for Course discovery
# COURSE_DISCOVERY_FILTERS = ["org", "language", "modes"]
FEATURES['COURSES_ARE_BROWSEABLE'] = True
HOMEPAGE_COURSE_MAX = 9
# Software secure fake page feature flag
FEATURES['ENABLE_SOFTWARE_SECURE_FAKE'] = True
# Setting for the testing of Software Secure Result Callback
VERIFY_STUDENT["SOFTWARE_SECURE"] = {
"API_ACCESS_KEY": "BBBBBBBBBBBBBBBBBBBB",
"API_SECRET_KEY": "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC",
}
DISABLE_ACCOUNT_ACTIVATION_REQUIREMENT_SWITCH = "verify_student_disable_account_activation_requirement"
# Skip enrollment start date filtering
SEARCH_SKIP_ENROLLMENT_START_DATE_FILTERING = True
########################## Shopping cart ##########################
FEATURES['ENABLE_COSMETIC_DISPLAY_PRICE'] = True
######################### Program Enrollments #####################
FEATURES['ENABLE_ENROLLMENT_RESET'] = True
########################## Third Party Auth #######################
if FEATURES.get('ENABLE_THIRD_PARTY_AUTH') and (
'common.djangoapps.third_party_auth.dummy.DummyBackend' not in AUTHENTICATION_BACKENDS
):
AUTHENTICATION_BACKENDS = ['common.djangoapps.third_party_auth.dummy.DummyBackend'] + list(AUTHENTICATION_BACKENDS)
############## ECOMMERCE API CONFIGURATION SETTINGS ###############
ECOMMERCE_PUBLIC_URL_ROOT = 'http://localhost:18130'
ECOMMERCE_API_URL = 'http://edx.devstack.ecommerce:18130/api/v2'
############## Comments CONFIGURATION SETTINGS ###############
COMMENTS_SERVICE_URL = 'http://edx.devstack.forum:4567'
############## Credentials CONFIGURATION SETTINGS ###############
CREDENTIALS_INTERNAL_SERVICE_URL = 'http://edx.devstack.credentials:18150'
CREDENTIALS_PUBLIC_SERVICE_URL = 'http://localhost:18150'
############################### BLOCKSTORE #####################################
BLOCKSTORE_API_URL = "http://edx.devstack.blockstore:18250/api/v1/"
########################## PROGRAMS LEARNER PORTAL ##############################
LEARNER_PORTAL_URL_ROOT = 'http://localhost:8734'
########################## ENTERPRISE LEARNER PORTAL ##############################
ENTERPRISE_LEARNER_PORTAL_NETLOC = 'localhost:8734'
ENTERPRISE_LEARNER_PORTAL_BASE_URL = 'http://' + ENTERPRISE_LEARNER_PORTAL_NETLOC
########################## ENTERPRISE ADMIN PORTAL ##############################
ENTERPRISE_ADMIN_PORTAL_NETLOC = 'localhost:1991'
ENTERPRISE_ADMIN_PORTAL_BASE_URL = 'http://' + ENTERPRISE_ADMIN_PORTAL_NETLOC
###################### Cross-domain requests ######################
FEATURES['ENABLE_CORS_HEADERS'] = True
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = ()
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_HEADERS = corsheaders_default_headers + (
'use-jwt-cookie',
)
LOGIN_REDIRECT_WHITELIST.extend([
CMS_BASE,
# Allow redirection to all micro-frontends.
# Please add your MFE if is not already listed here.
# Note: For this to work, the MFE must set BASE_URL in its .env.development to:
# BASE_URL=http://localhost:$PORT
# as opposed to:
# BASE_URL=localhost:$PORT
'localhost:1997', # frontend-app-account
'localhost:1976', # frontend-app-program-console
'localhost:1994', # frontend-app-gradebook
'localhost:2000', # frontend-app-learning
'localhost:2001', # frontend-app-course-authoring
'localhost:3001', # frontend-app-library-authoring
'localhost:18400', # frontend-app-publisher
'localhost:1993', # frontend-app-ora-grading
ENTERPRISE_LEARNER_PORTAL_NETLOC, # frontend-app-learner-portal-enterprise
ENTERPRISE_ADMIN_PORTAL_NETLOC, # frontend-app-admin-portal
])
###################### JWTs ######################
JWT_AUTH.update({
'JWT_AUDIENCE': 'lms-key',
'JWT_ISSUER': f'{LMS_ROOT_URL}/oauth2',
'JWT_ISSUERS': [{
'AUDIENCE': 'lms-key',
'ISSUER': f'{LMS_ROOT_URL}/oauth2',
'SECRET_KEY': 'lms-secret',
}],
'JWT_SECRET_KEY': 'lms-secret',
'JWT_SIGNING_ALGORITHM': 'RS512',
'JWT_PRIVATE_SIGNING_JWK': (
'{"e": "AQAB", "d": "RQ6k4NpRU3RB2lhwCbQ452W86bMMQiPsa7EJiFJUg-qBJthN0FMNQVbArtrCQ0xA1BdnQHThFiUnHcXfsTZUwmwvTu'
'iqEGR_MI6aI7h5D8vRj_5x-pxOz-0MCB8TY8dcuK9FkljmgtYvV9flVzCk_uUb3ZJIBVyIW8En7n7nV7JXpS9zey1yVLld2AbRG6W5--Pgqr9J'
'CI5-bLdc2otCLuen2sKyuUDHO5NIj30qGTaKUL-OW_PgVmxrwKwccF3w5uGNEvMQ-IcicosCOvzBwdIm1uhdm9rnHU1-fXz8VLRHNhGVv7z6mo'
'ghjNI0_u4smhUkEsYeshPv7RQEWTdkOQ", "n": "smKFSYowG6nNUAdeqH1jQQnH1PmIHphzBmwJ5vRf1vu48BUI5VcVtUWIPqzRK_LDSlZYh'
'9D0YFL0ZTxIrlb6Tn3Xz7pYvpIAeYuQv3_H5p8tbz7Fb8r63c1828wXPITVTv8f7oxx5W3lFFgpFAyYMmROC4Ee9qG5T38LFe8_oAuFCEntimW'
'xN9F3P-FJQy43TL7wG54WodgiM0EgzkeLr5K6cDnyckWjTuZbWI-4ffcTgTZsL_Kq1owa_J2ngEfxMCObnzGy5ZLcTUomo4rZLjghVpq6KZxfS'
'6I1Vz79ZsMVUWEdXOYePCKKsrQG20ogQEkmTf9FT_SouC6jPcHLXw", "q": "7KWj7l-ZkfCElyfvwsl7kiosvi-ppOO7Imsv90cribf88Dex'
'cO67xdMPesjM9Nh5X209IT-TzbsOtVTXSQyEsy42NY72WETnd1_nAGLAmfxGdo8VV4ZDnRsA8N8POnWjRDwYlVBUEEeuT_MtMWzwIKU94bzkWV'
'nHCY5vbhBYLeM", "p": "wPkfnjavNV1Hqb5Qqj2crBS9HQS6GDQIZ7WF9hlBb2ofDNe2K2dunddFqCOdvLXr7ydRcK51ZwSeHjcjgD1aJkHA'
'9i1zqyboxgd0uAbxVDo6ohnlVqYLtap2tXXcavKm4C9MTpob_rk6FBfEuq4uSsuxFvCER4yG3CYBBa4gZVU", "kid": "devstack_key", "'
'kty": "RSA"}'
),
'JWT_PUBLIC_SIGNING_JWK_SET': (
'{"keys": [{"kid": "devstack_key", "e": "AQAB", "kty": "RSA", "n": "smKFSYowG6nNUAdeqH1jQQnH1PmIHphzBmwJ5vRf1vu'
'48BUI5VcVtUWIPqzRK_LDSlZYh9D0YFL0ZTxIrlb6Tn3Xz7pYvpIAeYuQv3_H5p8tbz7Fb8r63c1828wXPITVTv8f7oxx5W3lFFgpFAyYMmROC'
'4Ee9qG5T38LFe8_oAuFCEntimWxN9F3P-FJQy43TL7wG54WodgiM0EgzkeLr5K6cDnyckWjTuZbWI-4ffcTgTZsL_Kq1owa_J2ngEfxMCObnzG'
'y5ZLcTUomo4rZLjghVpq6KZxfS6I1Vz79ZsMVUWEdXOYePCKKsrQG20ogQEkmTf9FT_SouC6jPcHLXw"}]}'
),
})
add_plugins(__name__, ProjectType.LMS, SettingsType.DEVSTACK)
######################### Django Rest Framework ########################
REST_FRAMEWORK['DEFAULT_RENDERER_CLASSES'] += (
'rest_framework.renderers.BrowsableAPIRenderer',
)
OPENAPI_CACHE_TIMEOUT = 0
#####################################################################
# Lastly, run any migrations, if needed.
MODULESTORE = convert_module_store_setting_if_needed(MODULESTORE)
SECRET_KEY = '85920908f28904ed733fe576320db18cabd7b6cd'
EDXNOTES_INTERNAL_API = 'http://edx.devstack.edxnotesapi:18120/api/v1'
EDXNOTES_CLIENT_NAME = 'edx_notes_api-backend-service'
############## Settings for Microfrontends #########################
LEARNING_MICROFRONTEND_URL = 'http://localhost:2000'
ACCOUNT_MICROFRONTEND_URL = 'http://localhost:1997'
AUTHN_MICROFRONTEND_URL = 'http://localhost:1999'
AUTHN_MICROFRONTEND_DOMAIN = 'localhost:1999'
################### FRONTEND APPLICATION DISCUSSIONS ###################
DISCUSSIONS_MICROFRONTEND_URL = 'http://localhost:2002'
################### FRONTEND APPLICATION DISCUSSIONS FEEDBACK URL###################
DISCUSSIONS_MFE_FEEDBACK_URL = None
############## Docker based devstack settings #######################
FEATURES.update({
'AUTOMATIC_AUTH_FOR_TESTING': True,
'ENABLE_DISCUSSION_SERVICE': True,
'SHOW_HEADER_LANGUAGE_SELECTOR': True,
# Enable enterprise integration by default.
# See https://github.com/edx/edx-enterprise/blob/master/docs/development.rst for
# more background on edx-enterprise.
# Toggle this off if you don't want anything to do with enterprise in devstack.
'ENABLE_ENTERPRISE_INTEGRATION': True,
})
ENABLE_MKTG_SITE = os.environ.get('ENABLE_MARKETING_SITE', False)
MARKETING_SITE_ROOT = os.environ.get('MARKETING_SITE_ROOT', 'http://localhost:8080')
MKTG_URLS = {
'ABOUT': '/about',
'ACCESSIBILITY': '/accessibility',
'AFFILIATES': '/affiliate-program',
'BLOG': '/blog',
'CAREERS': '/careers',
'CONTACT': '/support/contact_us',
'COURSES': '/course',
'DONATE': '/donate',
'ENTERPRISE': '/enterprise',
'FAQ': '/student-faq',
'HONOR': '/edx-terms-service',
'HOW_IT_WORKS': '/how-it-works',
'MEDIA_KIT': '/media-kit',
'NEWS': '/news-announcements',
'PRESS': '/press',
'PRIVACY': '/edx-privacy-policy',
'ROOT': MARKETING_SITE_ROOT,
'SCHOOLS': '/schools-partners',
'SITE_MAP': '/sitemap',
'TRADEMARKS': '/trademarks',
'TOS': '/edx-terms-service',
'TOS_AND_HONOR': '/edx-terms-service',
'WHAT_IS_VERIFIED_CERT': '/verified-certificate',
}
ENTERPRISE_MARKETING_FOOTER_QUERY_PARAMS = {}
CREDENTIALS_SERVICE_USERNAME = 'credentials_worker'
COURSE_CATALOG_URL_ROOT = 'http://edx.devstack.discovery:18381'
COURSE_CATALOG_API_URL = f'{COURSE_CATALOG_URL_ROOT}/api/v1'
SYSTEM_WIDE_ROLE_CLASSES = os.environ.get("SYSTEM_WIDE_ROLE_CLASSES", SYSTEM_WIDE_ROLE_CLASSES)
SYSTEM_WIDE_ROLE_CLASSES.append(
'system_wide_roles.SystemWideRoleAssignment',
)
if FEATURES.get('ENABLE_ENTERPRISE_INTEGRATION'):
SYSTEM_WIDE_ROLE_CLASSES.append(
'enterprise.SystemWideEnterpriseUserRoleAssignment',
)
#####################################################################
# django-session-cookie middleware
DCS_SESSION_COOKIE_SAMESITE = 'Lax'
DCS_SESSION_COOKIE_SAMESITE_FORCE_ALL = True
########################## THEMING #######################
# If you want to enable theming in devstack, uncomment this section and add any relevant
# theme directories to COMPREHENSIVE_THEME_DIRS
# We have to import the private method here because production.py calls
# derive_settings('lms.envs.production') which runs _make_mako_template_dirs with
# the settings from production, which doesn't include these theming settings. Thus,
# the templating engine is unable to find the themed templates because they don't exist
# in it's path. Re-calling derive_settings doesn't work because the settings was already
# changed from a function to a list, and it can't be derived again.
# from .common import _make_mako_template_dirs
# ENABLE_COMPREHENSIVE_THEMING = True
# COMPREHENSIVE_THEME_DIRS = [
# "/edx/app/edxapp/edx-platform/themes/"
# ]
# TEMPLATES[1]["DIRS"] = _make_mako_template_dirs
# derive_settings(__name__)
# Uncomment the lines below if you'd like to see SQL statements in your devstack LMS log.
# LOGGING['handlers']['console']['level'] = 'DEBUG'
# LOGGING['loggers']['django.db.backends'] = {'handlers': ['console'], 'level': 'DEBUG', 'propagate': False}
################### Special Exams (Proctoring) and Prereqs ###################
FEATURES['ENABLE_SPECIAL_EXAMS'] = True
FEATURES['ENABLE_PREREQUISITE_COURSES'] = True
# Used in edx-proctoring for ID generation in lieu of SECRET_KEY - dummy value
# (ref MST-637)
PROCTORING_USER_OBFUSCATION_KEY = '85920908f28904ed733fe576320db18cabd7b6cd'
#################### Webpack Configuration Settings ##############################
WEBPACK_LOADER['DEFAULT']['TIMEOUT'] = 5
################# New settings must go ABOVE this line #################
########################################################################
# See if the developer has any local overrides.
if os.path.isfile(join(dirname(abspath(__file__)), 'private.py')):
from .private import * # pylint: disable=import-error,wildcard-import
|
eduNEXT/edx-platform
|
lms/envs/devstack.py
|
Python
|
agpl-3.0
| 17,710
|
from unittest.mock import ANY, patch
from django.test import override_settings
from geoip2.errors import AddressNotFoundError
from rest_framework import status
from rest_framework.test import APITestCase
from karrot.groups.factories import GroupFactory
from karrot.users.factories import UserFactory
from karrot.utils.geoip import ip_to_city
from karrot.utils.tests.fake import faker
OVERRIDE_SETTINGS = {
'SENTRY_CLIENT_DSN': faker.name(),
'SENTRY_ENVIRONMENT': faker.name(),
'FCM_CLIENT_API_KEY': faker.name(),
'FCM_CLIENT_MESSAGING_SENDER_ID': faker.name(),
'FCM_CLIENT_PROJECT_ID': faker.name(),
'FCM_CLIENT_APP_ID': faker.name(),
}
class TestConfigAPI(APITestCase):
def test_default_config(self):
response = self.client.get('/api/config/')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(
response.data, {
'fcm': {
'api_key': None,
'messaging_sender_id': None,
'project_id': None,
'app_id': None,
},
'sentry': {
'dsn': None,
'environment': 'production',
},
}, response.data
)
@override_settings(**OVERRIDE_SETTINGS)
def test_config_with_overrides(self):
response = self.client.get('/api/config/')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(
response.data, {
'fcm': {
'api_key': OVERRIDE_SETTINGS['FCM_CLIENT_API_KEY'],
'messaging_sender_id': OVERRIDE_SETTINGS['FCM_CLIENT_MESSAGING_SENDER_ID'],
'project_id': OVERRIDE_SETTINGS['FCM_CLIENT_PROJECT_ID'],
'app_id': OVERRIDE_SETTINGS['FCM_CLIENT_APP_ID'],
},
'sentry': {
'dsn': OVERRIDE_SETTINGS['SENTRY_CLIENT_DSN'],
'environment': OVERRIDE_SETTINGS['SENTRY_ENVIRONMENT'],
},
}, response.data
)
class TestBootstrapAPI(APITestCase):
def setUp(self):
self.user = UserFactory()
self.member = UserFactory()
self.group = GroupFactory(members=[self.member], application_questions='')
self.url = '/api/bootstrap/'
self.client_ip = '2003:d9:ef08:4a00:4b7a:7964:8a3c:a33e'
ip_to_city.cache_clear() # prevent getting cached mock values
def tearDown(self):
ip_to_city.cache_clear()
def test_as_anon(self):
with self.assertNumQueries(1):
response = self.client.get(self.url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data['server'], ANY)
self.assertEqual(response.data['config'], ANY)
self.assertEqual(response.data['user'], None)
self.assertEqual(response.data['geoip'], None)
self.assertEqual(response.data['groups'], ANY)
@patch('karrot.utils.geoip.geoip')
def test_with_geoip(self, geoip):
lat_lng = [float(val) for val in faker.latlng()]
city = {'latitude': lat_lng[0], 'longitude': lat_lng[1], 'country_code': 'AA', 'time_zone': 'Europe/Berlin'}
geoip.city.return_value = city
response = self.client.get(self.url, HTTP_X_FORWARDED_FOR=self.client_ip)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(
dict(response.data['geoip']), {
'lat': city['latitude'],
'lng': city['longitude'],
'country_code': city['country_code'],
'timezone': city['time_zone'],
}
)
@patch('karrot.utils.geoip.geoip')
def test_without_geoip(self, geoip):
geoip.city.side_effect = AddressNotFoundError
response = self.client.get(self.url, HTTP_X_FORWARDED_FOR=self.client_ip)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertIsNone(response.data['geoip'])
def test_when_logged_in(self):
self.client.force_login(user=self.user)
with self.assertNumQueries(2):
response = self.client.get(self.url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data['user']['id'], self.user.id)
|
yunity/foodsaving-backend
|
karrot/bootstrap/tests/test_api.py
|
Python
|
agpl-3.0
| 4,392
|
# Fat Free CRM
# Copyright (C) 2008-2011 by Michael Dvorkin
#
# 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/>.
#------------------------------------------------------------------------------
require 'rails/all'
require 'jquery-rails'
require 'prototype-rails'
require 'haml'
require 'sass'
require 'acts_as_commentable'
require 'acts_as_list'
require 'acts-as-taggable-on'
require 'responds_to_parent'
require 'dynamic_form'
require 'paperclip'
require 'simple_form'
require 'will_paginate'
require 'authlogic'
require 'chosen-rails'
require 'ajax-chosen-rails'
require 'ransack'
require 'paper_trail'
require 'cancan'
require 'valium'
# Load redcloth if available (for textile markup in emails)
begin
require 'redcloth'
rescue LoadError
end
|
brookzhang/yxran_fatfreeCRM
|
lib/fat_free_crm/gem_dependencies.rb
|
Ruby
|
agpl-3.0
| 1,352
|
<?php
/**
* This file is part of the Checkbook NYC financial transparency software.
*
* Copyright (C) 2012, 2013 New York City
*
* 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/>.
*/
?>
<?php
echo eval($node->widgetConfig->header);
?>
<a class="trends-export" href="/export/download/trends_ratios_of_general_bonded_debt_csv?dataUrl=/node/<?php echo $node->nid ?>">Export</a>
<table id="table_<?php echo widget_unique_identifier($node) ?>" style='display:none' class="trendsShowOnLoad <?php echo $node->widgetConfig->html_class ?>">
<?php
if (isset($node->widgetConfig->caption_column)) {
echo '<caption>' . $node->data[0][$node->widgetConfig->caption_column] . '</caption>';
}
else if (isset($node->widgetConfig->caption)) {
echo '<caption>' . $node->widgetConfig->caption . '</caption>';
}
?>
<thead>
<tr>
<th class="number"><div class="trendCen" >Fiscal<br>Year</div></th>
<th class="number"><div class="trendCen" >General<br>Obligation<br>Bonds<br/>(in millions)</div></th>
<th class="number"><div class="trendCen" >Percentage of<br>Actual Taxable<br>Value of Property</div></th>
<th class="number"><div class="trendCen" >Per<br>Capita<br/>General<br>Obligations</div></th>
</tr>
</thead>
<tbody>
<?php $count = 1;
foreach( $node->data as $row){
$dollar_sign = ($count == 1) ? '<div class="dollarItem" >$</div>':'';
$percent_sign = ($count == 1) ? '<span class="endItem">%</span>' : '<span class="endItem" style="visibility:hidden;">%</span>';
echo "<tr><td class='number bonded'><div class='tdCen'>" . $row['fiscal_year'] . "</div></td>";
echo "<td class='number bonded'>" .$dollar_sign. "<div class='tdCen'>" . number_format($row['general_obligation_bonds']) . "</div></td>";
echo "<td class='number bonded'><div class='tdCen'>" . number_format($row['percentage_atcual_taxable_property'],2) . $percent_sign. "</div></td>";
echo "<td class='number bonded'>" .$dollar_sign. "<div class='tdCen'>" . number_format($row['per_capita_general_obligations']) . "</div></td>";
echo "</tr>";
$count++;
}
?>
</tbody>
</table>
<div class='footnote'><p>Sources: Comprehensive Annual Financial Reports of the Comptroller</p></div>
<?php
widget_data_tables_add_js($node);
?>
|
MomixSolutions/MyGovCenter
|
source/webapp/sites/all/modules/custom/checkbook_trends/templates/debt_capacity_trends/ratios_of_general_bonded_debt.tpl.php
|
PHP
|
agpl-3.0
| 2,986
|
#include "mupdf/fitz.h"
#if FZ_ENABLE_PDF
#include "mupdf/pdf.h"
#endif
#if FZ_ENABLE_JS
#include "mujs.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#define PS1 "> "
FZ_NORETURN static void rethrow(js_State *J)
{
js_newerror(J, fz_caught_message(js_getcontext(J)));
js_throw(J);
}
FZ_NORETURN static void rethrow_as_fz(js_State *J)
{
fz_throw(js_getcontext(J), FZ_ERROR_GENERIC, "%s", js_tostring(J, -1));
}
static void *alloc(void *actx, void *ptr, int n)
{
return fz_realloc_no_throw(actx, ptr, n);
}
static int eval_print(js_State *J, const char *source)
{
if (js_ploadstring(J, "[string]", source)) {
fprintf(stderr, "%s\n", js_trystring(J, -1, "Error"));
js_pop(J, 1);
return 1;
}
js_pushundefined(J);
if (js_pcall(J, 0)) {
fprintf(stderr, "%s\n", js_trystring(J, -1, "Error"));
js_pop(J, 1);
return 1;
}
if (js_isdefined(J, -1)) {
printf("%s\n", js_tryrepr(J, -1, "can't convert to string"));
}
js_pop(J, 1);
return 0;
}
static void jsB_propfun(js_State *J, const char *name, js_CFunction cfun, int n)
{
const char *realname = strchr(name, '.');
realname = realname ? realname + 1 : name;
js_newcfunction(J, cfun, name, n);
js_defproperty(J, -2, realname, JS_DONTENUM);
}
static void jsB_propcon(js_State *J, const char *tag, const char *name, js_CFunction cfun, int n)
{
const char *realname = strchr(name, '.');
realname = realname ? realname + 1 : name;
js_getregistry(J, tag);
js_newcconstructor(J, cfun, cfun, name, n);
js_defproperty(J, -2, realname, JS_DONTENUM);
}
static void jsB_gc(js_State *J)
{
int report = js_toboolean(J, 1);
js_gc(J, report);
js_pushundefined(J);
}
static void jsB_load(js_State *J)
{
const char *filename = js_tostring(J, 1);
int rv = js_dofile(J, filename);
js_pushboolean(J, !rv);
}
static void jsB_print(js_State *J)
{
unsigned int i, top = js_gettop(J);
for (i = 1; i < top; ++i) {
const char *s = js_tostring(J, i);
if (i > 1) putchar(' ');
fputs(s, stdout);
}
putchar('\n');
js_pushundefined(J);
}
static void jsB_write(js_State *J)
{
unsigned int i, top = js_gettop(J);
for (i = 1; i < top; ++i) {
const char *s = js_tostring(J, i);
if (i > 1) putchar(' ');
fputs(s, stdout);
}
js_pushundefined(J);
}
static void jsB_read(js_State *J)
{
fz_context *ctx = js_getcontext(J);
const char *filename = js_tostring(J, 1);
FILE *f;
char *s;
long n;
size_t t;
f = fopen(filename, "rb");
if (!f) {
js_error(J, "cannot open file: '%s'", filename);
}
if (fseek(f, 0, SEEK_END) < 0) {
fclose(f);
js_error(J, "cannot seek in file: '%s'", filename);
}
n = ftell(f);
if (n < 0) {
fclose(f);
js_error(J, "cannot tell in file: '%s'", filename);
}
if (fseek(f, 0, SEEK_SET) < 0) {
fclose(f);
js_error(J, "cannot seek in file: '%s'", filename);
}
s = fz_malloc(ctx, n + 1);
if (!s) {
fclose(f);
js_error(J, "cannot allocate storage for file contents: '%s'", filename);
}
t = fread(s, 1, n, f);
if (t != n) {
fz_free(ctx, s);
fclose(f);
js_error(J, "cannot read data from file: '%s'", filename);
}
s[n] = 0;
js_pushstring(J, s);
fz_free(ctx, s);
fclose(f);
}
static void jsB_readline(js_State *J)
{
char line[256];
size_t n;
if (!fgets(line, sizeof line, stdin))
js_error(J, "cannot read line from stdin");
n = strlen(line);
if (n > 0 && line[n-1] == '\n')
line[n-1] = 0;
js_pushstring(J, line);
}
static void jsB_repr(js_State *J)
{
js_repr(J, 1);
}
static void jsB_quit(js_State *J)
{
exit(js_tonumber(J, 1));
}
static const char *require_js =
"function require(name) {\n"
"var cache = require.cache;\n"
"if (name in cache) return cache[name];\n"
"var exports = {};\n"
"cache[name] = exports;\n"
"Function('exports', read(name+'.js'))(exports);\n"
"return exports;\n"
"}\n"
"require.cache = Object.create(null);\n"
;
static const char *stacktrace_js =
"Error.prototype.toString = function() {\n"
"if (this.stackTrace) return this.name + ': ' + this.message + this.stackTrace;\n"
"return this.name + ': ' + this.message;\n"
"};\n"
;
/* destructors */
static void ffi_gc_fz_buffer(js_State *J, void *buf)
{
fz_context *ctx = js_getcontext(J);
fz_try(ctx)
fz_drop_buffer(ctx, buf);
fz_catch(ctx)
rethrow(J);
}
static void ffi_gc_fz_document(js_State *J, void *doc)
{
fz_context *ctx = js_getcontext(J);
fz_drop_document(ctx, doc);
}
static void ffi_gc_fz_page(js_State *J, void *page)
{
fz_context *ctx = js_getcontext(J);
fz_drop_page(ctx, page);
}
static void ffi_gc_fz_colorspace(js_State *J, void *colorspace)
{
fz_context *ctx = js_getcontext(J);
fz_drop_colorspace(ctx, colorspace);
}
static void ffi_gc_fz_pixmap(js_State *J, void *pixmap)
{
fz_context *ctx = js_getcontext(J);
fz_drop_pixmap(ctx, pixmap);
}
static void ffi_gc_fz_path(js_State *J, void *path)
{
fz_context *ctx = js_getcontext(J);
fz_drop_path(ctx, path);
}
static void ffi_gc_fz_text(js_State *J, void *text)
{
fz_context *ctx = js_getcontext(J);
fz_drop_text(ctx, text);
}
static void ffi_gc_fz_font(js_State *J, void *font)
{
fz_context *ctx = js_getcontext(J);
fz_drop_font(ctx, font);
}
static void ffi_gc_fz_shade(js_State *J, void *shade)
{
fz_context *ctx = js_getcontext(J);
fz_drop_shade(ctx, shade);
}
static void ffi_gc_fz_image(js_State *J, void *image)
{
fz_context *ctx = js_getcontext(J);
fz_drop_image(ctx, image);
}
static void ffi_gc_fz_display_list(js_State *J, void *list)
{
fz_context *ctx = js_getcontext(J);
fz_drop_display_list(ctx, list);
}
static void ffi_gc_fz_stext_page(js_State *J, void *text)
{
fz_context *ctx = js_getcontext(J);
fz_drop_stext_page(ctx, text);
}
static void ffi_gc_fz_device(js_State *J, void *device)
{
fz_context *ctx = js_getcontext(J);
fz_drop_device(ctx, device);
}
static void ffi_gc_fz_document_writer(js_State *J, void *wri)
{
fz_context *ctx = js_getcontext(J);
fz_drop_document_writer(ctx, wri);
}
#if FZ_ENABLE_PDF
static void ffi_gc_pdf_annot(js_State *J, void *annot)
{
fz_context *ctx = js_getcontext(J);
pdf_drop_annot(ctx, annot);
}
static void ffi_gc_pdf_document(js_State *J, void *doc)
{
fz_context *ctx = js_getcontext(J);
pdf_drop_document(ctx, doc);
}
static void ffi_gc_pdf_obj(js_State *J, void *obj)
{
fz_context *ctx = js_getcontext(J);
pdf_drop_obj(ctx, obj);
}
static void ffi_gc_pdf_graft_map(js_State *J, void *map)
{
fz_context *ctx = js_getcontext(J);
pdf_drop_graft_map(ctx, map);
}
static fz_document *ffi_todocument(js_State *J, int idx)
{
if (js_isuserdata(J, idx, "pdf_document"))
return js_touserdata(J, idx, "pdf_document");
return js_touserdata(J, idx, "fz_document");
}
static void ffi_pushdocument(js_State *J, fz_document *document)
{
fz_context *ctx = js_getcontext(J);
pdf_document *pdocument = pdf_document_from_fz_document(ctx, document);
if (pdocument) {
js_getregistry(J, "pdf_document");
js_newuserdata(J, "pdf_document", document, ffi_gc_fz_document);
} else {
js_getregistry(J, "fz_document");
js_newuserdata(J, "fz_document", document, ffi_gc_fz_document);
}
}
static fz_page *ffi_topage(js_State *J, int idx)
{
if (js_isuserdata(J, idx, "pdf_page"))
return js_touserdata(J, idx, "pdf_page");
return js_touserdata(J, idx, "fz_page");
}
static void ffi_pushpage(js_State *J, fz_page *page)
{
fz_context *ctx = js_getcontext(J);
pdf_page *ppage = pdf_page_from_fz_page(ctx, page);
if (ppage) {
js_getregistry(J, "pdf_page");
js_newuserdata(J, "pdf_page", page, ffi_gc_fz_page);
} else {
js_getregistry(J, "fz_page");
js_newuserdata(J, "fz_page", page, ffi_gc_fz_page);
}
}
#else
static fz_document *ffi_todocument(js_State *J, int idx)
{
return js_touserdata(J, idx, "fz_document");
}
static void ffi_pushdocument(js_State *J, fz_document *document)
{
js_getregistry(J, "fz_document");
js_newuserdata(J, "fz_document", doc, ffi_gc_fz_document);
}
static fz_page *ffi_topage(js_State *J, int idx)
{
return js_touserdata(J, idx, "fz_page");
}
static void ffi_pushpage(js_State *J, fz_page *page)
{
js_getregistry(J, "fz_page");
js_newuserdata(J, "fz_page", page, ffi_gc_fz_page);
}
#endif /* FZ_ENABLE_PDF */
/* type conversions */
struct color {
fz_colorspace *colorspace;
float color[FZ_MAX_COLORS];
float alpha;
};
static fz_matrix ffi_tomatrix(js_State *J, int idx)
{
if (js_iscoercible(J, idx))
{
fz_matrix matrix;
js_getindex(J, idx, 0); matrix.a = js_tonumber(J, -1); js_pop(J, 1);
js_getindex(J, idx, 1); matrix.b = js_tonumber(J, -1); js_pop(J, 1);
js_getindex(J, idx, 2); matrix.c = js_tonumber(J, -1); js_pop(J, 1);
js_getindex(J, idx, 3); matrix.d = js_tonumber(J, -1); js_pop(J, 1);
js_getindex(J, idx, 4); matrix.e = js_tonumber(J, -1); js_pop(J, 1);
js_getindex(J, idx, 5); matrix.f = js_tonumber(J, -1); js_pop(J, 1);
return matrix;
}
return fz_identity;
}
static void ffi_pushmatrix(js_State *J, fz_matrix matrix)
{
js_newarray(J);
js_pushnumber(J, matrix.a); js_setindex(J, -2, 0);
js_pushnumber(J, matrix.b); js_setindex(J, -2, 1);
js_pushnumber(J, matrix.c); js_setindex(J, -2, 2);
js_pushnumber(J, matrix.d); js_setindex(J, -2, 3);
js_pushnumber(J, matrix.e); js_setindex(J, -2, 4);
js_pushnumber(J, matrix.f); js_setindex(J, -2, 5);
}
static fz_point ffi_topoint(js_State *J, int idx)
{
fz_point point;
js_getindex(J, idx, 0); point.x = js_tonumber(J, -1); js_pop(J, 1);
js_getindex(J, idx, 1); point.y = js_tonumber(J, -1); js_pop(J, 1);
return point;
}
static fz_rect ffi_torect(js_State *J, int idx)
{
fz_rect rect;
js_getindex(J, idx, 0); rect.x0 = js_tonumber(J, -1); js_pop(J, 1);
js_getindex(J, idx, 1); rect.y0 = js_tonumber(J, -1); js_pop(J, 1);
js_getindex(J, idx, 2); rect.x1 = js_tonumber(J, -1); js_pop(J, 1);
js_getindex(J, idx, 3); rect.y1 = js_tonumber(J, -1); js_pop(J, 1);
return rect;
}
static void ffi_pushrect(js_State *J, fz_rect rect)
{
js_newarray(J);
js_pushnumber(J, rect.x0); js_setindex(J, -2, 0);
js_pushnumber(J, rect.y0); js_setindex(J, -2, 1);
js_pushnumber(J, rect.x1); js_setindex(J, -2, 2);
js_pushnumber(J, rect.y1); js_setindex(J, -2, 3);
}
static void ffi_pushquad(js_State *J, fz_quad quad)
{
js_newarray(J);
js_pushnumber(J, quad.ul.x); js_setindex(J, -2, 0);
js_pushnumber(J, quad.ul.y); js_setindex(J, -2, 1);
js_pushnumber(J, quad.ur.x); js_setindex(J, -2, 2);
js_pushnumber(J, quad.ur.y); js_setindex(J, -2, 3);
js_pushnumber(J, quad.ll.x); js_setindex(J, -2, 4);
js_pushnumber(J, quad.ll.y); js_setindex(J, -2, 5);
js_pushnumber(J, quad.lr.x); js_setindex(J, -2, 6);
js_pushnumber(J, quad.lr.y); js_setindex(J, -2, 7);
}
static fz_irect ffi_toirect(js_State *J, int idx)
{
fz_irect irect;
js_getindex(J, idx, 0); irect.x0 = js_tonumber(J, -1); js_pop(J, 1);
js_getindex(J, idx, 1); irect.y0 = js_tonumber(J, -1); js_pop(J, 1);
js_getindex(J, idx, 2); irect.x1 = js_tonumber(J, -1); js_pop(J, 1);
js_getindex(J, idx, 3); irect.y1 = js_tonumber(J, -1); js_pop(J, 1);
return irect;
}
static void ffi_pusharray(js_State *J, const float *v, int n)
{
int i;
js_newarray(J);
for (i = 0; i < n; ++i) {
js_pushnumber(J, v[i]);
js_setindex(J, -2, i);
}
}
static void ffi_pushcolorspace(js_State *J, fz_colorspace *colorspace)
{
fz_context *ctx = js_getcontext(J);
if (colorspace == fz_device_rgb(ctx))
js_getregistry(J, "DeviceRGB");
else if (colorspace == fz_device_bgr(ctx))
js_getregistry(J, "DeviceBGR");
else if (colorspace == fz_device_gray(ctx))
js_getregistry(J, "DeviceGray");
else if (colorspace == fz_device_cmyk(ctx))
js_getregistry(J, "DeviceCMYK");
else {
js_getregistry(J, "fz_colorspace");
js_newuserdata(J, "fz_colorspace", fz_keep_colorspace(ctx, colorspace), ffi_gc_fz_colorspace);
}
}
static void ffi_pushcolor(js_State *J, fz_colorspace *colorspace, const float *color, float alpha)
{
fz_context *ctx = js_getcontext(J);
if (colorspace) {
ffi_pushcolorspace(J, colorspace);
ffi_pusharray(J, color, fz_colorspace_n(ctx, colorspace));
} else {
js_pushnull(J);
js_pushnull(J);
}
js_pushnumber(J, alpha);
}
static struct color ffi_tocolor(js_State *J, int idx)
{
struct color c;
int n, i;
fz_context *ctx = js_getcontext(J);
c.colorspace = js_touserdata(J, idx, "fz_colorspace");
if (c.colorspace) {
n = fz_colorspace_n(ctx, c.colorspace);
for (i=0; i < n; ++i) {
js_getindex(J, idx + 1, i);
c.color[i] = js_tonumber(J, -1);
js_pop(J, 1);
}
}
c.alpha = js_tonumber(J, idx + 2);
return c;
}
static fz_color_params ffi_tocolorparams(js_State *J, int idx)
{
/* TODO */
return fz_default_color_params;
}
static void ffi_pushcolorparams(js_State *J, fz_color_params color_params)
{
/* TODO */
js_pushnull(J);
}
static const char *string_from_cap(fz_linecap cap)
{
switch (cap) {
default:
case FZ_LINECAP_BUTT: return "Butt";
case FZ_LINECAP_ROUND: return "Round";
case FZ_LINECAP_SQUARE: return "Square";
case FZ_LINECAP_TRIANGLE: return "Triangle";
}
}
static const char *string_from_join(fz_linejoin join)
{
switch (join) {
default:
case FZ_LINEJOIN_MITER: return "Miter";
case FZ_LINEJOIN_ROUND: return "Round";
case FZ_LINEJOIN_BEVEL: return "Bevel";
case FZ_LINEJOIN_MITER_XPS: return "MiterXPS";
}
}
static fz_linecap cap_from_string(const char *str)
{
if (!strcmp(str, "Round")) return FZ_LINECAP_ROUND;
if (!strcmp(str, "Square")) return FZ_LINECAP_SQUARE;
if (!strcmp(str, "Triangle")) return FZ_LINECAP_TRIANGLE;
return FZ_LINECAP_BUTT;
}
static fz_linejoin join_from_string(const char *str)
{
if (!strcmp(str, "Round")) return FZ_LINEJOIN_ROUND;
if (!strcmp(str, "Bevel")) return FZ_LINEJOIN_BEVEL;
if (!strcmp(str, "MiterXPS")) return FZ_LINEJOIN_MITER_XPS;
return FZ_LINEJOIN_MITER;
}
static void ffi_pushstroke(js_State *J, const fz_stroke_state *stroke)
{
js_newobject(J);
js_pushliteral(J, string_from_cap(stroke->start_cap));
js_setproperty(J, -2, "startCap");
js_pushliteral(J, string_from_cap(stroke->dash_cap));
js_setproperty(J, -2, "dashCap");
js_pushliteral(J, string_from_cap(stroke->end_cap));
js_setproperty(J, -2, "endCap");
js_pushliteral(J, string_from_join(stroke->linejoin));
js_setproperty(J, -2, "lineJoin");
js_pushnumber(J, stroke->linewidth);
js_setproperty(J, -2, "lineWidth");
js_pushnumber(J, stroke->miterlimit);
js_setproperty(J, -2, "miterLimit");
js_pushnumber(J, stroke->dash_phase);
js_setproperty(J, -2, "dashPhase");
ffi_pusharray(J, stroke->dash_list, stroke->dash_len);
js_setproperty(J, -2, "dashes");
}
static fz_stroke_state ffi_tostroke(js_State *J, int idx)
{
fz_stroke_state stroke = fz_default_stroke_state;
if (js_hasproperty(J, idx, "lineCap")) {
stroke.start_cap = cap_from_string(js_tostring(J, -1));
stroke.dash_cap = stroke.start_cap;
stroke.end_cap = stroke.start_cap;
}
if (js_hasproperty(J, idx, "startCap")) {
stroke.start_cap = cap_from_string(js_tostring(J, -1));
js_pop(J, 1);
}
if (js_hasproperty(J, idx, "dashCap")) {
stroke.dash_cap = cap_from_string(js_tostring(J, -1));
js_pop(J, 1);
}
if (js_hasproperty(J, idx, "endCap")) {
stroke.end_cap = cap_from_string(js_tostring(J, -1));
js_pop(J, 1);
}
if (js_hasproperty(J, idx, "lineJoin")) {
stroke.linejoin = join_from_string(js_tostring(J, -1));
js_pop(J, 1);
}
if (js_hasproperty(J, idx, "lineWidth")) {
stroke.linewidth = js_tonumber(J, -1);
js_pop(J, 1);
}
if (js_hasproperty(J, idx, "miterLimit")) {
stroke.miterlimit = js_tonumber(J, -1);
js_pop(J, 1);
}
if (js_hasproperty(J, idx, "dashPhase")) {
stroke.dash_phase = js_tonumber(J, -1);
js_pop(J, 1);
}
if (js_hasproperty(J, idx, "dashes")) {
int i, n = js_getlength(J, -1);
if (n > nelem(stroke.dash_list))
n = nelem(stroke.dash_list);
stroke.dash_len = n;
for (i = 0; i < n; ++i) {
js_getindex(J, -1, i);
stroke.dash_list[i] = js_tonumber(J, -1);
js_pop(J, 1);
}
}
return stroke;
}
static void ffi_pushtext(js_State *J, const fz_text *text)
{
fz_context *ctx = js_getcontext(J);
js_getregistry(J, "fz_text");
js_newuserdata(J, "fz_text", fz_keep_text(ctx, text), ffi_gc_fz_text);
}
static void ffi_pushpath(js_State *J, const fz_path *path)
{
fz_context *ctx = js_getcontext(J);
js_getregistry(J, "fz_path");
js_newuserdata(J, "fz_path", fz_keep_path(ctx, path), ffi_gc_fz_path);
}
static void ffi_pushfont(js_State *J, fz_font *font)
{
fz_context *ctx = js_getcontext(J);
js_getregistry(J, "fz_font");
js_newuserdata(J, "fz_font", fz_keep_font(ctx, font), ffi_gc_fz_font);
}
static void ffi_pushshade(js_State *J, fz_shade *shade)
{
fz_context *ctx = js_getcontext(J);
js_getregistry(J, "fz_shade");
js_newuserdata(J, "fz_shade", fz_keep_shade(ctx, shade), ffi_gc_fz_shade);
}
static void ffi_pushimage(js_State *J, fz_image *image)
{
fz_context *ctx = js_getcontext(J);
js_getregistry(J, "fz_image");
js_newuserdata(J, "fz_image", fz_keep_image(ctx, image), ffi_gc_fz_image);
}
static void ffi_pushimage_own(js_State *J, fz_image *image)
{
js_getregistry(J, "fz_image");
js_newuserdata(J, "fz_image", image, ffi_gc_fz_image);
}
static int is_number(const char *key, int *idx)
{
char *end;
*idx = strtol(key, &end, 10);
return *end == 0;
}
static int ffi_buffer_has(js_State *J, void *buf_, const char *key)
{
fz_buffer *buf = buf_;
int idx;
unsigned char *data;
size_t len = fz_buffer_storage(js_getcontext(J), buf, &data);
if (is_number(key, &idx)) {
if (idx < 0 || (size_t)idx >= len)
js_rangeerror(J, "index out of bounds");
js_pushnumber(J, data[idx]);
return 1;
}
if (!strcmp(key, "length")) {
js_pushnumber(J, len);
return 1;
}
return 0;
}
static int ffi_buffer_put(js_State *J, void *buf_, const char *key)
{
fz_buffer *buf = buf_;
int idx;
unsigned char *data;
size_t len = fz_buffer_storage(js_getcontext(J), buf, &data);
if (is_number(key, &idx)) {
if (idx < 0 || (size_t)idx >= len)
js_rangeerror(J, "index out of bounds");
data[idx] = js_tonumber(J, -1);
return 1;
}
if (!strcmp(key, "length"))
js_typeerror(J, "buffer length is read-only");
return 0;
}
static void ffi_pushbuffer(js_State *J, fz_buffer *buf)
{
js_getregistry(J, "fz_buffer");
js_newuserdatax(J, "fz_buffer", buf,
ffi_buffer_has, ffi_buffer_put, NULL,
ffi_gc_fz_buffer);
}
#if FZ_ENABLE_PDF
static fz_buffer *ffi_tobuffer(js_State *J, int idx)
{
fz_context *ctx = js_getcontext(J);
fz_buffer *buf = NULL;
if (js_isuserdata(J, idx, "fz_buffer"))
buf = fz_keep_buffer(ctx, js_touserdata(J, idx, "fz_buffer"));
else {
const char *str = js_tostring(J, idx);
fz_try(ctx)
buf = fz_new_buffer_from_copied_data(ctx, (const unsigned char *)str, strlen(str));
fz_catch(ctx)
rethrow(J);
}
return buf;
}
#endif /* FZ_ENABLE_PDF */
/* device calling into js from c */
typedef struct js_device_s
{
fz_device super;
js_State *J;
} js_device;
static void
js_dev_fill_path(fz_context *ctx, fz_device *dev, const fz_path *path, int even_odd, fz_matrix ctm,
fz_colorspace *colorspace, const float *color, float alpha, fz_color_params color_params)
{
js_State *J = ((js_device*)dev)->J;
if (js_try(J))
rethrow_as_fz(J);
if (js_hasproperty(J, -1, "fillPath")) {
js_copy(J, -2);
ffi_pushpath(J, path);
js_pushboolean(J, even_odd);
ffi_pushmatrix(J, ctm);
ffi_pushcolor(J, colorspace, color, alpha);
ffi_pushcolorparams(J, color_params);
js_call(J, 7);
js_pop(J, 1);
}
js_endtry(J);
}
static void
js_dev_clip_path(fz_context *ctx, fz_device *dev, const fz_path *path, int even_odd, fz_matrix ctm,
fz_rect scissor)
{
js_State *J = ((js_device*)dev)->J;
if (js_try(J))
rethrow_as_fz(J);
if (js_hasproperty(J, -1, "clipPath")) {
js_copy(J, -2);
ffi_pushpath(J, path);
js_pushboolean(J, even_odd);
ffi_pushmatrix(J, ctm);
js_call(J, 3);
js_pop(J, 1);
}
js_endtry(J);
}
static void
js_dev_stroke_path(fz_context *ctx, fz_device *dev, const fz_path *path,
const fz_stroke_state *stroke, fz_matrix ctm,
fz_colorspace *colorspace, const float *color, float alpha, fz_color_params color_params)
{
js_State *J = ((js_device*)dev)->J;
if (js_try(J))
rethrow_as_fz(J);
if (js_hasproperty(J, -1, "strokePath")) {
js_copy(J, -2);
ffi_pushpath(J, path);
ffi_pushstroke(J, stroke);
ffi_pushmatrix(J, ctm);
ffi_pushcolor(J, colorspace, color, alpha);
ffi_pushcolorparams(J, color_params);
js_call(J, 7);
js_pop(J, 1);
}
js_endtry(J);
}
static void
js_dev_clip_stroke_path(fz_context *ctx, fz_device *dev, const fz_path *path, const fz_stroke_state *stroke,
fz_matrix ctm, fz_rect scissor)
{
js_State *J = ((js_device*)dev)->J;
if (js_try(J))
rethrow_as_fz(J);
if (js_hasproperty(J, -1, "clipStrokePath")) {
js_copy(J, -2);
ffi_pushpath(J, path);
ffi_pushstroke(J, stroke);
ffi_pushmatrix(J, ctm);
js_call(J, 3);
js_pop(J, 1);
}
js_endtry(J);
}
static void
js_dev_fill_text(fz_context *ctx, fz_device *dev, const fz_text *text, fz_matrix ctm,
fz_colorspace *colorspace, const float *color, float alpha, fz_color_params color_params)
{
js_State *J = ((js_device*)dev)->J;
if (js_try(J))
rethrow_as_fz(J);
if (js_hasproperty(J, -1, "fillText")) {
js_copy(J, -2);
ffi_pushtext(J, text);
ffi_pushmatrix(J, ctm);
ffi_pushcolor(J, colorspace, color, alpha);
ffi_pushcolorparams(J, color_params);
js_call(J, 6);
js_pop(J, 1);
}
js_endtry(J);
}
static void
js_dev_stroke_text(fz_context *ctx, fz_device *dev, const fz_text *text, const fz_stroke_state *stroke,
fz_matrix ctm, fz_colorspace *colorspace, const float *color, float alpha, fz_color_params color_params)
{
js_State *J = ((js_device*)dev)->J;
if (js_try(J))
rethrow_as_fz(J);
if (js_hasproperty(J, -1, "strokeText")) {
js_copy(J, -2);
ffi_pushtext(J, text);
ffi_pushstroke(J, stroke);
ffi_pushmatrix(J, ctm);
ffi_pushcolor(J, colorspace, color, alpha);
ffi_pushcolorparams(J, color_params);
js_call(J, 7);
js_pop(J, 1);
}
js_endtry(J);
}
static void
js_dev_clip_text(fz_context *ctx, fz_device *dev, const fz_text *text, fz_matrix ctm, fz_rect scissor)
{
js_State *J = ((js_device*)dev)->J;
if (js_try(J))
rethrow_as_fz(J);
if (js_hasproperty(J, -1, "clipText")) {
js_copy(J, -2);
ffi_pushtext(J, text);
ffi_pushmatrix(J, ctm);
js_call(J, 2);
js_pop(J, 1);
}
js_endtry(J);
}
static void
js_dev_clip_stroke_text(fz_context *ctx, fz_device *dev, const fz_text *text, const fz_stroke_state *stroke,
fz_matrix ctm, fz_rect scissor)
{
js_State *J = ((js_device*)dev)->J;
if (js_try(J))
rethrow_as_fz(J);
if (js_hasproperty(J, -1, "clipStrokeText")) {
js_copy(J, -2);
ffi_pushtext(J, text);
ffi_pushstroke(J, stroke);
ffi_pushmatrix(J, ctm);
js_call(J, 3);
js_pop(J, 1);
}
js_endtry(J);
}
static void
js_dev_ignore_text(fz_context *ctx, fz_device *dev, const fz_text *text, fz_matrix ctm)
{
js_State *J = ((js_device*)dev)->J;
if (js_try(J))
rethrow_as_fz(J);
if (js_hasproperty(J, -1, "ignoreText")) {
js_copy(J, -2);
ffi_pushtext(J, text);
ffi_pushmatrix(J, ctm);
js_call(J, 2);
js_pop(J, 1);
}
js_endtry(J);
}
static void
js_dev_fill_shade(fz_context *ctx, fz_device *dev, fz_shade *shade, fz_matrix ctm, float alpha, fz_color_params color_params)
{
js_State *J = ((js_device*)dev)->J;
if (js_try(J))
rethrow_as_fz(J);
if (js_hasproperty(J, -1, "fillShade")) {
js_copy(J, -2);
ffi_pushshade(J, shade);
ffi_pushmatrix(J, ctm);
js_pushnumber(J, alpha);
ffi_pushcolorparams(J, color_params);
js_call(J, 4);
js_pop(J, 1);
}
js_endtry(J);
}
static void
js_dev_fill_image(fz_context *ctx, fz_device *dev, fz_image *image, fz_matrix ctm, float alpha, fz_color_params color_params)
{
js_State *J = ((js_device*)dev)->J;
if (js_try(J))
rethrow_as_fz(J);
if (js_hasproperty(J, -1, "fillImage")) {
js_copy(J, -2);
ffi_pushimage(J, image);
ffi_pushmatrix(J, ctm);
js_pushnumber(J, alpha);
ffi_pushcolorparams(J, color_params);
js_call(J, 4);
js_pop(J, 1);
}
js_endtry(J);
}
static void
js_dev_fill_image_mask(fz_context *ctx, fz_device *dev, fz_image *image, fz_matrix ctm,
fz_colorspace *colorspace, const float *color, float alpha, fz_color_params color_params)
{
js_State *J = ((js_device*)dev)->J;
if (js_try(J))
rethrow_as_fz(J);
if (js_hasproperty(J, -1, "fillImageMask")) {
js_copy(J, -2);
ffi_pushimage(J, image);
ffi_pushmatrix(J, ctm);
ffi_pushcolor(J, colorspace, color, alpha);
ffi_pushcolorparams(J, color_params);
js_call(J, 6);
js_pop(J, 1);
}
js_endtry(J);
}
static void
js_dev_clip_image_mask(fz_context *ctx, fz_device *dev, fz_image *image, fz_matrix ctm, fz_rect scissor)
{
js_State *J = ((js_device*)dev)->J;
if (js_try(J))
rethrow_as_fz(J);
if (js_hasproperty(J, -1, "clipImageMask")) {
js_copy(J, -2);
ffi_pushimage(J, image);
ffi_pushmatrix(J, ctm);
js_call(J, 2);
js_pop(J, 1);
}
js_endtry(J);
}
static void
js_dev_pop_clip(fz_context *ctx, fz_device *dev)
{
js_State *J = ((js_device*)dev)->J;
if (js_try(J))
rethrow_as_fz(J);
if (js_hasproperty(J, -1, "popClip")) {
js_copy(J, -2);
js_call(J, 0);
js_pop(J, 1);
}
js_endtry(J);
}
static void
js_dev_begin_mask(fz_context *ctx, fz_device *dev, fz_rect bbox, int luminosity,
fz_colorspace *colorspace, const float *color, fz_color_params color_params)
{
js_State *J = ((js_device*)dev)->J;
if (js_try(J))
rethrow_as_fz(J);
if (js_hasproperty(J, -1, "beginMask")) {
js_copy(J, -2);
ffi_pushrect(J, bbox);
js_pushboolean(J, luminosity);
ffi_pushcolor(J, colorspace, color, 1);
ffi_pushcolorparams(J, color_params);
js_call(J, 6);
js_pop(J, 1);
}
js_endtry(J);
}
static void
js_dev_end_mask(fz_context *ctx, fz_device *dev)
{
js_State *J = ((js_device*)dev)->J;
if (js_try(J))
rethrow_as_fz(J);
if (js_hasproperty(J, -1, "endMask")) {
js_copy(J, -2);
js_call(J, 0);
js_pop(J, 1);
}
js_endtry(J);
}
static void
js_dev_begin_group(fz_context *ctx, fz_device *dev, fz_rect bbox,
fz_colorspace *cs, int isolated, int knockout, int blendmode, float alpha)
{
js_State *J = ((js_device*)dev)->J;
if (js_try(J))
rethrow_as_fz(J);
if (js_hasproperty(J, -1, "beginGroup")) {
js_copy(J, -2);
ffi_pushrect(J, bbox);
js_pushboolean(J, isolated);
js_pushboolean(J, knockout);
js_pushliteral(J, fz_blendmode_name(blendmode));
js_pushnumber(J, alpha);
js_call(J, 5);
js_pop(J, 1);
}
js_endtry(J);
}
static void
js_dev_end_group(fz_context *ctx, fz_device *dev)
{
js_State *J = ((js_device*)dev)->J;
if (js_try(J))
rethrow_as_fz(J);
if (js_hasproperty(J, -1, "endGroup")) {
js_copy(J, -2);
js_call(J, 0);
js_pop(J, 1);
}
js_endtry(J);
}
static int
js_dev_begin_tile(fz_context *ctx, fz_device *dev, fz_rect area, fz_rect view,
float xstep, float ystep, fz_matrix ctm, int id)
{
js_State *J = ((js_device*)dev)->J;
if (js_try(J))
rethrow_as_fz(J);
if (js_hasproperty(J, -1, "beginTile")) {
int n;
js_copy(J, -2);
ffi_pushrect(J, area);
ffi_pushrect(J, view);
js_pushnumber(J, xstep);
js_pushnumber(J, ystep);
ffi_pushmatrix(J, ctm);
js_pushnumber(J, id);
js_call(J, 6);
n = js_tointeger(J, -1);
js_pop(J, 1);
return n;
}
js_endtry(J);
return 0;
}
static void
js_dev_end_tile(fz_context *ctx, fz_device *dev)
{
js_State *J = ((js_device*)dev)->J;
if (js_try(J))
rethrow_as_fz(J);
if (js_hasproperty(J, -1, "endTile")) {
js_copy(J, -2);
js_call(J, 0);
js_pop(J, 1);
}
js_endtry(J);
}
static void
js_dev_begin_layer(fz_context *ctx, fz_device *dev, const char *name)
{
js_State *J = ((js_device*)dev)->J;
if (js_try(J))
rethrow_as_fz(J);
if (js_hasproperty(J, -1, "beginLayer")) {
js_copy(J, -2);
js_pushstring(J, name);
js_call(J, 1);
js_pop(J, 1);
}
js_endtry(J);
}
static void
js_dev_end_layer(fz_context *ctx, fz_device *dev)
{
js_State *J = ((js_device*)dev)->J;
if (js_try(J))
rethrow_as_fz(J);
if (js_hasproperty(J, -1, "endLayer")) {
js_copy(J, -2);
js_call(J, 0);
js_pop(J, 1);
}
js_endtry(J);
}
static fz_device *new_js_device(fz_context *ctx, js_State *J)
{
js_device *dev = fz_new_derived_device(ctx, js_device);
dev->super.fill_path = js_dev_fill_path;
dev->super.stroke_path = js_dev_stroke_path;
dev->super.clip_path = js_dev_clip_path;
dev->super.clip_stroke_path = js_dev_clip_stroke_path;
dev->super.fill_text = js_dev_fill_text;
dev->super.stroke_text = js_dev_stroke_text;
dev->super.clip_text = js_dev_clip_text;
dev->super.clip_stroke_text = js_dev_clip_stroke_text;
dev->super.ignore_text = js_dev_ignore_text;
dev->super.fill_shade = js_dev_fill_shade;
dev->super.fill_image = js_dev_fill_image;
dev->super.fill_image_mask = js_dev_fill_image_mask;
dev->super.clip_image_mask = js_dev_clip_image_mask;
dev->super.pop_clip = js_dev_pop_clip;
dev->super.begin_mask = js_dev_begin_mask;
dev->super.end_mask = js_dev_end_mask;
dev->super.begin_group = js_dev_begin_group;
dev->super.end_group = js_dev_end_group;
dev->super.begin_tile = js_dev_begin_tile;
dev->super.end_tile = js_dev_end_tile;
dev->super.begin_layer = js_dev_begin_layer;
dev->super.end_layer = js_dev_end_layer;
dev->J = J;
return (fz_device*)dev;
}
/* device calling into c from js */
static void ffi_Device_close(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_device *dev = js_touserdata(J, 0, "fz_device");
fz_try(ctx)
fz_close_device(ctx, dev);
fz_catch(ctx)
rethrow(J);
}
static void ffi_Device_fillPath(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_device *dev = js_touserdata(J, 0, "fz_device");
fz_path *path = js_touserdata(J, 1, "fz_path");
int even_odd = js_toboolean(J, 2);
fz_matrix ctm = ffi_tomatrix(J, 3);
struct color c = ffi_tocolor(J, 4);
fz_color_params color_params = ffi_tocolorparams(J, 7);
fz_try(ctx)
fz_fill_path(ctx, dev, path, even_odd, ctm, c.colorspace, c.color, c.alpha, color_params);
fz_catch(ctx)
rethrow(J);
}
static void ffi_Device_strokePath(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_device *dev = js_touserdata(J, 0, "fz_device");
fz_path *path = js_touserdata(J, 1, "fz_path");
fz_stroke_state stroke = ffi_tostroke(J, 2);
fz_matrix ctm = ffi_tomatrix(J, 3);
struct color c = ffi_tocolor(J, 4);
fz_color_params color_params = ffi_tocolorparams(J, 7);
fz_try(ctx)
fz_stroke_path(ctx, dev, path, &stroke, ctm, c.colorspace, c.color, c.alpha, color_params);
fz_catch(ctx)
rethrow(J);
}
static void ffi_Device_clipPath(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_device *dev = js_touserdata(J, 0, "fz_device");
fz_path *path = js_touserdata(J, 1, "fz_path");
int even_odd = js_toboolean(J, 2);
fz_matrix ctm = ffi_tomatrix(J, 3);
fz_try(ctx)
fz_clip_path(ctx, dev, path, even_odd, ctm, fz_infinite_rect);
fz_catch(ctx)
rethrow(J);
}
static void ffi_Device_clipStrokePath(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_device *dev = js_touserdata(J, 0, "fz_device");
fz_path *path = js_touserdata(J, 1, "fz_path");
fz_stroke_state stroke = ffi_tostroke(J, 2);
fz_matrix ctm = ffi_tomatrix(J, 3);
fz_try(ctx)
fz_clip_stroke_path(ctx, dev, path, &stroke, ctm, fz_infinite_rect);
fz_catch(ctx)
rethrow(J);
}
static void ffi_Device_fillText(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_device *dev = js_touserdata(J, 0, "fz_device");
fz_text *text = js_touserdata(J, 1, "fz_text");
fz_matrix ctm = ffi_tomatrix(J, 2);
struct color c = ffi_tocolor(J, 3);
fz_color_params color_params = ffi_tocolorparams(J, 6);
fz_try(ctx)
fz_fill_text(ctx, dev, text, ctm, c.colorspace, c.color, c.alpha, color_params);
fz_catch(ctx)
rethrow(J);
}
static void ffi_Device_strokeText(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_device *dev = js_touserdata(J, 0, "fz_device");
fz_text *text = js_touserdata(J, 1, "fz_text");
fz_stroke_state stroke = ffi_tostroke(J, 2);
fz_matrix ctm = ffi_tomatrix(J, 3);
struct color c = ffi_tocolor(J, 4);
fz_color_params color_params = ffi_tocolorparams(J, 7);
fz_try(ctx)
fz_stroke_text(ctx, dev, text, &stroke, ctm, c.colorspace, c.color, c.alpha, color_params);
fz_catch(ctx)
rethrow(J);
}
static void ffi_Device_clipText(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_device *dev = js_touserdata(J, 0, "fz_device");
fz_text *text = js_touserdata(J, 1, "fz_text");
fz_matrix ctm = ffi_tomatrix(J, 2);
fz_try(ctx)
fz_clip_text(ctx, dev, text, ctm, fz_infinite_rect);
fz_catch(ctx)
rethrow(J);
}
static void ffi_Device_clipStrokeText(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_device *dev = js_touserdata(J, 0, "fz_device");
fz_text *text = js_touserdata(J, 1, "fz_text");
fz_stroke_state stroke = ffi_tostroke(J, 2);
fz_matrix ctm = ffi_tomatrix(J, 3);
fz_try(ctx)
fz_clip_stroke_text(ctx, dev, text, &stroke, ctm, fz_infinite_rect);
fz_catch(ctx)
rethrow(J);
}
static void ffi_Device_ignoreText(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_device *dev = js_touserdata(J, 0, "fz_device");
fz_text *text = js_touserdata(J, 1, "fz_text");
fz_matrix ctm = ffi_tomatrix(J, 2);
fz_try(ctx)
fz_ignore_text(ctx, dev, text, ctm);
fz_catch(ctx)
rethrow(J);
}
static void ffi_Device_fillShade(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_device *dev = js_touserdata(J, 0, "fz_device");
fz_shade *shade = js_touserdata(J, 1, "fz_shade");
fz_matrix ctm = ffi_tomatrix(J, 2);
float alpha = js_tonumber(J, 3);
fz_color_params color_params = ffi_tocolorparams(J, 4);
fz_try(ctx)
fz_fill_shade(ctx, dev, shade, ctm, alpha, color_params);
fz_catch(ctx)
rethrow(J);
}
static void ffi_Device_fillImage(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_device *dev = js_touserdata(J, 0, "fz_device");
fz_image *image = js_touserdata(J, 1, "fz_image");
fz_matrix ctm = ffi_tomatrix(J, 2);
float alpha = js_tonumber(J, 3);
fz_color_params color_params = ffi_tocolorparams(J, 4);
fz_try(ctx)
fz_fill_image(ctx, dev, image, ctm, alpha, color_params);
fz_catch(ctx)
rethrow(J);
}
static void ffi_Device_fillImageMask(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_device *dev = js_touserdata(J, 0, "fz_device");
fz_image *image = js_touserdata(J, 1, "fz_image");
fz_matrix ctm = ffi_tomatrix(J, 2);
struct color c = ffi_tocolor(J, 3);
fz_color_params color_params = ffi_tocolorparams(J, 6);
fz_try(ctx)
fz_fill_image_mask(ctx, dev, image, ctm, c.colorspace, c.color, c.alpha, color_params);
fz_catch(ctx)
rethrow(J);
}
static void ffi_Device_clipImageMask(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_device *dev = js_touserdata(J, 0, "fz_device");
fz_image *image = js_touserdata(J, 1, "fz_image");
fz_matrix ctm = ffi_tomatrix(J, 2);
fz_try(ctx)
fz_clip_image_mask(ctx, dev, image, ctm, fz_infinite_rect);
fz_catch(ctx)
rethrow(J);
}
static void ffi_Device_popClip(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_device *dev = js_touserdata(J, 0, "fz_device");
fz_try(ctx)
fz_pop_clip(ctx, dev);
fz_catch(ctx)
rethrow(J);
}
static void ffi_Device_beginMask(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_device *dev = js_touserdata(J, 0, "fz_device");
fz_rect area = ffi_torect(J, 1);
int luminosity = js_toboolean(J, 2);
struct color c = ffi_tocolor(J, 3);
fz_color_params color_params = ffi_tocolorparams(J, 6);
fz_try(ctx)
fz_begin_mask(ctx, dev, area, luminosity, c.colorspace, c.color, color_params);
fz_catch(ctx)
rethrow(J);
}
static void ffi_Device_endMask(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_device *dev = js_touserdata(J, 0, "fz_device");
fz_try(ctx)
fz_end_mask(ctx, dev);
fz_catch(ctx)
rethrow(J);
}
static void ffi_Device_beginGroup(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_device *dev = js_touserdata(J, 0, "fz_device");
fz_rect area = ffi_torect(J, 1);
int isolated = js_toboolean(J, 2);
int knockout = js_toboolean(J, 3);
int blendmode = fz_lookup_blendmode(js_tostring(J, 4));
float alpha = js_tonumber(J, 5);
fz_try(ctx)
fz_begin_group(ctx, dev, area, NULL, isolated, knockout, blendmode, alpha);
fz_catch(ctx)
rethrow(J);
}
static void ffi_Device_endGroup(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_device *dev = js_touserdata(J, 0, "fz_device");
fz_try(ctx)
fz_end_group(ctx, dev);
fz_catch(ctx)
rethrow(J);
}
static void ffi_Device_beginTile(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_device *dev = js_touserdata(J, 0, "fz_device");
fz_rect area = ffi_torect(J, 1);
fz_rect view = ffi_torect(J, 2);
float xstep = js_tonumber(J, 3);
float ystep = js_tonumber(J, 4);
fz_matrix ctm = ffi_tomatrix(J, 5);
int id = js_tonumber(J, 6);
int n = 0;
fz_try(ctx)
n = fz_begin_tile_id(ctx, dev, area, view, xstep, ystep, ctm, id);
fz_catch(ctx)
rethrow(J);
js_pushnumber(J, n);
}
static void ffi_Device_endTile(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_device *dev = js_touserdata(J, 0, "fz_device");
fz_try(ctx)
fz_end_tile(ctx, dev);
fz_catch(ctx)
rethrow(J);
}
static void ffi_Device_beginLayer(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_device *dev = js_touserdata(J, 0, "fz_device");
const char *name = js_tostring(J, 1);
fz_try(ctx)
fz_begin_layer(ctx, dev, name);
fz_catch(ctx)
rethrow(J);
}
static void ffi_Device_endLayer(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_device *dev = js_touserdata(J, 0, "fz_device");
fz_try(ctx)
fz_end_layer(ctx, dev);
fz_catch(ctx)
rethrow(J);
}
/* mupdf module */
static void ffi_readFile(js_State *J)
{
fz_context *ctx = js_getcontext(J);
const char *filename = js_tostring(J, 1);
fz_buffer *buf = NULL;
fz_try(ctx)
buf = fz_read_file(ctx, filename);
fz_catch(ctx)
rethrow(J);
ffi_pushbuffer(J, buf);
}
static void ffi_setUserCSS(js_State *J)
{
fz_context *ctx = js_getcontext(J);
const char *user_css = js_tostring(J, 1);
int use_doc_css = js_iscoercible(J, 2) ? js_toboolean(J, 2) : 1;
fz_try(ctx) {
fz_set_user_css(ctx, user_css);
fz_set_use_document_css(ctx, use_doc_css);
} fz_catch(ctx)
rethrow(J);
}
static void ffi_new_Buffer(js_State *J)
{
fz_context *ctx = js_getcontext(J);
int n = js_isdefined(J, 1) ? js_tonumber(J, 1) : 0;
fz_buffer *buf = NULL;
fz_try(ctx)
buf = fz_new_buffer(ctx, n);
fz_catch(ctx)
rethrow(J);
ffi_pushbuffer(J, buf);
}
static void ffi_Buffer_writeByte(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_buffer *buf = js_touserdata(J, 0, "fz_buffer");
unsigned char val = js_tonumber(J, 1);
fz_try(ctx)
fz_append_byte(ctx, buf, val);
fz_catch(ctx)
rethrow(J);
}
static void ffi_Buffer_writeRune(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_buffer *buf = js_touserdata(J, 0, "fz_buffer");
int val = js_tonumber(J, 1);
fz_try(ctx)
fz_append_rune(ctx, buf, val);
fz_catch(ctx)
rethrow(J);
}
static void ffi_Buffer_write(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_buffer *buf = js_touserdata(J, 0, "fz_buffer");
int i, n = js_gettop(J);
for (i = 1; i < n; ++i) {
const char *s = js_tostring(J, i);
fz_try(ctx) {
if (i > 1)
fz_append_byte(ctx, buf, ' ');
fz_append_string(ctx, buf, s);
} fz_catch(ctx)
rethrow(J);
}
}
static void ffi_Buffer_writeLine(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_buffer *buf = js_touserdata(J, 0, "fz_buffer");
ffi_Buffer_write(J);
fz_try(ctx)
fz_append_byte(ctx, buf, '\n');
fz_catch(ctx)
rethrow(J);
}
static void ffi_Buffer_writeBuffer(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_buffer *buf = js_touserdata(J, 0, "fz_buffer");
fz_buffer *cat = js_touserdata(J, 1, "fz_buffer");
fz_try(ctx)
fz_append_buffer(ctx, buf, cat);
fz_catch(ctx)
rethrow(J);
}
static void ffi_Buffer_save(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_buffer *buf = js_touserdata(J, 0, "fz_buffer");
const char *filename = js_tostring(J, 1);
fz_try(ctx)
fz_save_buffer(ctx, buf, filename);
fz_catch(ctx)
rethrow(J);
}
static void ffi_new_Document(js_State *J)
{
fz_context *ctx = js_getcontext(J);
const char *filename = js_tostring(J, 1);
fz_document *doc = NULL;
fz_try(ctx)
doc = fz_open_document(ctx, filename);
fz_catch(ctx)
rethrow(J);
ffi_pushdocument(J, doc);
}
static void ffi_Document_isPDF(js_State *J)
{
js_pushboolean(J, js_isuserdata(J, 0, "pdf_document"));
}
static void ffi_Document_countPages(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_document *doc = ffi_todocument(J, 0);
int count = 0;
fz_try(ctx)
count = fz_count_pages(ctx, doc);
fz_catch(ctx)
rethrow(J);
js_pushnumber(J, count);
}
static void ffi_Document_loadPage(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_document *doc = ffi_todocument(J, 0);
int number = js_tointeger(J, 1);
fz_page *page = NULL;
fz_try(ctx)
page = fz_load_page(ctx, doc, number);
fz_catch(ctx)
rethrow(J);
ffi_pushpage(J, page);
}
static void ffi_Document_needsPassword(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_document *doc = ffi_todocument(J, 0);
int b = 0;
fz_try(ctx)
b = fz_needs_password(ctx, doc);
fz_catch(ctx)
rethrow(J);
js_pushboolean(J, b);
}
static void ffi_Document_authenticatePassword(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_document *doc = ffi_todocument(J, 0);
const char *password = js_tostring(J, 1);
int b = 0;
fz_try(ctx)
b = fz_authenticate_password(ctx, doc, password);
fz_catch(ctx)
rethrow(J);
js_pushboolean(J, b);
}
static void ffi_Document_getMetaData(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_document *doc = ffi_todocument(J, 0);
const char *key = js_tostring(J, 1);
char info[256];
int found;
fz_try(ctx)
found = fz_lookup_metadata(ctx, doc, key, info, sizeof info);
fz_catch(ctx)
rethrow(J);
if (found)
js_pushstring(J, info);
else
js_pushundefined(J);
}
static void ffi_Document_isReflowable(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_document *doc = ffi_todocument(J, 0);
int is_reflowable = 0;
fz_try(ctx)
is_reflowable = fz_is_document_reflowable(ctx, doc);
fz_catch(ctx)
rethrow(J);
js_pushboolean(J, is_reflowable);
}
static void ffi_Document_layout(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_document *doc = ffi_todocument(J, 0);
float w = js_tonumber(J, 1);
float h = js_tonumber(J, 2);
float em = js_tonumber(J, 3);
fz_try(ctx)
fz_layout_document(ctx, doc, w, h, em);
fz_catch(ctx)
rethrow(J);
}
static void to_outline(js_State *J, fz_outline *outline)
{
int i = 0;
js_newarray(J);
while (outline) {
js_newobject(J);
if (outline->title)
js_pushstring(J, outline->title);
else
js_pushundefined(J);
js_setproperty(J, -2, "title");
if (outline->uri)
js_pushstring(J, outline->uri);
else
js_pushundefined(J);
js_setproperty(J, -2, "uri");
if (outline->page >= 0)
js_pushnumber(J, outline->page);
else
js_pushundefined(J);
js_setproperty(J, -2, "page");
if (outline->down) {
to_outline(J, outline->down);
js_setproperty(J, -2, "down");
}
js_setindex(J, -2, i++);
outline = outline->next;
}
}
static void ffi_Document_loadOutline(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_document *doc = ffi_todocument(J, 0);
fz_outline *outline = NULL;
fz_try(ctx)
outline = fz_load_outline(ctx, doc);
fz_catch(ctx)
rethrow(J);
to_outline(J, outline);
fz_drop_outline(ctx, outline);
}
static void ffi_Page_isPDF(js_State *J)
{
js_pushboolean(J, js_isuserdata(J, 0, "pdf_page"));
}
static void ffi_Page_bound(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_page *page = ffi_topage(J, 0);
fz_rect bounds;
fz_try(ctx)
bounds = fz_bound_page(ctx, page);
fz_catch(ctx)
rethrow(J);
ffi_pushrect(J, bounds);
}
static void ffi_Page_run(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_page *page = ffi_topage(J, 0);
fz_device *device = NULL;
fz_matrix ctm = ffi_tomatrix(J, 2);
int no_annots = js_isdefined(J, 3) ? js_toboolean(J, 3) : 0;
if (js_isuserdata(J, 1, "fz_device")) {
device = js_touserdata(J, 1, "fz_device");
fz_try(ctx)
if (no_annots)
fz_run_page_contents(ctx, page, device, ctm, NULL);
else
fz_run_page(ctx, page, device, ctm, NULL);
fz_catch(ctx)
rethrow(J);
} else {
device = new_js_device(ctx, J);
js_copy(J, 1); /* put the js device on the top so the callbacks know where to get it */
fz_try(ctx) {
if (no_annots)
fz_run_page_contents(ctx, page, device, ctm, NULL);
else
fz_run_page(ctx, page, device, ctm, NULL);
fz_close_device(ctx, device);
}
fz_always(ctx)
fz_drop_device(ctx, device);
fz_catch(ctx)
rethrow(J);
}
}
static void ffi_Page_toDisplayList(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_page *page = ffi_topage(J, 0);
int no_annots = js_isdefined(J, 1) ? js_toboolean(J, 1) : 0;
fz_display_list *list = NULL;
fz_try(ctx)
if (no_annots)
list = fz_new_display_list_from_page_contents(ctx, page);
else
list = fz_new_display_list_from_page(ctx, page);
fz_catch(ctx)
rethrow(J);
js_getregistry(J, "fz_display_list");
js_newuserdata(J, "fz_display_list", list, ffi_gc_fz_display_list);
}
static void ffi_Page_toPixmap(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_page *page = ffi_topage(J, 0);
fz_matrix ctm = ffi_tomatrix(J, 1);
fz_colorspace *colorspace = js_touserdata(J, 2, "fz_colorspace");
int alpha = js_toboolean(J, 3);
int no_annots = js_isdefined(J, 4) ? js_toboolean(J, 4) : 0;
fz_pixmap *pixmap = NULL;
fz_try(ctx)
if (no_annots)
pixmap = fz_new_pixmap_from_page_contents(ctx, page, ctm, colorspace, alpha);
else
pixmap = fz_new_pixmap_from_page(ctx, page, ctm, colorspace, alpha);
fz_catch(ctx)
rethrow(J);
js_getregistry(J, "fz_pixmap");
js_newuserdata(J, "fz_pixmap", pixmap, ffi_gc_fz_pixmap);
}
static void ffi_Page_toStructuredText(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_page *page = ffi_topage(J, 0);
const char *options = js_iscoercible(J, 1) ? js_tostring(J, 1) : NULL;
fz_stext_options so;
fz_stext_page *text = NULL;
fz_try(ctx) {
fz_parse_stext_options(ctx, &so, options);
text = fz_new_stext_page_from_page(ctx, page, &so);
}
fz_catch(ctx)
rethrow(J);
js_getregistry(J, "fz_stext_page");
js_newuserdata(J, "fz_stext_page", text, ffi_gc_fz_stext_page);
}
static void ffi_Page_search(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_page *page = ffi_topage(J, 0);
const char *needle = js_tostring(J, 1);
fz_quad hits[256];
int i, n = 0;
fz_try(ctx)
n = fz_search_page(ctx, page, needle, hits, nelem(hits));
fz_catch(ctx)
rethrow(J);
js_newarray(J);
for (i = 0; i < n; ++i) {
ffi_pushquad(J, hits[i]);
js_setindex(J, -2, i);
}
}
static void ffi_Page_getLinks(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_page *page = ffi_topage(J, 0);
fz_link *link, *links = NULL;
int i = 0;
js_newarray(J);
fz_try(ctx)
links = fz_load_links(ctx, page);
fz_catch(ctx)
rethrow(J);
js_newarray(J);
for (link = links; link; link = link->next) {
js_newobject(J);
ffi_pushrect(J, link->rect);
js_setproperty(J, -2, "bounds");
js_pushstring(J, link->uri);
js_setproperty(J, -2, "uri");
js_setindex(J, -2, i++);
}
fz_drop_link(ctx, links);
}
static void ffi_ColorSpace_getNumberOfComponents(js_State *J)
{
fz_colorspace *colorspace = js_touserdata(J, 0, "fz_colorspace");
fz_context *ctx = js_getcontext(J);
js_pushnumber(J, fz_colorspace_n(ctx, colorspace));
}
static void ffi_ColorSpace_toString(js_State *J)
{
fz_colorspace *colorspace = js_touserdata(J, 0, "fz_colorspace");
fz_context *ctx = js_getcontext(J);
js_pushstring(J, fz_colorspace_name(ctx, colorspace));
}
static void ffi_new_Pixmap(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_colorspace *colorspace = js_touserdata(J, 1, "fz_colorspace");
fz_irect bounds = ffi_toirect(J, 2);
int alpha = js_toboolean(J, 3);
fz_pixmap *pixmap = NULL;
fz_try(ctx)
pixmap = fz_new_pixmap_with_bbox(ctx, colorspace, bounds, 0, alpha);
fz_catch(ctx)
rethrow(J);
js_getregistry(J, "fz_pixmap");
js_newuserdata(J, "fz_pixmap", pixmap, ffi_gc_fz_pixmap);
}
static void ffi_Pixmap_saveAsPNG(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_pixmap *pixmap = js_touserdata(J, 0, "fz_pixmap");
const char *filename = js_tostring(J, 1);
fz_try(ctx)
fz_save_pixmap_as_png(ctx, pixmap, filename);
fz_catch(ctx)
rethrow(J);
}
static void ffi_Pixmap_bound(js_State *J)
{
fz_pixmap *pixmap = js_touserdata(J, 0, "fz_pixmap");
fz_rect bounds;
// fz_irect and fz_pixmap_bbox instead
bounds.x0 = pixmap->x;
bounds.y0 = pixmap->y;
bounds.x1 = pixmap->x + pixmap->w;
bounds.y1 = pixmap->y + pixmap->h;
ffi_pushrect(J, bounds);
}
static void ffi_Pixmap_clear(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_pixmap *pixmap = js_touserdata(J, 0, "fz_pixmap");
if (js_isdefined(J, 1)) {
int value = js_tonumber(J, 1);
fz_try(ctx)
fz_clear_pixmap_with_value(ctx, pixmap, value);
fz_catch(ctx)
rethrow(J);
} else {
fz_try(ctx)
fz_clear_pixmap(ctx, pixmap);
fz_catch(ctx)
rethrow(J);
}
}
static void ffi_Pixmap_getX(js_State *J)
{
fz_pixmap *pixmap = js_touserdata(J, 0, "fz_pixmap");
js_pushnumber(J, pixmap->x);
}
static void ffi_Pixmap_getY(js_State *J)
{
fz_pixmap *pixmap = js_touserdata(J, 0, "fz_pixmap");
js_pushnumber(J, pixmap->y);
}
static void ffi_Pixmap_getWidth(js_State *J)
{
fz_pixmap *pixmap = js_touserdata(J, 0, "fz_pixmap");
js_pushnumber(J, pixmap->w);
}
static void ffi_Pixmap_getHeight(js_State *J)
{
fz_pixmap *pixmap = js_touserdata(J, 0, "fz_pixmap");
js_pushnumber(J, pixmap->h);
}
static void ffi_Pixmap_getNumberOfComponents(js_State *J)
{
fz_pixmap *pixmap = js_touserdata(J, 0, "fz_pixmap");
js_pushnumber(J, pixmap->n);
}
static void ffi_Pixmap_getAlpha(js_State *J)
{
fz_pixmap *pixmap = js_touserdata(J, 0, "fz_pixmap");
js_pushnumber(J, pixmap->alpha);
}
static void ffi_Pixmap_getStride(js_State *J)
{
fz_pixmap *pixmap = js_touserdata(J, 0, "fz_pixmap");
js_pushnumber(J, pixmap->stride);
}
static void ffi_Pixmap_getSample(js_State *J)
{
fz_pixmap *pixmap = js_touserdata(J, 0, "fz_pixmap");
int x = js_tointeger(J, 1);
int y = js_tointeger(J, 2);
int k = js_tointeger(J, 3);
if (x < 0 || x >= pixmap->w) js_rangeerror(J, "X out of range");
if (y < 0 || y >= pixmap->h) js_rangeerror(J, "Y out of range");
if (k < 0 || k >= pixmap->n) js_rangeerror(J, "N out of range");
js_pushnumber(J, pixmap->samples[(x + y * pixmap->w) * pixmap->n + k]);
}
static void ffi_Pixmap_getXResolution(js_State *J)
{
fz_pixmap *pixmap = js_touserdata(J, 0, "fz_pixmap");
js_pushnumber(J, pixmap->xres);
}
static void ffi_Pixmap_getYResolution(js_State *J)
{
fz_pixmap *pixmap = js_touserdata(J, 0, "fz_pixmap");
js_pushnumber(J, pixmap->yres);
}
static void ffi_Pixmap_getColorSpace(js_State *J)
{
fz_pixmap *pixmap = js_touserdata(J, 0, "fz_pixmap");
ffi_pushcolorspace(J, pixmap->colorspace);
}
static void ffi_new_Image(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_image *image = NULL;
if (js_isuserdata(J, 1, "fz_pixmap")) {
fz_pixmap *pixmap = js_touserdata(J, 1, "fz_pixmap");
fz_try(ctx)
image = fz_new_image_from_pixmap(ctx, pixmap, NULL);
fz_catch(ctx)
rethrow(J);
} else {
const char *name = js_tostring(J, 1);
fz_try(ctx)
image = fz_new_image_from_file(ctx, name);
fz_catch(ctx)
rethrow(J);
}
ffi_pushimage_own(J, image);
}
static void ffi_Image_getWidth(js_State *J)
{
fz_image *image = js_touserdata(J, 0, "fz_image");
js_pushnumber(J, image->w);
}
static void ffi_Image_getHeight(js_State *J)
{
fz_image *image = js_touserdata(J, 0, "fz_image");
js_pushnumber(J, image->h);
}
static void ffi_Image_getXResolution(js_State *J)
{
fz_image *image = js_touserdata(J, 0, "fz_image");
js_pushnumber(J, image->xres);
}
static void ffi_Image_getYResolution(js_State *J)
{
fz_image *image = js_touserdata(J, 0, "fz_image");
js_pushnumber(J, image->yres);
}
static void ffi_Image_getNumberOfComponents(js_State *J)
{
fz_image *image = js_touserdata(J, 0, "fz_image");
js_pushnumber(J, image->n);
}
static void ffi_Image_getBitsPerComponent(js_State *J)
{
fz_image *image = js_touserdata(J, 0, "fz_image");
js_pushnumber(J, image->bpc);
}
static void ffi_Image_getInterpolate(js_State *J)
{
fz_image *image = js_touserdata(J, 0, "fz_image");
js_pushboolean(J, image->interpolate);
}
static void ffi_Image_getImageMask(js_State *J)
{
fz_image *image = js_touserdata(J, 0, "fz_image");
js_pushboolean(J, image->imagemask);
}
static void ffi_Image_getMask(js_State *J)
{
fz_image *image = js_touserdata(J, 0, "fz_image");
if (image->mask)
ffi_pushimage(J, image->mask);
else
js_pushnull(J);
}
static void ffi_Image_getColorSpace(js_State *J)
{
fz_image *image = js_touserdata(J, 0, "fz_image");
ffi_pushcolorspace(J, image->colorspace);
}
static void ffi_Image_toPixmap(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_image *image = js_touserdata(J, 0, "fz_image");
fz_matrix matrix_, *matrix = NULL;
fz_pixmap *pixmap = NULL;
if (js_isnumber(J, 1) && js_isnumber(J, 2)) {
matrix_ = fz_scale(js_tonumber(J, 1), js_tonumber(J, 2));
matrix = &matrix_;
}
fz_try(ctx)
pixmap = fz_get_pixmap_from_image(ctx, image, NULL, matrix, NULL, NULL);
fz_catch(ctx)
rethrow(J);
js_getregistry(J, "fz_pixmap");
js_newuserdata(J, "fz_pixmap", pixmap, ffi_gc_fz_pixmap);
}
static void ffi_Shade_bound(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_shade *shade = js_touserdata(J, 0, "fz_shade");
fz_matrix ctm = ffi_tomatrix(J, 1);
fz_rect bounds;
fz_try(ctx)
bounds = fz_bound_shade(ctx, shade, ctm);
fz_catch(ctx)
rethrow(J);
ffi_pushrect(J, bounds);
}
static void ffi_new_Font(js_State *J)
{
fz_context *ctx = js_getcontext(J);
const char *name = js_tostring(J, 1);
int index = js_isnumber(J, 2) ? js_tonumber(J, 2) : 0;
const unsigned char *data;
int size;
fz_font *font = NULL;
fz_try(ctx) {
data = fz_lookup_base14_font(ctx, name, &size);
if (!data)
data = fz_lookup_cjk_font_by_language(ctx, name, &size, &index);
if (data)
font = fz_new_font_from_memory(ctx, name, data, size, index, 0);
else
font = fz_new_font_from_file(ctx, name, name, index, 0);
}
fz_catch(ctx)
rethrow(J);
js_getregistry(J, "fz_font");
js_newuserdata(J, "fz_font", font, ffi_gc_fz_font);
}
static void ffi_Font_getName(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_font *font = js_touserdata(J, 0, "fz_font");
js_pushstring(J, fz_font_name(ctx, font));
}
static void ffi_Font_encodeCharacter(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_font *font = js_touserdata(J, 0, "fz_font");
int unicode = js_tonumber(J, 1);
int glyph = 0;
fz_try(ctx)
glyph = fz_encode_character(ctx, font, unicode);
fz_catch(ctx)
rethrow(J);
js_pushnumber(J, glyph);
}
static void ffi_Font_advanceGlyph(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_font *font = js_touserdata(J, 0, "fz_font");
int glyph = js_tonumber(J, 1);
int wmode = js_isdefined(J, 2) ? js_toboolean(J, 2) : 0;
float advance = 0;
fz_try(ctx)
advance = fz_advance_glyph(ctx, font, glyph, wmode);
fz_catch(ctx)
rethrow(J);
js_pushnumber(J, advance);
}
static void ffi_new_Text(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_text *text = NULL;
fz_try(ctx)
text = fz_new_text(ctx);
fz_catch(ctx)
rethrow(J);
js_getregistry(J, "fz_text");
js_newuserdata(J, "fz_text", text, ffi_gc_fz_text);
}
static void ffi_Text_walk(js_State *J)
{
fz_text *text = js_touserdata(J, 0, "fz_text");
fz_text_span *span;
fz_matrix trm;
int i;
js_getproperty(J, 1, "showGlyph");
for (span = text->head; span; span = span->next) {
ffi_pushfont(J, span->font);
trm = span->trm;
for (i = 0; i < span->len; ++i) {
trm.e = span->items[i].x;
trm.f = span->items[i].y;
js_copy(J, -2); /* showGlyph function */
js_copy(J, 1); /* object for this binding */
js_copy(J, -3); /* font */
ffi_pushmatrix(J, trm);
js_pushnumber(J, span->items[i].gid);
js_pushnumber(J, span->items[i].ucs);
js_pushnumber(J, span->wmode);
js_pushnumber(J, span->bidi_level);
js_call(J, 6);
js_pop(J, 1);
}
js_pop(J, 1); /* pop font object */
}
js_pop(J, 1); /* pop showGlyph function */
}
static void ffi_Text_showGlyph(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_text *text = js_touserdata(J, 0, "fz_text");
fz_font *font = js_touserdata(J, 1, "fz_font");
fz_matrix trm = ffi_tomatrix(J, 2);
int glyph = js_tointeger(J, 3);
int unicode = js_tointeger(J, 4);
int wmode = js_isdefined(J, 5) ? js_toboolean(J, 5) : 0;
fz_try(ctx)
fz_show_glyph(ctx, text, font, trm, glyph, unicode, wmode, 0, FZ_BIDI_NEUTRAL, FZ_LANG_UNSET);
fz_catch(ctx)
rethrow(J);
}
static void ffi_Text_showString(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_text *text = js_touserdata(J, 0, "fz_text");
fz_font *font = js_touserdata(J, 1, "fz_font");
fz_matrix trm = ffi_tomatrix(J, 2);
const char *s = js_tostring(J, 3);
int wmode = js_isdefined(J, 4) ? js_toboolean(J, 4) : 0;
fz_try(ctx)
trm = fz_show_string(ctx, text, font, trm, s, wmode, 0, FZ_BIDI_NEUTRAL, FZ_LANG_UNSET);
fz_catch(ctx)
rethrow(J);
/* update matrix with new pen position */
js_pushnumber(J, trm.e);
js_setindex(J, 2, 4);
js_pushnumber(J, trm.f);
js_setindex(J, 2, 5);
}
static void ffi_new_Path(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_path *path = NULL;
fz_try(ctx)
path = fz_new_path(ctx);
fz_catch(ctx)
rethrow(J);
js_getregistry(J, "fz_path");
js_newuserdata(J, "fz_path", path, ffi_gc_fz_path);
}
static void ffi_Path_walk_moveTo(fz_context *ctx, void *arg, float x, float y)
{
js_State *J = arg;
if (js_try(J))
rethrow_as_fz(J);
if (js_hasproperty(J, 1, "moveTo")) {
js_copy(J, 1);
js_pushnumber(J, x);
js_pushnumber(J, y);
js_call(J, 2);
js_pop(J, 1);
}
js_endtry(J);
}
static void ffi_Path_walk_lineTo(fz_context *ctx, void *arg, float x, float y)
{
js_State *J = arg;
if (js_try(J))
rethrow_as_fz(J);
if (js_hasproperty(J, 1, "lineTo")) {
js_copy(J, 1);
js_pushnumber(J, x);
js_pushnumber(J, y);
js_call(J, 2);
js_pop(J, 1);
}
js_endtry(J);
}
static void ffi_Path_walk_curveTo(fz_context *ctx, void *arg,
float x1, float y1, float x2, float y2, float x3, float y3)
{
js_State *J = arg;
if (js_try(J))
rethrow_as_fz(J);
if (js_hasproperty(J, 1, "curveTo")) {
js_copy(J, 1);
js_pushnumber(J, x1);
js_pushnumber(J, y1);
js_pushnumber(J, x2);
js_pushnumber(J, y2);
js_pushnumber(J, x3);
js_pushnumber(J, y3);
js_call(J, 6);
js_pop(J, 1);
}
js_endtry(J);
}
static void ffi_Path_walk_closePath(fz_context *ctx, void *arg)
{
js_State *J = arg;
if (js_try(J))
rethrow_as_fz(J);
if (js_hasproperty(J, 1, "closePath")) {
js_copy(J, 1);
js_call(J, 0);
js_pop(J, 1);
}
js_endtry(J);
}
static void ffi_Path_walk(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_path *path = js_touserdata(J, 0, "fz_path");
fz_path_walker walker = {
ffi_Path_walk_moveTo,
ffi_Path_walk_lineTo,
ffi_Path_walk_curveTo,
ffi_Path_walk_closePath,
};
fz_try(ctx)
fz_walk_path(ctx, path, &walker, J);
fz_catch(ctx)
rethrow(J);
}
static void ffi_Path_moveTo(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_path *path = js_touserdata(J, 0, "fz_path");
float x = js_tonumber(J, 1);
float y = js_tonumber(J, 2);
fz_try(ctx)
fz_moveto(ctx, path, x, y);
fz_catch(ctx)
rethrow(J);
}
static void ffi_Path_lineTo(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_path *path = js_touserdata(J, 0, "fz_path");
float x = js_tonumber(J, 1);
float y = js_tonumber(J, 2);
fz_try(ctx)
fz_lineto(ctx, path, x, y);
fz_catch(ctx)
rethrow(J);
}
static void ffi_Path_curveTo(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_path *path = js_touserdata(J, 0, "fz_path");
float x1 = js_tonumber(J, 1);
float y1 = js_tonumber(J, 2);
float x2 = js_tonumber(J, 3);
float y2 = js_tonumber(J, 4);
float x3 = js_tonumber(J, 5);
float y3 = js_tonumber(J, 6);
fz_try(ctx)
fz_curveto(ctx, path, x1, y1, x2, y2, x3, y3);
fz_catch(ctx)
rethrow(J);
}
static void ffi_Path_curveToV(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_path *path = js_touserdata(J, 0, "fz_path");
float cx = js_tonumber(J, 1);
float cy = js_tonumber(J, 2);
float ex = js_tonumber(J, 3);
float ey = js_tonumber(J, 4);
fz_try(ctx)
fz_curvetov(ctx, path, cx, cy, ex, ey);
fz_catch(ctx)
rethrow(J);
}
static void ffi_Path_curveToY(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_path *path = js_touserdata(J, 0, "fz_path");
float cx = js_tonumber(J, 1);
float cy = js_tonumber(J, 2);
float ex = js_tonumber(J, 3);
float ey = js_tonumber(J, 4);
fz_try(ctx)
fz_curvetoy(ctx, path, cx, cy, ex, ey);
fz_catch(ctx)
rethrow(J);
}
static void ffi_Path_closePath(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_path *path = js_touserdata(J, 0, "fz_path");
fz_try(ctx)
fz_closepath(ctx, path);
fz_catch(ctx)
rethrow(J);
}
static void ffi_Path_rect(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_path *path = js_touserdata(J, 0, "fz_path");
float x1 = js_tonumber(J, 1);
float y1 = js_tonumber(J, 2);
float x2 = js_tonumber(J, 3);
float y2 = js_tonumber(J, 4);
fz_try(ctx)
fz_rectto(ctx, path, x1, y1, x2, y2);
fz_catch(ctx)
rethrow(J);
}
static void ffi_Path_bound(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_path *path = js_touserdata(J, 0, "fz_path");
fz_stroke_state stroke = ffi_tostroke(J, 1);
fz_matrix ctm = ffi_tomatrix(J, 2);
fz_rect bounds;
fz_try(ctx)
bounds = fz_bound_path(ctx, path, &stroke, ctm);
fz_catch(ctx)
rethrow(J);
ffi_pushrect(J, bounds);
}
static void ffi_Path_transform(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_path *path = js_touserdata(J, 0, "fz_path");
fz_matrix ctm = ffi_tomatrix(J, 1);
fz_try(ctx)
fz_transform_path(ctx, path, ctm);
fz_catch(ctx)
rethrow(J);
}
static void ffi_new_DisplayList(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_rect mediabox = js_iscoercible(J, 1) ? ffi_torect(J, 1) : fz_empty_rect;
fz_display_list *list = NULL;
fz_try(ctx)
list = fz_new_display_list(ctx, mediabox);
fz_catch(ctx)
rethrow(J);
js_getregistry(J, "fz_display_list");
js_newuserdata(J, "fz_display_list", list, ffi_gc_fz_display_list);
}
static void ffi_DisplayList_run(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_display_list *list = js_touserdata(J, 0, "fz_display_list");
fz_device *device = NULL;
fz_matrix ctm = ffi_tomatrix(J, 2);
if (js_isuserdata(J, 1, "fz_device")) {
device = js_touserdata(J, 1, "fz_device");
fz_try(ctx)
fz_run_display_list(ctx, list, device, ctm, fz_infinite_rect, NULL);
fz_catch(ctx)
rethrow(J);
} else {
device = new_js_device(ctx, J);
js_copy(J, 1);
fz_try(ctx) {
fz_run_display_list(ctx, list, device, ctm, fz_infinite_rect, NULL);
fz_close_device(ctx, device);
}
fz_always(ctx)
fz_drop_device(ctx, device);
fz_catch(ctx)
rethrow(J);
}
}
static void ffi_DisplayList_toPixmap(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_display_list *list = js_touserdata(J, 0, "fz_display_list");
fz_matrix ctm = ffi_tomatrix(J, 1);
fz_colorspace *colorspace = js_touserdata(J, 2, "fz_colorspace");
int alpha = js_isdefined(J, 3) ? js_toboolean(J, 3) : 0;
fz_pixmap *pixmap = NULL;
fz_try(ctx)
pixmap = fz_new_pixmap_from_display_list(ctx, list, ctm, colorspace, alpha);
fz_catch(ctx)
rethrow(J);
js_getregistry(J, "fz_pixmap");
js_newuserdata(J, "fz_pixmap", pixmap, ffi_gc_fz_pixmap);
}
static void ffi_DisplayList_toStructuredText(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_display_list *list = js_touserdata(J, 0, "fz_display_list");
const char *options = js_iscoercible(J, 1) ? js_tostring(J, 1) : NULL;
fz_stext_options so;
fz_stext_page *text = NULL;
fz_try(ctx) {
fz_parse_stext_options(ctx, &so, options);
text = fz_new_stext_page_from_display_list(ctx, list, &so);
}
fz_catch(ctx)
rethrow(J);
js_getregistry(J, "fz_stext_page");
js_newuserdata(J, "fz_stext_page", text, ffi_gc_fz_stext_page);
}
static void ffi_DisplayList_search(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_display_list *list = js_touserdata(J, 0, "fz_display_list");
const char *needle = js_tostring(J, 1);
fz_quad hits[256];
int i, n = 0;
fz_try(ctx)
n = fz_search_display_list(ctx, list, needle, hits, nelem(hits));
fz_catch(ctx)
rethrow(J);
js_newarray(J);
for (i = 0; i < n; ++i) {
ffi_pushquad(J, hits[i]);
js_setindex(J, -2, i);
}
}
static void ffi_StructuredText_search(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_stext_page *text = js_touserdata(J, 0, "fz_stext_page");
const char *needle = js_tostring(J, 1);
fz_quad hits[256];
int i, n = 0;
fz_try(ctx)
n = fz_search_stext_page(ctx, text, needle, hits, nelem(hits));
fz_catch(ctx)
rethrow(J);
js_newarray(J);
for (i = 0; i < n; ++i) {
ffi_pushquad(J, hits[i]);
js_setindex(J, -2, i);
}
}
static void ffi_StructuredText_highlight(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_stext_page *text = js_touserdata(J, 0, "fz_stext_page");
fz_point a = ffi_topoint(J, 1);
fz_point b = ffi_topoint(J, 2);
fz_quad hits[256];
int i, n = 0;
fz_try(ctx)
n = fz_highlight_selection(ctx, text, a, b, hits, nelem(hits));
fz_catch(ctx)
rethrow(J);
js_newarray(J);
for (i = 0; i < n; ++i) {
ffi_pushquad(J, hits[i]);
js_setindex(J, -2, i);
}
}
static void ffi_StructuredText_copy(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_stext_page *text = js_touserdata(J, 0, "fz_stext_page");
fz_point a = ffi_topoint(J, 1);
fz_point b = ffi_topoint(J, 2);
char *s = NULL;
fz_try(ctx)
s = fz_copy_selection(ctx, text, a, b, 0);
fz_catch(ctx)
rethrow(J);
js_pushstring(J, s);
fz_try(ctx)
fz_free(ctx, s);
fz_catch(ctx)
rethrow(J);
}
static void ffi_new_DisplayListDevice(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_display_list *list = js_touserdata(J, 0, "fz_display_list");
fz_device *device = NULL;
fz_try(ctx)
device = fz_new_list_device(ctx, list);
fz_catch(ctx)
rethrow(J);
js_getregistry(J, "fz_device");
js_newuserdata(J, "fz_device", device, ffi_gc_fz_device);
}
static void ffi_new_DrawDevice(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_matrix transform = ffi_tomatrix(J, 1);
fz_pixmap *pixmap = js_touserdata(J, 2, "fz_pixmap");
fz_device *device = NULL;
fz_try(ctx)
device = fz_new_draw_device(ctx, transform, pixmap);
fz_catch(ctx)
rethrow(J);
js_getregistry(J, "fz_device");
js_newuserdata(J, "fz_device", device, ffi_gc_fz_device);
}
static void ffi_new_DocumentWriter(js_State *J)
{
fz_context *ctx = js_getcontext(J);
const char *filename = js_tostring(J, 1);
const char *format = js_iscoercible(J, 2) ? js_tostring(J, 2) : NULL;
const char *options = js_iscoercible(J, 3) ? js_tostring(J, 3) : NULL;
fz_document_writer *wri = NULL;
fz_try(ctx)
wri = fz_new_document_writer(ctx, filename, format, options);
fz_catch(ctx)
rethrow(J);
js_getregistry(J, "fz_document_writer");
js_newuserdata(J, "fz_document_writer", wri, ffi_gc_fz_document_writer);
}
static void ffi_DocumentWriter_beginPage(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_document_writer *wri = js_touserdata(J, 0, "fz_document_writer");
fz_rect mediabox = ffi_torect(J, 1);
fz_device *device = NULL;
fz_try(ctx)
device = fz_begin_page(ctx, wri, mediabox);
fz_catch(ctx)
rethrow(J);
js_getregistry(J, "fz_device");
js_newuserdata(J, "fz_device", fz_keep_device(ctx, device), ffi_gc_fz_device);
}
static void ffi_DocumentWriter_endPage(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_document_writer *wri = js_touserdata(J, 0, "fz_document_writer");
fz_try(ctx)
fz_end_page(ctx, wri);
fz_catch(ctx)
rethrow(J);
}
static void ffi_DocumentWriter_close(js_State *J)
{
fz_context *ctx = js_getcontext(J);
fz_document_writer *wri = js_touserdata(J, 0, "fz_document_writer");
fz_try(ctx)
fz_close_document_writer(ctx, wri);
fz_catch(ctx)
rethrow(J);
}
/* PDF specifics */
#if FZ_ENABLE_PDF
static pdf_obj *ffi_toobj(js_State *J, pdf_document *pdf, int idx)
{
fz_context *ctx = js_getcontext(J);
pdf_obj *obj = NULL;
/* make sure index is absolute */
if (idx < 0)
idx += js_gettop(J);
if (js_isuserdata(J, idx, "pdf_obj"))
return pdf_keep_obj(ctx, js_touserdata(J, idx, "pdf_obj"));
if (js_isnumber(J, idx)) {
float f = js_tonumber(J, idx);
fz_try(ctx)
if (f == (int)f)
obj = pdf_new_int(ctx, f);
else
obj = pdf_new_real(ctx, f);
fz_catch(ctx)
rethrow(J);
return obj;
}
if (js_isstring(J, idx)) {
const char *s = js_tostring(J, idx);
fz_try(ctx)
if (s[0] == '(' && s[1] != 0)
obj = pdf_new_string(ctx, s+1, strlen(s)-2);
else
obj = pdf_new_name(ctx, s);
fz_catch(ctx)
rethrow(J);
return obj;
}
if (js_isboolean(J, idx)) {
return js_toboolean(J, idx) ? PDF_TRUE : PDF_FALSE;
}
if (js_isnull(J, idx)) {
return PDF_NULL;
}
if (js_isarray(J, idx)) {
int i, n = js_getlength(J, idx);
pdf_obj *val;
fz_try(ctx)
obj = pdf_new_array(ctx, pdf, n);
fz_catch(ctx)
rethrow(J);
if (js_try(J)) {
pdf_drop_obj(ctx, obj);
js_throw(J);
}
for (i = 0; i < n; ++i) {
js_getindex(J, idx, i);
val = ffi_toobj(J, pdf, -1);
fz_try(ctx)
pdf_array_push_drop(ctx, obj, val);
fz_catch(ctx)
rethrow(J);
js_pop(J, 1);
}
js_endtry(J);
return obj;
}
if (js_isobject(J, idx)) {
const char *key;
pdf_obj *val;
fz_try(ctx)
obj = pdf_new_dict(ctx, pdf, 0);
fz_catch(ctx)
rethrow(J);
if (js_try(J)) {
pdf_drop_obj(ctx, obj);
js_throw(J);
}
js_pushiterator(J, idx, 1);
while ((key = js_nextiterator(J, -1))) {
js_getproperty(J, idx, key);
val = ffi_toobj(J, pdf, -1);
fz_try(ctx)
pdf_dict_puts_drop(ctx, obj, key, val);
fz_catch(ctx)
rethrow(J);
js_pop(J, 1);
}
js_pop(J, 1);
js_endtry(J);
return obj;
}
js_error(J, "cannot convert JS type to PDF");
}
static void ffi_pushobj(js_State *J, pdf_obj *obj);
static int ffi_pdf_obj_has(js_State *J, void *obj, const char *key)
{
fz_context *ctx = js_getcontext(J);
pdf_obj *val = NULL;
int idx, len = 0;
if (!strcmp(key, "length")) {
fz_try(ctx)
len = pdf_array_len(ctx, obj);
fz_catch(ctx)
rethrow(J);
js_pushnumber(J, len);
return 1;
}
if (is_number(key, &idx)) {
fz_try(ctx)
val = pdf_array_get(ctx, obj, idx);
fz_catch(ctx)
rethrow(J);
} else {
fz_try(ctx)
val = pdf_dict_gets(ctx, obj, key);
fz_catch(ctx)
rethrow(J);
}
if (val) {
ffi_pushobj(J, pdf_keep_obj(ctx, val));
return 1;
}
return 0;
}
static int ffi_pdf_obj_put(js_State *J, void *obj, const char *key)
{
fz_context *ctx = js_getcontext(J);
pdf_document *pdf = NULL;
pdf_obj *val;
int idx;
fz_try(ctx)
pdf = pdf_get_bound_document(ctx, obj);
fz_catch(ctx)
rethrow(J);
val = ffi_toobj(J, pdf, -1);
if (is_number(key, &idx)) {
fz_try(ctx)
pdf_array_put(ctx, obj, idx, val);
fz_always(ctx)
pdf_drop_obj(ctx, val);
fz_catch(ctx)
rethrow(J);
} else {
fz_try(ctx)
pdf_dict_puts(ctx, obj, key, val);
fz_always(ctx)
pdf_drop_obj(ctx, val);
fz_catch(ctx)
rethrow(J);
}
return 1;
}
static int ffi_pdf_obj_delete(js_State *J, void *obj, const char *key)
{
fz_context *ctx = js_getcontext(J);
int idx;
if (is_number(key, &idx)) {
fz_try(ctx)
pdf_array_delete(ctx, obj, idx);
fz_catch(ctx)
rethrow(J);
} else {
fz_try(ctx)
pdf_dict_dels(ctx, obj, key);
fz_catch(ctx)
rethrow(J);
}
return 1;
}
static void ffi_pushobj(js_State *J, pdf_obj *obj)
{
if (obj) {
js_getregistry(J, "pdf_obj");
js_newuserdatax(J, "pdf_obj", obj,
ffi_pdf_obj_has, ffi_pdf_obj_put, ffi_pdf_obj_delete,
ffi_gc_pdf_obj);
} else {
js_pushnull(J);
}
}
static void ffi_new_PDFDocument(js_State *J)
{
fz_context *ctx = js_getcontext(J);
const char *filename = js_iscoercible(J, 1) ? js_tostring(J, 1) : NULL;
pdf_document *pdf = NULL;
fz_try(ctx)
if (filename)
pdf = pdf_open_document(ctx, filename);
else
pdf = pdf_create_document(ctx);
fz_catch(ctx)
rethrow(J);
js_getregistry(J, "pdf_document");
js_newuserdata(J, "pdf_document", pdf, ffi_gc_pdf_document);
}
static void ffi_PDFDocument_getTrailer(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_document *pdf = js_touserdata(J, 0, "pdf_document");
pdf_obj *trailer = NULL;
fz_try(ctx)
trailer = pdf_trailer(ctx, pdf);
fz_catch(ctx)
rethrow(J);
ffi_pushobj(J, pdf_keep_obj(ctx, trailer));
}
static void ffi_PDFDocument_countObjects(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_document *pdf = js_touserdata(J, 0, "pdf_document");
int count = 0;
fz_try(ctx)
count = pdf_xref_len(ctx, pdf);
fz_catch(ctx)
rethrow(J);
js_pushnumber(J, count);
}
static void ffi_PDFDocument_createObject(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_document *pdf = js_touserdata(J, 0, "pdf_document");
pdf_obj *ind = NULL;
fz_try(ctx)
ind = pdf_new_indirect(ctx, pdf, pdf_create_object(ctx, pdf), 0);
fz_catch(ctx)
rethrow(J);
ffi_pushobj(J, ind);
}
static void ffi_PDFDocument_deleteObject(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_document *pdf = js_touserdata(J, 0, "pdf_document");
pdf_obj *ind = js_isuserdata(J, 1, "pdf_obj") ? js_touserdata(J, 1, "pdf_obj") : NULL;
int num = ind ? pdf_to_num(ctx, ind) : js_tonumber(J, 1);
fz_try(ctx)
pdf_delete_object(ctx, pdf, num);
fz_catch(ctx)
rethrow(J);
}
static void ffi_PDFDocument_addObject(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_document *pdf = js_touserdata(J, 0, "pdf_document");
pdf_obj *obj = ffi_toobj(J, pdf, 1);
pdf_obj *ind = NULL;
fz_try(ctx)
ind = pdf_add_object_drop(ctx, pdf, obj);
fz_catch(ctx)
rethrow(J);
ffi_pushobj(J, ind);
}
static void ffi_PDFDocument_addStream_imp(js_State *J, int compressed)
{
fz_context *ctx = js_getcontext(J);
pdf_document *pdf = js_touserdata(J, 0, "pdf_document");
fz_buffer *buf = ffi_tobuffer(J, 1); /* FIXME: leak if ffi_toobj throws */
pdf_obj *obj = js_iscoercible(J, 2) ? ffi_toobj(J, pdf, 2) : NULL;
pdf_obj *ind = NULL;
fz_try(ctx)
ind = pdf_add_stream(ctx, pdf, buf, obj, compressed);
fz_always(ctx) {
fz_drop_buffer(ctx, buf);
pdf_drop_obj(ctx, obj);
} fz_catch(ctx)
rethrow(J);
ffi_pushobj(J, ind);
}
static void ffi_PDFDocument_addStream(js_State *J)
{
ffi_PDFDocument_addStream_imp(J, 0);
}
static void ffi_PDFDocument_addRawStream(js_State *J)
{
ffi_PDFDocument_addStream_imp(J, 1);
}
static void ffi_PDFDocument_addImage(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_document *pdf = js_touserdata(J, 0, "pdf_document");
fz_image *image = js_touserdata(J, 1, "fz_image");
pdf_obj *ind = NULL;
fz_try(ctx)
ind = pdf_add_image(ctx, pdf, image);
fz_catch(ctx)
rethrow(J);
ffi_pushobj(J, ind);
}
static void ffi_PDFDocument_loadImage(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_document *pdf = js_touserdata(J, 0, "pdf_document");
pdf_obj *obj = ffi_toobj(J, pdf, 1);
fz_image *img = NULL;
fz_try(ctx)
img = pdf_load_image(ctx, pdf, obj);
fz_catch(ctx)
rethrow(J);
ffi_pushimage_own(J, img);
}
static void ffi_PDFDocument_addSimpleFont(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_document *pdf = js_touserdata(J, 0, "pdf_document");
fz_font *font = js_touserdata(J, 1, "fz_font");
const char *encname = js_tostring(J, 2);
pdf_obj *ind = NULL;
int enc = PDF_SIMPLE_ENCODING_LATIN;
if (!strcmp(encname, "Latin") || !strcmp(encname, "Latn"))
enc = PDF_SIMPLE_ENCODING_LATIN;
else if (!strcmp(encname, "Greek") || !strcmp(encname, "Grek"))
enc = PDF_SIMPLE_ENCODING_GREEK;
else if (!strcmp(encname, "Cyrillic") || !strcmp(encname, "Cyrl"))
enc = PDF_SIMPLE_ENCODING_CYRILLIC;
fz_try(ctx)
ind = pdf_add_simple_font(ctx, pdf, font, enc);
fz_catch(ctx)
rethrow(J);
ffi_pushobj(J, ind);
}
static void ffi_PDFDocument_addCJKFont(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_document *pdf = js_touserdata(J, 0, "pdf_document");
fz_font *font = js_touserdata(J, 1, "fz_font");
const char *lang = js_tostring(J, 2);
const char *wm = js_tostring(J, 3);
const char *ss = js_tostring(J, 4);
int ordering;
int wmode = 0;
int serif = 1;
pdf_obj *ind = NULL;
ordering = fz_lookup_cjk_ordering_by_language(lang);
if (!strcmp(wm, "V"))
wmode = 1;
if (!strcmp(ss, "sans") || !strcmp(ss, "sans-serif"))
serif = 0;
fz_try(ctx)
ind = pdf_add_cjk_font(ctx, pdf, font, ordering, wmode, serif);
fz_catch(ctx)
rethrow(J);
ffi_pushobj(J, ind);
}
static void ffi_PDFDocument_addFont(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_document *pdf = js_touserdata(J, 0, "pdf_document");
fz_font *font = js_touserdata(J, 1, "fz_font");
pdf_obj *ind = NULL;
fz_try(ctx)
ind = pdf_add_cid_font(ctx, pdf, font);
fz_catch(ctx)
rethrow(J);
ffi_pushobj(J, ind);
}
static void ffi_PDFDocument_addPage(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_document *pdf = js_touserdata(J, 0, "pdf_document");
fz_rect mediabox = ffi_torect(J, 1);
int rotate = js_tonumber(J, 2);
pdf_obj *resources = ffi_toobj(J, pdf, 3); /* FIXME: leak if ffi_tobuffer throws */
fz_buffer *contents = ffi_tobuffer(J, 4);
pdf_obj *ind = NULL;
fz_try(ctx)
ind = pdf_add_page(ctx, pdf, mediabox, rotate, resources, contents);
fz_always(ctx) {
fz_drop_buffer(ctx, contents);
pdf_drop_obj(ctx, resources);
} fz_catch(ctx)
rethrow(J);
ffi_pushobj(J, ind);
}
static void ffi_PDFDocument_insertPage(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_document *pdf = js_touserdata(J, 0, "pdf_document");
int at = js_tonumber(J, 1);
pdf_obj *obj = ffi_toobj(J, pdf, 2);
fz_try(ctx)
pdf_insert_page(ctx, pdf, at, obj);
fz_always(ctx)
pdf_drop_obj(ctx, obj);
fz_catch(ctx)
rethrow(J);
}
static void ffi_PDFDocument_deletePage(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_document *pdf = js_touserdata(J, 0, "pdf_document");
int at = js_tonumber(J, 1);
fz_try(ctx)
pdf_delete_page(ctx, pdf, at);
fz_catch(ctx)
rethrow(J);
}
static void ffi_PDFDocument_countPages(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_document *pdf = js_touserdata(J, 0, "pdf_document");
int count = 0;
fz_try(ctx)
count = pdf_count_pages(ctx, pdf);
fz_catch(ctx)
rethrow(J);
js_pushnumber(J, count);
}
static void ffi_PDFDocument_findPage(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_document *pdf = js_touserdata(J, 0, "pdf_document");
int at = js_tonumber(J, 1);
pdf_obj *obj = NULL;
fz_try(ctx)
obj = pdf_lookup_page_obj(ctx, pdf, at);
fz_catch(ctx)
rethrow(J);
ffi_pushobj(J, pdf_keep_obj(ctx, obj));
}
static void ffi_PDFDocument_save(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_document *pdf = js_touserdata(J, 0, "pdf_document");
const char *filename = js_tostring(J, 1);
const char *options = js_iscoercible(J, 2) ? js_tostring(J, 2) : NULL;
pdf_write_options pwo;
fz_try(ctx) {
pdf_parse_write_options(ctx, &pwo, options);
pdf_save_document(ctx, pdf, filename, &pwo);
} fz_catch(ctx)
rethrow(J);
}
static void ffi_PDFDocument_newNull(js_State *J)
{
ffi_pushobj(J, PDF_NULL);
}
static void ffi_PDFDocument_newBoolean(js_State *J)
{
int val = js_toboolean(J, 1);
ffi_pushobj(J, val ? PDF_TRUE : PDF_FALSE);
}
static void ffi_PDFDocument_newInteger(js_State *J)
{
fz_context *ctx = js_getcontext(J);
int val = js_tointeger(J, 1);
pdf_obj *obj = NULL;
fz_try(ctx)
obj = pdf_new_int(ctx, val);
fz_catch(ctx)
rethrow(J);
ffi_pushobj(J, obj);
}
static void ffi_PDFDocument_newReal(js_State *J)
{
fz_context *ctx = js_getcontext(J);
float val = js_tonumber(J, 1);
pdf_obj *obj = NULL;
fz_try(ctx)
obj = pdf_new_real(ctx, val);
fz_catch(ctx)
rethrow(J);
ffi_pushobj(J, obj);
}
static void ffi_PDFDocument_newString(js_State *J)
{
fz_context *ctx = js_getcontext(J);
const char *val = js_tostring(J, 1);
pdf_obj *obj = NULL;
fz_try(ctx)
obj = pdf_new_text_string(ctx, val);
fz_catch(ctx)
rethrow(J);
ffi_pushobj(J, obj);
}
static void ffi_PDFDocument_newByteString(js_State *J)
{
fz_context *ctx = js_getcontext(J);
int n, i;
char *buf;
pdf_obj *obj = NULL;
n = js_getlength(J, 1);
fz_try(ctx)
buf = fz_malloc(ctx, n);
fz_catch(ctx)
rethrow(J);
if (js_try(J)) {
fz_free(ctx, buf);
js_throw(J);
}
for (i = 0; i < n; ++i) {
js_getindex(J, 1, i);
buf[i] = js_tonumber(J, -1);
js_pop(J, 1);
}
js_endtry(J);
fz_try(ctx)
obj = pdf_new_string(ctx, buf, n);
fz_always(ctx)
fz_free(ctx, buf);
fz_catch(ctx)
rethrow(J);
ffi_pushobj(J, obj);
}
static void ffi_PDFDocument_newName(js_State *J)
{
fz_context *ctx = js_getcontext(J);
const char *val = js_tostring(J, 1);
pdf_obj *obj = NULL;
fz_try(ctx)
obj = pdf_new_name(ctx, val);
fz_catch(ctx)
rethrow(J);
ffi_pushobj(J, obj);
}
static void ffi_PDFDocument_newIndirect(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_document *pdf = js_touserdata(J, 0, "pdf_document");
int num = js_tointeger(J, 1);
int gen = js_tointeger(J, 2);
pdf_obj *obj = NULL;
fz_try(ctx)
obj = pdf_new_indirect(ctx, pdf, num, gen);
fz_catch(ctx)
rethrow(J);
ffi_pushobj(J, obj);
}
static void ffi_PDFDocument_newArray(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_document *pdf = js_touserdata(J, 0, "pdf_document");
pdf_obj *obj = NULL;
fz_try(ctx)
obj = pdf_new_array(ctx, pdf, 0);
fz_catch(ctx)
rethrow(J);
ffi_pushobj(J, obj);
}
static void ffi_PDFDocument_newDictionary(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_document *pdf = js_touserdata(J, 0, "pdf_document");
pdf_obj *obj = NULL;
fz_try(ctx)
obj = pdf_new_dict(ctx, pdf, 0);
fz_catch(ctx)
rethrow(J);
ffi_pushobj(J, obj);
}
static void ffi_PDFDocument_newGraftMap(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_document *pdf = js_touserdata(J, 0, "pdf_document");
pdf_graft_map *map = NULL;
fz_try(ctx)
map = pdf_new_graft_map(ctx, pdf);
fz_catch(ctx)
rethrow(J);
js_getregistry(J, "pdf_graft_map");
js_newuserdata(J, "pdf_graft_map", map, ffi_gc_pdf_graft_map);
}
static void ffi_PDFDocument_graftObject(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_document *dst = js_touserdata(J, 0, "pdf_document");
pdf_obj *obj = js_touserdata(J, 1, "pdf_obj");
fz_try(ctx)
obj = pdf_graft_object(ctx, dst, obj);
fz_catch(ctx)
rethrow(J);
ffi_pushobj(J, obj);
}
static void ffi_PDFGraftMap_graftObject(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_graft_map *map = js_touserdata(J, 0, "pdf_graft_map");
pdf_obj *obj = js_touserdata(J, 1, "pdf_obj");
fz_try(ctx)
obj = pdf_graft_mapped_object(ctx, map, obj);
fz_catch(ctx)
rethrow(J);
ffi_pushobj(J, obj);
}
static void ffi_PDFObject_get(js_State *J)
{
pdf_obj *obj = js_touserdata(J, 0, "pdf_obj");
const char *key = js_tostring(J, 1);
if (!ffi_pdf_obj_has(J, obj, key))
js_pushundefined(J);
}
static void ffi_PDFObject_put(js_State *J)
{
pdf_obj *obj = js_touserdata(J, 0, "pdf_obj");
const char *key = js_tostring(J, 1);
js_copy(J, 2);
ffi_pdf_obj_put(J, obj, key);
}
static void ffi_PDFObject_delete(js_State *J)
{
pdf_obj *obj = js_touserdata(J, 0, "pdf_obj");
const char *key = js_tostring(J, 1);
ffi_pdf_obj_delete(J, obj, key);
}
static void ffi_PDFObject_push(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_obj *obj = js_touserdata(J, 0, "pdf_obj");
pdf_document *pdf = pdf_get_bound_document(ctx, obj);
pdf_obj *item = ffi_toobj(J, pdf, 1);
fz_try(ctx)
pdf_array_push(ctx, obj, item);
fz_always(ctx)
pdf_drop_obj(ctx, item);
fz_catch(ctx)
rethrow(J);
}
static void ffi_PDFObject_resolve(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_obj *obj = js_touserdata(J, 0, "pdf_obj");
pdf_obj *ind = NULL;
fz_try(ctx)
ind = pdf_resolve_indirect(ctx, obj);
fz_catch(ctx)
rethrow(J);
ffi_pushobj(J, pdf_keep_obj(ctx, ind));
}
static void ffi_PDFObject_toString(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_obj *obj = js_touserdata(J, 0, "pdf_obj");
int tight = js_isdefined(J, 1) ? js_toboolean(J, 1) : 1;
int ascii = js_isdefined(J, 2) ? js_toboolean(J, 2) : 0;
char *s = NULL;
int n;
fz_try(ctx)
s = pdf_sprint_obj(ctx, NULL, 0, &n, obj, tight, ascii);
fz_catch(ctx)
rethrow(J);
if (js_try(J)) {
fz_free(ctx, s);
js_throw(J);
}
js_pushstring(J, s);
js_endtry(J);
fz_free(ctx, s);
}
static void ffi_PDFObject_valueOf(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_obj *obj = js_touserdata(J, 0, "pdf_obj");
if (pdf_is_indirect(ctx, obj))
js_pushstring(J, "R");
else if (pdf_is_null(ctx, obj))
js_pushnull(J);
else if (pdf_is_bool(ctx, obj))
js_pushboolean(J, pdf_to_bool(ctx, obj));
else if (pdf_is_int(ctx, obj))
js_pushnumber(J, pdf_to_int(ctx, obj));
else if (pdf_is_real(ctx, obj))
js_pushnumber(J, pdf_to_real(ctx, obj));
else if (pdf_is_string(ctx, obj))
js_pushlstring(J, pdf_to_str_buf(ctx, obj), pdf_to_str_len(ctx, obj));
else if (pdf_is_name(ctx, obj))
js_pushstring(J, pdf_to_name(ctx, obj));
else
js_copy(J, 0);
}
static void ffi_PDFObject_isArray(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_obj *obj = js_touserdata(J, 0, "pdf_obj");
int b = 0;
fz_try(ctx)
b = pdf_is_array(ctx, obj);
fz_catch(ctx)
rethrow(J);
js_pushboolean(J, b);
}
static void ffi_PDFObject_isDictionary(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_obj *obj = js_touserdata(J, 0, "pdf_obj");
int b = 0;
fz_try(ctx)
b = pdf_is_dict(ctx, obj);
fz_catch(ctx)
rethrow(J);
js_pushboolean(J, b);
}
static void ffi_PDFObject_isIndirect(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_obj *obj = js_touserdata(J, 0, "pdf_obj");
int b = 0;
fz_try(ctx)
b = pdf_is_indirect(ctx, obj);
fz_catch(ctx)
rethrow(J);
js_pushboolean(J, b);
}
static void ffi_PDFObject_asIndirect(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_obj *obj = js_touserdata(J, 0, "pdf_obj");
int num = 0;
fz_try(ctx)
num = pdf_to_num(ctx, obj);
fz_catch(ctx)
rethrow(J);
js_pushnumber(J, num);
}
static void ffi_PDFObject_isNull(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_obj *obj = js_touserdata(J, 0, "pdf_obj");
int b = 0;
fz_try(ctx)
b = pdf_is_null(ctx, obj);
fz_catch(ctx)
rethrow(J);
js_pushboolean(J, b);
}
static void ffi_PDFObject_isBoolean(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_obj *obj = js_touserdata(J, 0, "pdf_obj");
int b = 0;
fz_try(ctx)
b = pdf_is_bool(ctx, obj);
fz_catch(ctx)
rethrow(J);
js_pushboolean(J, b);
}
static void ffi_PDFObject_asBoolean(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_obj *obj = js_touserdata(J, 0, "pdf_obj");
int b = 0;
fz_try(ctx)
b = pdf_to_bool(ctx, obj);
fz_catch(ctx)
rethrow(J);
js_pushboolean(J, b);
}
static void ffi_PDFObject_isNumber(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_obj *obj = js_touserdata(J, 0, "pdf_obj");
int b = 0;
fz_try(ctx)
b = pdf_is_number(ctx, obj);
fz_catch(ctx)
rethrow(J);
js_pushboolean(J, b);
}
static void ffi_PDFObject_asNumber(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_obj *obj = js_touserdata(J, 0, "pdf_obj");
float num = 0;
fz_try(ctx)
if (pdf_is_int(ctx, obj))
num = pdf_to_int(ctx, obj);
else
num = pdf_to_real(ctx, obj);
fz_catch(ctx)
rethrow(J);
js_pushnumber(J, num);
}
static void ffi_PDFObject_isName(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_obj *obj = js_touserdata(J, 0, "pdf_obj");
int b = 0;
fz_try(ctx)
b = pdf_is_name(ctx, obj);
fz_catch(ctx)
rethrow(J);
js_pushboolean(J, b);
}
static void ffi_PDFObject_asName(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_obj *obj = js_touserdata(J, 0, "pdf_obj");
const char *name = NULL;
fz_try(ctx)
name = pdf_to_name(ctx, obj);
fz_catch(ctx)
rethrow(J);
js_pushstring(J, name);
}
static void ffi_PDFObject_isString(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_obj *obj = js_touserdata(J, 0, "pdf_obj");
int b = 0;
fz_try(ctx)
b = pdf_is_string(ctx, obj);
fz_catch(ctx)
rethrow(J);
js_pushboolean(J, b);
}
static void ffi_PDFObject_asString(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_obj *obj = js_touserdata(J, 0, "pdf_obj");
const char *string = NULL;
fz_try(ctx)
string = pdf_to_text_string(ctx, obj);
fz_catch(ctx)
rethrow(J);
js_pushstring(J, string);
}
static void ffi_PDFObject_asByteString(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_obj *obj = js_touserdata(J, 0, "pdf_obj");
const char *buf;
size_t i, len = 0;
fz_try(ctx)
buf = pdf_to_string(ctx, obj, &len);
fz_catch(ctx)
rethrow(J);
js_newarray(J);
for (i = 0; i < len; ++i) {
js_pushnumber(J, (unsigned char)buf[i]);
js_setindex(J, -2, i);
}
}
static void ffi_PDFObject_isStream(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_obj *obj = js_touserdata(J, 0, "pdf_obj");
int b = 0;
fz_try(ctx)
b = pdf_is_stream(ctx, obj);
fz_catch(ctx)
rethrow(J);
js_pushboolean(J, b);
}
static void ffi_PDFObject_readStream(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_obj *obj = js_touserdata(J, 0, "pdf_obj");
fz_buffer *buf = NULL;
fz_try(ctx)
buf = pdf_load_stream(ctx, obj);
fz_catch(ctx)
rethrow(J);
ffi_pushbuffer(J, buf);
}
static void ffi_PDFObject_readRawStream(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_obj *obj = js_touserdata(J, 0, "pdf_obj");
fz_buffer *buf = NULL;
fz_try(ctx)
buf = pdf_load_raw_stream(ctx, obj);
fz_catch(ctx)
rethrow(J);
ffi_pushbuffer(J, buf);
}
static void ffi_PDFObject_writeObject(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_obj *ref = js_touserdata(J, 0, "pdf_obj");
pdf_document *pdf = pdf_get_bound_document(ctx, ref);
pdf_obj *obj = ffi_toobj(J, pdf, 1);
fz_try(ctx)
pdf_update_object(ctx, pdf, pdf_to_num(ctx, ref), obj);
fz_always(ctx)
pdf_drop_obj(ctx, obj);
fz_catch(ctx)
rethrow(J);
}
static void ffi_PDFObject_writeStream(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_obj *obj = js_touserdata(J, 0, "pdf_obj");
fz_buffer *buf = ffi_tobuffer(J, 1);
fz_try(ctx)
pdf_update_stream(ctx, pdf_get_bound_document(ctx, obj), obj, buf, 0);
fz_always(ctx)
fz_drop_buffer(ctx, buf);
fz_catch(ctx)
rethrow(J);
}
static void ffi_PDFObject_writeRawStream(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_obj *obj = js_touserdata(J, 0, "pdf_obj");
fz_buffer *buf = ffi_tobuffer(J, 1);
fz_try(ctx)
pdf_update_stream(ctx, pdf_get_bound_document(ctx, obj), obj, buf, 1);
fz_always(ctx)
fz_drop_buffer(ctx, buf);
fz_catch(ctx)
rethrow(J);
}
static void ffi_PDFObject_forEach(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_obj *obj = js_touserdata(J, 0, "pdf_obj");
pdf_obj *val = NULL;
const char *key = NULL;
int i, n = 0;
fz_try(ctx)
obj = pdf_resolve_indirect_chain(ctx, obj);
fz_catch(ctx)
rethrow(J);
if (pdf_is_array(ctx, obj)) {
fz_try(ctx)
n = pdf_array_len(ctx, obj);
fz_catch(ctx)
rethrow(J);
for (i = 0; i < n; ++i) {
fz_try(ctx)
val = pdf_array_get(ctx, obj, i);
fz_catch(ctx)
rethrow(J);
js_copy(J, 1);
js_pushnull(J);
js_pushnumber(J, i);
ffi_pushobj(J, pdf_keep_obj(ctx, val));
js_call(J, 2);
js_pop(J, 1);
}
return;
}
if (pdf_is_dict(ctx, obj)) {
fz_try(ctx)
n = pdf_dict_len(ctx, obj);
fz_catch(ctx)
rethrow(J);
for (i = 0; i < n; ++i) {
fz_try(ctx) {
key = pdf_to_name(ctx, pdf_dict_get_key(ctx, obj, i));
val = pdf_dict_get_val(ctx, obj, i);
} fz_catch(ctx)
rethrow(J);
js_copy(J, 1);
js_pushnull(J);
js_pushstring(J, key);
ffi_pushobj(J, pdf_keep_obj(ctx, val));
js_call(J, 2);
js_pop(J, 1);
}
return;
}
}
static void ffi_PDFPage_getAnnotations(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_page *page = js_touserdata(J, 0, "pdf_page");
pdf_annot *annot = NULL;
int i = 0;
js_newarray(J);
fz_try(ctx)
annot = pdf_first_annot(ctx, page);
fz_catch(ctx)
rethrow(J);
while (annot) {
js_newuserdata(J, "pdf_annot", pdf_keep_annot(ctx, annot), ffi_gc_pdf_annot);
js_setindex(J, -2, i++);
fz_try(ctx)
annot = pdf_next_annot(ctx, annot);
fz_catch(ctx)
rethrow(J);
}
}
static void ffi_PDFPage_createAnnotation(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_page *page = js_touserdata(J, 0, "pdf_page");
const char *name = js_tostring(J, 1);
pdf_annot *annot = NULL;
int subtype;
fz_try(ctx)
{
subtype = pdf_annot_type_from_string(ctx, name);
annot = pdf_create_annot(ctx, page, subtype);
}
fz_catch(ctx)
rethrow(J);
js_newuserdata(J, "pdf_annot", annot, ffi_gc_pdf_annot);
}
static void ffi_PDFPage_deleteAnnotation(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_page *page = js_touserdata(J, 0, "pdf_page");
pdf_annot *annot = js_touserdata(J, 1, "pdf_annot");
fz_try(ctx)
pdf_delete_annot(ctx, page, annot);
fz_catch(ctx)
rethrow(J);
}
static void ffi_PDFPage_update(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_page *page = js_touserdata(J, 0, "pdf_page");
int changed = 0;
fz_try(ctx)
changed = pdf_update_page(ctx, page);
fz_catch(ctx)
rethrow(J);
js_pushboolean(J, changed);
}
static void ffi_PDFAnnotation_bound(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_annot *annot = js_touserdata(J, 0, "pdf_annot");
fz_rect bounds;
fz_try(ctx)
bounds = pdf_bound_annot(ctx, annot);
fz_catch(ctx)
rethrow(J);
ffi_pushrect(J, bounds);
}
static void ffi_PDFAnnotation_run(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_annot *annot = js_touserdata(J, 0, "pdf_annot");
fz_device *device = NULL;
fz_matrix ctm = ffi_tomatrix(J, 2);
if (js_isuserdata(J, 1, "fz_device")) {
device = js_touserdata(J, 1, "fz_device");
fz_try(ctx)
pdf_run_annot(ctx, annot, device, ctm, NULL);
fz_catch(ctx)
rethrow(J);
} else {
device = new_js_device(ctx, J);
js_copy(J, 1); /* put the js device on the top so the callbacks know where to get it */
fz_try(ctx) {
pdf_run_annot(ctx, annot, device, ctm, NULL);
fz_close_device(ctx, device);
}
fz_always(ctx)
fz_drop_device(ctx, device);
fz_catch(ctx)
rethrow(J);
}
}
static void ffi_PDFAnnotation_toDisplayList(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_annot *annot = js_touserdata(J, 0, "pdf_annot");
fz_display_list *list = NULL;
fz_try(ctx)
list = pdf_new_display_list_from_annot(ctx, annot);
fz_catch(ctx)
rethrow(J);
js_getregistry(J, "fz_display_list");
js_newuserdata(J, "fz_display_list", list, ffi_gc_fz_display_list);
}
static void ffi_PDFAnnotation_toPixmap(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_annot *annot = js_touserdata(J, 0, "pdf_annot");
fz_matrix ctm = ffi_tomatrix(J, 1);
fz_colorspace *colorspace = js_touserdata(J, 2, "fz_colorspace");
int alpha = js_toboolean(J, 3);
fz_pixmap *pixmap = NULL;
fz_try(ctx)
pixmap = pdf_new_pixmap_from_annot(ctx, annot, ctm, colorspace, NULL, alpha);
fz_catch(ctx)
rethrow(J);
js_getregistry(J, "fz_pixmap");
js_newuserdata(J, "fz_pixmap", pixmap, ffi_gc_fz_pixmap);
}
static void ffi_PDFAnnotation_getType(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_annot *annot = js_touserdata(J, 0, "pdf_annot");
int type;
const char *subtype = NULL;
fz_try(ctx)
{
type = pdf_annot_type(ctx, annot);
subtype = pdf_string_from_annot_type(ctx, type);
}
fz_catch(ctx)
rethrow(J);
js_pushstring(J, subtype);
}
static void ffi_PDFAnnotation_getFlags(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_annot *annot = js_touserdata(J, 0, "pdf_annot");
int flags = 0;
fz_try(ctx)
flags = pdf_annot_flags(ctx, annot);
fz_catch(ctx)
rethrow(J);
js_pushnumber(J, flags);
}
static void ffi_PDFAnnotation_setFlags(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_annot *annot = js_touserdata(J, 0, "pdf_annot");
int flags = js_tonumber(J, 1);
fz_try(ctx)
pdf_set_annot_flags(ctx, annot, flags);
fz_catch(ctx)
rethrow(J);
}
static void ffi_PDFAnnotation_getContents(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_annot *annot = js_touserdata(J, 0, "pdf_annot");
const char *contents = NULL;
fz_try(ctx)
contents = pdf_annot_contents(ctx, annot);
fz_catch(ctx)
rethrow(J);
js_pushstring(J, contents);
}
static void ffi_PDFAnnotation_setContents(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_annot *annot = js_touserdata(J, 0, "pdf_annot");
const char *contents = js_tostring(J, 1);
fz_try(ctx)
pdf_set_annot_contents(ctx, annot, contents);
fz_catch(ctx)
rethrow(J);
}
static void ffi_PDFAnnotation_getRect(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_annot *annot = js_touserdata(J, 0, "pdf_annot");
fz_rect rect;
fz_try(ctx)
rect = pdf_annot_rect(ctx, annot);
fz_catch(ctx)
rethrow(J);
ffi_pushrect(J, rect);
}
static void ffi_PDFAnnotation_setRect(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_annot *annot = js_touserdata(J, 0, "pdf_annot");
fz_rect rect = ffi_torect(J, 1);
fz_try(ctx)
pdf_set_annot_rect(ctx, annot, rect);
fz_catch(ctx)
rethrow(J);
}
static void ffi_PDFAnnotation_getBorder(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_annot *annot = js_touserdata(J, 0, "pdf_annot");
float border = 0;
fz_try(ctx)
border = pdf_annot_border(ctx, annot);
fz_catch(ctx)
rethrow(J);
js_pushnumber(J, border);
}
static void ffi_PDFAnnotation_setBorder(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_annot *annot = js_touserdata(J, 0, "pdf_annot");
float border = js_tonumber(J, 1);
fz_try(ctx)
pdf_set_annot_border(ctx, annot, border);
fz_catch(ctx)
rethrow(J);
}
static void ffi_PDFAnnotation_getColor(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_annot *annot = js_touserdata(J, 0, "pdf_annot");
int i, n = 0;
float color[4];
fz_try(ctx)
pdf_annot_color(ctx, annot, &n, color);
fz_catch(ctx)
rethrow(J);
js_newarray(J);
for (i = 0; i < n; ++i) {
js_pushnumber(J, color[i]);
js_setindex(J, -2, i);
}
}
static void ffi_PDFAnnotation_setColor(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_annot *annot = js_touserdata(J, 0, "pdf_annot");
int i, n = js_getlength(J, 1);
float color[4];
for (i = 0; i < n && i < 4; ++i) {
js_getindex(J, 1, i);
color[i] = js_tonumber(J, -1);
js_pop(J, 1);
}
fz_try(ctx)
pdf_set_annot_color(ctx, annot, n, color);
fz_catch(ctx)
rethrow(J);
}
static void ffi_PDFAnnotation_getInteriorColor(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_annot *annot = js_touserdata(J, 0, "pdf_annot");
int i, n = 0;
float color[4];
fz_try(ctx)
pdf_annot_interior_color(ctx, annot, &n, color);
fz_catch(ctx)
rethrow(J);
js_newarray(J);
for (i = 0; i < n; ++i) {
js_pushnumber(J, color[i]);
js_setindex(J, -2, i);
}
}
static void ffi_PDFAnnotation_setInteriorColor(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_annot *annot = js_touserdata(J, 0, "pdf_annot");
int i, n = js_getlength(J, 1);
float color[4];
for (i = 0; i < n && i < 4; ++i) {
js_getindex(J, 1, i);
color[i] = js_tonumber(J, -1);
js_pop(J, 1);
}
fz_try(ctx)
pdf_set_annot_interior_color(ctx, annot, n, color);
fz_catch(ctx)
rethrow(J);
}
static void ffi_PDFAnnotation_getQuadPoints(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_annot *annot = js_touserdata(J, 0, "pdf_annot");
float qp[8] = { 0 };
int i, k, n = 0;
fz_try(ctx)
n = pdf_annot_quad_point_count(ctx, annot);
fz_catch(ctx)
rethrow(J);
js_newarray(J);
for (i = 0; i < n; ++i) {
fz_try(ctx)
pdf_annot_quad_point(ctx, annot, i, qp);
fz_catch(ctx)
rethrow(J);
js_newarray(J);
for (k = 0; k < 8; ++k) {
js_pushnumber(J, qp[k]);
js_setindex(J, -2, k);
}
js_setindex(J, -2, i);
}
}
static void ffi_PDFAnnotation_setQuadPoints(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_annot *annot = js_touserdata(J, 0, "pdf_annot");
float *qp = NULL;
int k, i, n;
n = js_getlength(J, 1);
fz_try(ctx)
qp = fz_malloc(ctx, n * 8 * sizeof *qp);
fz_catch(ctx)
rethrow(J);
for (i = 0; i < n; ++i) {
js_getindex(J, 1, i);
for (k = 0; k < 8; ++k) {
js_getindex(J, -1, k);
qp[i * 8 + k] = js_tonumber(J, -1);
js_pop(J, 1);
}
js_pop(J, 1);
}
fz_try(ctx)
pdf_set_annot_quad_points(ctx, annot, n, qp);
fz_always(ctx)
fz_free(ctx, qp);
fz_catch(ctx)
rethrow(J);
}
static void ffi_PDFAnnotation_getInkList(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_annot *annot = js_touserdata(J, 0, "pdf_annot");
int i, k, m = 0, n = 0;
fz_point pt;
js_newarray(J);
fz_try(ctx)
n = pdf_annot_ink_list_count(ctx, annot);
fz_catch(ctx)
rethrow(J);
for (i = 0; i < n; ++i) {
fz_try(ctx)
m = pdf_annot_ink_list_stroke_count(ctx, annot, i);
fz_catch(ctx)
rethrow(J);
js_newarray(J);
for (k = 0; k < m; ++k) {
fz_try(ctx)
pt = pdf_annot_ink_list_stroke_vertex(ctx, annot, i, k);
fz_catch(ctx)
rethrow(J);
js_pushnumber(J, pt.x);
js_setindex(J, -2, k * 2 + 0);
js_pushnumber(J, pt.y);
js_setindex(J, -2, k * 2 + 1);
}
js_setindex(J, -2, i);
}
}
static void ffi_PDFAnnotation_setInkList(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_annot *annot = js_touserdata(J, 0, "pdf_annot");
fz_point *points = NULL;
int *counts = NULL;
int n, nv, k, i, v;
fz_var(counts);
fz_var(points);
n = js_getlength(J, 1);
nv = 0;
for (i = 0; i < n; ++i) {
js_getindex(J, 1, i);
nv += js_getlength(J, -1) / 2;
js_pop(J, 1);
}
fz_try(ctx) {
counts = fz_malloc(ctx, n * sizeof(int));
points = fz_malloc(ctx, nv * sizeof(fz_point));
} fz_catch(ctx) {
fz_free(ctx, counts);
fz_free(ctx, points);
rethrow(J);
}
if (js_try(J)) {
fz_free(ctx, counts);
fz_free(ctx, points);
js_throw(J);
}
for (i = v = 0; i < n; ++i) {
js_getindex(J, 1, i);
counts[i] = js_getlength(J, -1) / 2;
for (k = 0; k < counts[i]; ++k) {
js_getindex(J, -1, k*2);
points[v].x = js_tonumber(J, -1);
js_pop(J, 1);
js_getindex(J, -1, k*2+1);
points[v].y = js_tonumber(J, -1);
js_pop(J, 1);
++v;
}
js_pop(J, 1);
}
js_endtry(J);
fz_try(ctx)
pdf_set_annot_ink_list(ctx, annot, n, counts, points);
fz_always(ctx) {
fz_free(ctx, counts);
fz_free(ctx, points);
}
fz_catch(ctx)
rethrow(J);
}
static void ffi_PDFAnnotation_getAuthor(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_annot *annot = js_touserdata(J, 0, "pdf_annot");
const char *author = NULL;
fz_try(ctx)
author = pdf_annot_author(ctx, annot);
fz_catch(ctx)
rethrow(J);
js_pushstring(J, author);
}
static void ffi_PDFAnnotation_setAuthor(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_annot *annot = js_touserdata(J, 0, "pdf_annot");
const char *author = js_tostring(J, 1);
fz_try(ctx)
pdf_set_annot_author(ctx, annot, author);
fz_catch(ctx)
rethrow(J);
}
static void ffi_PDFAnnotation_getModificationDate(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_annot *annot = js_touserdata(J, 0, "pdf_annot");
double time;
fz_try(ctx)
time = pdf_annot_modification_date(ctx, annot);
fz_catch(ctx)
rethrow(J);
js_getglobal(J, "Date");
js_pushnumber(J, time * 1000);
js_construct(J, 1);
}
static void ffi_PDFAnnotation_setModificationDate(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_annot *annot = js_touserdata(J, 0, "pdf_annot");
double time = js_tonumber(J, 1);
fz_try(ctx)
pdf_set_annot_modification_date(ctx, annot, time / 1000);
fz_catch(ctx)
rethrow(J);
}
static void ffi_PDFAnnotation_updateAppearance(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_annot *annot = js_touserdata(J, 0, "pdf_annot");
fz_try(ctx)
pdf_update_appearance(ctx, annot);
fz_catch(ctx)
rethrow(J);
}
static void ffi_PDFAnnotation_update(js_State *J)
{
fz_context *ctx = js_getcontext(J);
pdf_annot *annot = js_touserdata(J, 0, "pdf_annot");
int changed = 0;
fz_try(ctx)
changed = pdf_update_annot(ctx, annot);
fz_catch(ctx)
rethrow(J);
js_pushboolean(J, changed);
}
#endif /* FZ_ENABLE_PDF */
int murun_main(int argc, char **argv)
{
fz_context *ctx;
js_State *J;
int i;
ctx = fz_new_context(NULL, NULL, FZ_STORE_UNLIMITED);
fz_register_document_handlers(ctx);
J = js_newstate(alloc, ctx, JS_STRICT);
js_setcontext(J, ctx);
/* standard command line javascript functions */
js_newcfunction(J, jsB_gc, "gc", 0);
js_setglobal(J, "gc");
js_newcfunction(J, jsB_load, "load", 1);
js_setglobal(J, "load");
js_newcfunction(J, jsB_print, "print", 1);
js_setglobal(J, "print");
js_newcfunction(J, jsB_write, "write", 0);
js_setglobal(J, "write");
js_newcfunction(J, jsB_read, "read", 1);
js_setglobal(J, "read");
js_newcfunction(J, jsB_readline, "readline", 0);
js_setglobal(J, "readline");
js_newcfunction(J, jsB_repr, "repr", 1);
js_setglobal(J, "repr");
js_newcfunction(J, jsB_quit, "quit", 1);
js_setglobal(J, "quit");
js_dostring(J, require_js);
js_dostring(J, stacktrace_js);
/* mupdf module */
/* Create superclass for all userdata objects */
js_dostring(J, "function Userdata() { throw new Error('Userdata is not callable'); }");
js_getglobal(J, "Userdata");
js_getproperty(J, -1, "prototype");
js_setregistry(J, "Userdata");
js_pop(J, 1);
js_getregistry(J, "Userdata");
js_newobjectx(J);
{
jsB_propfun(J, "Buffer.writeByte", ffi_Buffer_writeByte, 1);
jsB_propfun(J, "Buffer.writeRune", ffi_Buffer_writeRune, 1);
jsB_propfun(J, "Buffer.writeLine", ffi_Buffer_writeLine, 1);
jsB_propfun(J, "Buffer.writeBuffer", ffi_Buffer_writeBuffer, 1);
jsB_propfun(J, "Buffer.write", ffi_Buffer_write, 1);
jsB_propfun(J, "Buffer.save", ffi_Buffer_save, 1);
}
js_setregistry(J, "fz_buffer");
js_getregistry(J, "Userdata");
js_newobjectx(J);
{
jsB_propfun(J, "Document.isPDF", ffi_Document_isPDF, 0);
jsB_propfun(J, "Document.needsPassword", ffi_Document_needsPassword, 0);
jsB_propfun(J, "Document.authenticatePassword", ffi_Document_authenticatePassword, 1);
//jsB_propfun(J, "Document.hasPermission", ffi_Document_hasPermission, 1);
jsB_propfun(J, "Document.getMetaData", ffi_Document_getMetaData, 1);
jsB_propfun(J, "Document.isReflowable", ffi_Document_isReflowable, 0);
jsB_propfun(J, "Document.layout", ffi_Document_layout, 3);
jsB_propfun(J, "Document.countPages", ffi_Document_countPages, 0);
jsB_propfun(J, "Document.loadPage", ffi_Document_loadPage, 1);
jsB_propfun(J, "Document.loadOutline", ffi_Document_loadOutline, 0);
}
js_setregistry(J, "fz_document");
js_getregistry(J, "Userdata");
js_newobjectx(J);
{
jsB_propfun(J, "Page.isPDF", ffi_Page_isPDF, 0);
jsB_propfun(J, "Page.bound", ffi_Page_bound, 0);
jsB_propfun(J, "Page.run", ffi_Page_run, 3);
jsB_propfun(J, "Page.toPixmap", ffi_Page_toPixmap, 4);
jsB_propfun(J, "Page.toDisplayList", ffi_Page_toDisplayList, 1);
jsB_propfun(J, "Page.toStructuredText", ffi_Page_toStructuredText, 1);
jsB_propfun(J, "Page.search", ffi_Page_search, 0);
jsB_propfun(J, "Page.getLinks", ffi_Page_getLinks, 0);
}
js_setregistry(J, "fz_page");
js_getregistry(J, "Userdata");
js_newobjectx(J);
{
jsB_propfun(J, "Device.close", ffi_Device_close, 0);
jsB_propfun(J, "Device.fillPath", ffi_Device_fillPath, 7);
jsB_propfun(J, "Device.strokePath", ffi_Device_strokePath, 7);
jsB_propfun(J, "Device.clipPath", ffi_Device_clipPath, 3);
jsB_propfun(J, "Device.clipStrokePath", ffi_Device_clipStrokePath, 3);
jsB_propfun(J, "Device.fillText", ffi_Device_fillText, 6);
jsB_propfun(J, "Device.strokeText", ffi_Device_strokeText, 7);
jsB_propfun(J, "Device.clipText", ffi_Device_clipText, 2);
jsB_propfun(J, "Device.clipStrokeText", ffi_Device_clipStrokeText, 3);
jsB_propfun(J, "Device.ignoreText", ffi_Device_ignoreText, 2);
jsB_propfun(J, "Device.fillShade", ffi_Device_fillShade, 4);
jsB_propfun(J, "Device.fillImage", ffi_Device_fillImage, 4);
jsB_propfun(J, "Device.fillImageMask", ffi_Device_fillImageMask, 6);
jsB_propfun(J, "Device.clipImageMask", ffi_Device_clipImageMask, 2);
jsB_propfun(J, "Device.popClip", ffi_Device_popClip, 0);
jsB_propfun(J, "Device.beginMask", ffi_Device_beginMask, 6);
jsB_propfun(J, "Device.endMask", ffi_Device_endMask, 0);
jsB_propfun(J, "Device.beginGroup", ffi_Device_beginGroup, 5);
jsB_propfun(J, "Device.endGroup", ffi_Device_endGroup, 0);
jsB_propfun(J, "Device.beginTile", ffi_Device_beginTile, 6);
jsB_propfun(J, "Device.endTile", ffi_Device_endTile, 0);
jsB_propfun(J, "Device.beginLayer", ffi_Device_beginLayer, 1);
jsB_propfun(J, "Device.endLayer", ffi_Device_endLayer, 0);
}
js_setregistry(J, "fz_device");
js_getregistry(J, "Userdata");
js_newobjectx(J);
{
jsB_propfun(J, "ColorSpace.getNumberOfComponents", ffi_ColorSpace_getNumberOfComponents, 0);
jsB_propfun(J, "ColorSpace.toString", ffi_ColorSpace_toString, 0);
}
js_setregistry(J, "fz_colorspace");
{
js_getregistry(J, "fz_colorspace");
js_newuserdata(J, "fz_colorspace", fz_keep_colorspace(ctx, fz_device_gray(ctx)), ffi_gc_fz_colorspace);
js_setregistry(J, "DeviceGray");
js_getregistry(J, "fz_colorspace");
js_newuserdata(J, "fz_colorspace", fz_keep_colorspace(ctx, fz_device_rgb(ctx)), ffi_gc_fz_colorspace);
js_setregistry(J, "DeviceRGB");
js_getregistry(J, "fz_colorspace");
js_newuserdata(J, "fz_colorspace", fz_keep_colorspace(ctx, fz_device_bgr(ctx)), ffi_gc_fz_colorspace);
js_setregistry(J, "DeviceBGR");
js_getregistry(J, "fz_colorspace");
js_newuserdata(J, "fz_colorspace", fz_keep_colorspace(ctx, fz_device_cmyk(ctx)), ffi_gc_fz_colorspace);
js_setregistry(J, "DeviceCMYK");
}
js_getregistry(J, "Userdata");
js_newobjectx(J);
{
jsB_propfun(J, "Shade.bound", ffi_Shade_bound, 1);
}
js_setregistry(J, "fz_shade");
js_getregistry(J, "Userdata");
js_newobjectx(J);
{
jsB_propfun(J, "Image.getWidth", ffi_Image_getWidth, 0);
jsB_propfun(J, "Image.getHeight", ffi_Image_getHeight, 0);
jsB_propfun(J, "Image.getColorSpace", ffi_Image_getColorSpace, 0);
jsB_propfun(J, "Image.getXResolution", ffi_Image_getXResolution, 0);
jsB_propfun(J, "Image.getYResolution", ffi_Image_getYResolution, 0);
jsB_propfun(J, "Image.getNumberOfComponents", ffi_Image_getNumberOfComponents, 0);
jsB_propfun(J, "Image.getBitsPerComponent", ffi_Image_getBitsPerComponent, 0);
jsB_propfun(J, "Image.getInterpolate", ffi_Image_getInterpolate, 0);
jsB_propfun(J, "Image.getImageMask", ffi_Image_getImageMask, 0);
jsB_propfun(J, "Image.getMask", ffi_Image_getMask, 0);
jsB_propfun(J, "Image.toPixmap", ffi_Image_toPixmap, 2);
}
js_setregistry(J, "fz_image");
js_getregistry(J, "Userdata");
js_newobjectx(J);
{
jsB_propfun(J, "Font.getName", ffi_Font_getName, 0);
jsB_propfun(J, "Font.encodeCharacter", ffi_Font_encodeCharacter, 1);
jsB_propfun(J, "Font.advanceGlyph", ffi_Font_advanceGlyph, 2);
}
js_setregistry(J, "fz_font");
js_getregistry(J, "Userdata");
js_newobjectx(J);
{
jsB_propfun(J, "Text.walk", ffi_Text_walk, 1);
jsB_propfun(J, "Text.showGlyph", ffi_Text_showGlyph, 5);
jsB_propfun(J, "Text.showString", ffi_Text_showString, 4);
}
js_setregistry(J, "fz_text");
js_getregistry(J, "Userdata");
js_newobjectx(J);
{
jsB_propfun(J, "Path.walk", ffi_Path_walk, 1);
jsB_propfun(J, "Path.moveTo", ffi_Path_moveTo, 2);
jsB_propfun(J, "Path.lineTo", ffi_Path_lineTo, 2);
jsB_propfun(J, "Path.curveTo", ffi_Path_curveTo, 6);
jsB_propfun(J, "Path.curveToV", ffi_Path_curveToV, 4);
jsB_propfun(J, "Path.curveToY", ffi_Path_curveToY, 4);
jsB_propfun(J, "Path.closePath", ffi_Path_closePath, 0);
jsB_propfun(J, "Path.rect", ffi_Path_rect, 4);
jsB_propfun(J, "Path.bound", ffi_Path_bound, 2);
jsB_propfun(J, "Path.transform", ffi_Path_transform, 1);
}
js_setregistry(J, "fz_path");
js_getregistry(J, "Userdata");
js_newobjectx(J);
{
jsB_propfun(J, "DisplayList.run", ffi_DisplayList_run, 2);
jsB_propfun(J, "DisplayList.toPixmap", ffi_DisplayList_toPixmap, 3);
jsB_propfun(J, "DisplayList.toStructuredText", ffi_DisplayList_toStructuredText, 1);
jsB_propfun(J, "DisplayList.search", ffi_DisplayList_search, 1);
}
js_setregistry(J, "fz_display_list");
js_getregistry(J, "Userdata");
js_newobjectx(J);
{
jsB_propfun(J, "StructuredText.search", ffi_StructuredText_search, 1);
jsB_propfun(J, "StructuredText.highlight", ffi_StructuredText_highlight, 2);
jsB_propfun(J, "StructuredText.copy", ffi_StructuredText_copy, 2);
}
js_setregistry(J, "fz_stext_page");
js_getregistry(J, "Userdata");
js_newobjectx(J);
{
jsB_propfun(J, "Pixmap.bound", ffi_Pixmap_bound, 0);
jsB_propfun(J, "Pixmap.clear", ffi_Pixmap_clear, 1);
jsB_propfun(J, "Pixmap.getX", ffi_Pixmap_getX, 0);
jsB_propfun(J, "Pixmap.getY", ffi_Pixmap_getY, 0);
jsB_propfun(J, "Pixmap.getWidth", ffi_Pixmap_getWidth, 0);
jsB_propfun(J, "Pixmap.getHeight", ffi_Pixmap_getHeight, 0);
jsB_propfun(J, "Pixmap.getNumberOfComponents", ffi_Pixmap_getNumberOfComponents, 0);
jsB_propfun(J, "Pixmap.getAlpha", ffi_Pixmap_getAlpha, 0);
jsB_propfun(J, "Pixmap.getStride", ffi_Pixmap_getStride, 0);
jsB_propfun(J, "Pixmap.getColorSpace", ffi_Pixmap_getColorSpace, 0);
jsB_propfun(J, "Pixmap.getXResolution", ffi_Pixmap_getXResolution, 0);
jsB_propfun(J, "Pixmap.getYResolution", ffi_Pixmap_getYResolution, 0);
jsB_propfun(J, "Pixmap.getSample", ffi_Pixmap_getSample, 3);
// Pixmap.samples()
// Pixmap.invert
// Pixmap.tint
// Pixmap.gamma
// Pixmap.scale()
jsB_propfun(J, "Pixmap.saveAsPNG", ffi_Pixmap_saveAsPNG, 1);
// Pixmap.saveAsPNM, PAM, PWG, PCL
// Pixmap.halftone() -> Bitmap
// Pixmap.md5()
}
js_setregistry(J, "fz_pixmap");
js_getregistry(J, "Userdata");
js_newobjectx(J);
{
jsB_propfun(J, "DocumentWriter.beginPage", ffi_DocumentWriter_beginPage, 1);
jsB_propfun(J, "DocumentWriter.endPage", ffi_DocumentWriter_endPage, 0);
jsB_propfun(J, "DocumentWriter.close", ffi_DocumentWriter_close, 0);
}
js_setregistry(J, "fz_document_writer");
#if FZ_ENABLE_PDF
js_getregistry(J, "fz_document");
js_newobjectx(J);
{
jsB_propfun(J, "PDFDocument.getTrailer", ffi_PDFDocument_getTrailer, 0);
jsB_propfun(J, "PDFDocument.countObjects", ffi_PDFDocument_countObjects, 0);
jsB_propfun(J, "PDFDocument.createObject", ffi_PDFDocument_createObject, 0);
jsB_propfun(J, "PDFDocument.deleteObject", ffi_PDFDocument_deleteObject, 1);
jsB_propfun(J, "PDFDocument.addObject", ffi_PDFDocument_addObject, 1);
jsB_propfun(J, "PDFDocument.addStream", ffi_PDFDocument_addStream, 2);
jsB_propfun(J, "PDFDocument.addRawStream", ffi_PDFDocument_addRawStream, 2);
jsB_propfun(J, "PDFDocument.addSimpleFont", ffi_PDFDocument_addSimpleFont, 2);
jsB_propfun(J, "PDFDocument.addCJKFont", ffi_PDFDocument_addCJKFont, 4);
jsB_propfun(J, "PDFDocument.addFont", ffi_PDFDocument_addFont, 1);
jsB_propfun(J, "PDFDocument.addImage", ffi_PDFDocument_addImage, 1);
jsB_propfun(J, "PDFDocument.loadImage", ffi_PDFDocument_loadImage, 1);
jsB_propfun(J, "PDFDocument.addPage", ffi_PDFDocument_addPage, 4);
jsB_propfun(J, "PDFDocument.insertPage", ffi_PDFDocument_insertPage, 2);
jsB_propfun(J, "PDFDocument.deletePage", ffi_PDFDocument_deletePage, 1);
jsB_propfun(J, "PDFDocument.countPages", ffi_PDFDocument_countPages, 0);
jsB_propfun(J, "PDFDocument.findPage", ffi_PDFDocument_findPage, 1);
jsB_propfun(J, "PDFDocument.save", ffi_PDFDocument_save, 2);
jsB_propfun(J, "PDFDocument.newNull", ffi_PDFDocument_newNull, 0);
jsB_propfun(J, "PDFDocument.newBoolean", ffi_PDFDocument_newBoolean, 1);
jsB_propfun(J, "PDFDocument.newInteger", ffi_PDFDocument_newInteger, 1);
jsB_propfun(J, "PDFDocument.newReal", ffi_PDFDocument_newReal, 1);
jsB_propfun(J, "PDFDocument.newString", ffi_PDFDocument_newString, 1);
jsB_propfun(J, "PDFDocument.newByteString", ffi_PDFDocument_newByteString, 1);
jsB_propfun(J, "PDFDocument.newName", ffi_PDFDocument_newName, 1);
jsB_propfun(J, "PDFDocument.newIndirect", ffi_PDFDocument_newIndirect, 2);
jsB_propfun(J, "PDFDocument.newArray", ffi_PDFDocument_newArray, 1);
jsB_propfun(J, "PDFDocument.newDictionary", ffi_PDFDocument_newDictionary, 1);
jsB_propfun(J, "PDFDocument.newGraftMap", ffi_PDFDocument_newGraftMap, 0);
jsB_propfun(J, "PDFDocument.graftObject", ffi_PDFDocument_graftObject, 1);
}
js_setregistry(J, "pdf_document");
js_getregistry(J, "fz_page");
js_newobjectx(J);
{
jsB_propfun(J, "PDFPage.getAnnotations", ffi_PDFPage_getAnnotations, 0);
jsB_propfun(J, "PDFPage.createAnnotation", ffi_PDFPage_createAnnotation, 1);
jsB_propfun(J, "PDFPage.deleteAnnotation", ffi_PDFPage_deleteAnnotation, 1);
jsB_propfun(J, "PDFPage.update", ffi_PDFPage_update, 0);
}
js_setregistry(J, "pdf_page");
js_getregistry(J, "Userdata");
js_newobjectx(J);
{
jsB_propfun(J, "PDFAnnotation.bound", ffi_PDFAnnotation_bound, 0);
jsB_propfun(J, "PDFAnnotation.run", ffi_PDFAnnotation_run, 2);
jsB_propfun(J, "PDFAnnotation.toPixmap", ffi_PDFAnnotation_toPixmap, 3);
jsB_propfun(J, "PDFAnnotation.toDisplayList", ffi_PDFAnnotation_toDisplayList, 0);
jsB_propfun(J, "PDFAnnotation.getType", ffi_PDFAnnotation_getType, 0);
jsB_propfun(J, "PDFAnnotation.getFlags", ffi_PDFAnnotation_getFlags, 0);
jsB_propfun(J, "PDFAnnotation.setFlags", ffi_PDFAnnotation_setFlags, 1);
jsB_propfun(J, "PDFAnnotation.getContents", ffi_PDFAnnotation_getContents, 0);
jsB_propfun(J, "PDFAnnotation.setContents", ffi_PDFAnnotation_setContents, 1);
jsB_propfun(J, "PDFAnnotation.getRect", ffi_PDFAnnotation_getRect, 0);
jsB_propfun(J, "PDFAnnotation.setRect", ffi_PDFAnnotation_setRect, 1);
jsB_propfun(J, "PDFAnnotation.getBorder", ffi_PDFAnnotation_getBorder, 0);
jsB_propfun(J, "PDFAnnotation.setBorder", ffi_PDFAnnotation_setBorder, 1);
jsB_propfun(J, "PDFAnnotation.getColor", ffi_PDFAnnotation_getColor, 0);
jsB_propfun(J, "PDFAnnotation.setColor", ffi_PDFAnnotation_setColor, 1);
jsB_propfun(J, "PDFAnnotation.getInteriorColor", ffi_PDFAnnotation_getInteriorColor, 0);
jsB_propfun(J, "PDFAnnotation.setInteriorColor", ffi_PDFAnnotation_setInteriorColor, 1);
jsB_propfun(J, "PDFAnnotation.getQuadPoints", ffi_PDFAnnotation_getQuadPoints, 0);
jsB_propfun(J, "PDFAnnotation.setQuadPoints", ffi_PDFAnnotation_setQuadPoints, 1);
jsB_propfun(J, "PDFAnnotation.getInkList", ffi_PDFAnnotation_getInkList, 0);
jsB_propfun(J, "PDFAnnotation.setInkList", ffi_PDFAnnotation_setInkList, 1);
jsB_propfun(J, "PDFAnnotation.getAuthor", ffi_PDFAnnotation_getAuthor, 0);
jsB_propfun(J, "PDFAnnotation.setAuthor", ffi_PDFAnnotation_setAuthor, 1);
jsB_propfun(J, "PDFAnnotation.getModificationDate", ffi_PDFAnnotation_getModificationDate, 0);
jsB_propfun(J, "PDFAnnotation.setModificationDate", ffi_PDFAnnotation_setModificationDate, 0);
jsB_propfun(J, "PDFAnnotation.updateAppearance", ffi_PDFAnnotation_updateAppearance, 0);
jsB_propfun(J, "PDFAnnotation.update", ffi_PDFAnnotation_update, 0);
}
js_setregistry(J, "pdf_annot");
js_getregistry(J, "Userdata");
js_newobjectx(J);
{
jsB_propfun(J, "PDFObject.get", ffi_PDFObject_get, 1);
jsB_propfun(J, "PDFObject.put", ffi_PDFObject_put, 2);
jsB_propfun(J, "PDFObject.push", ffi_PDFObject_push, 1);
jsB_propfun(J, "PDFObject.delete", ffi_PDFObject_delete, 1);
jsB_propfun(J, "PDFObject.resolve", ffi_PDFObject_resolve, 0);
jsB_propfun(J, "PDFObject.toString", ffi_PDFObject_toString, 2);
jsB_propfun(J, "PDFObject.valueOf", ffi_PDFObject_valueOf, 0);
jsB_propfun(J, "PDFObject.isArray", ffi_PDFObject_isArray, 0);
jsB_propfun(J, "PDFObject.isDictionary", ffi_PDFObject_isDictionary, 0);
jsB_propfun(J, "PDFObject.isIndirect", ffi_PDFObject_isIndirect, 0);
jsB_propfun(J, "PDFObject.asIndirect", ffi_PDFObject_asIndirect, 0);
jsB_propfun(J, "PDFObject.isNull", ffi_PDFObject_isNull, 0);
jsB_propfun(J, "PDFObject.isBoolean", ffi_PDFObject_isBoolean, 0);
jsB_propfun(J, "PDFObject.asBoolean", ffi_PDFObject_asBoolean, 0);
jsB_propfun(J, "PDFObject.isNumber", ffi_PDFObject_isNumber, 0);
jsB_propfun(J, "PDFObject.asNumber", ffi_PDFObject_asNumber, 0);
jsB_propfun(J, "PDFObject.isName", ffi_PDFObject_isName, 0);
jsB_propfun(J, "PDFObject.asName", ffi_PDFObject_asName, 0);
jsB_propfun(J, "PDFObject.isString", ffi_PDFObject_isString, 0);
jsB_propfun(J, "PDFObject.asString", ffi_PDFObject_asString, 0);
jsB_propfun(J, "PDFObject.asByteString", ffi_PDFObject_asByteString, 0);
jsB_propfun(J, "PDFObject.isStream", ffi_PDFObject_isStream, 0);
jsB_propfun(J, "PDFObject.readStream", ffi_PDFObject_readStream, 0);
jsB_propfun(J, "PDFObject.readRawStream", ffi_PDFObject_readRawStream, 0);
jsB_propfun(J, "PDFObject.writeObject", ffi_PDFObject_writeObject, 1);
jsB_propfun(J, "PDFObject.writeStream", ffi_PDFObject_writeStream, 1);
jsB_propfun(J, "PDFObject.writeRawStream", ffi_PDFObject_writeRawStream, 1);
jsB_propfun(J, "PDFObject.forEach", ffi_PDFObject_forEach, 1);
}
js_setregistry(J, "pdf_obj");
js_getregistry(J, "Userdata");
js_newobjectx(J);
{
jsB_propfun(J, "PDFGraftMap.graftObject", ffi_PDFGraftMap_graftObject, 1);
}
js_setregistry(J, "pdf_graft_map");
#endif
js_pushglobal(J);
{
#if FZ_ENABLE_PDF
jsB_propcon(J, "pdf_document", "PDFDocument", ffi_new_PDFDocument, 1);
#endif
jsB_propcon(J, "fz_buffer", "Buffer", ffi_new_Buffer, 1);
jsB_propcon(J, "fz_document", "Document", ffi_new_Document, 1);
jsB_propcon(J, "fz_pixmap", "Pixmap", ffi_new_Pixmap, 3);
jsB_propcon(J, "fz_image", "Image", ffi_new_Image, 1);
jsB_propcon(J, "fz_font", "Font", ffi_new_Font, 2);
jsB_propcon(J, "fz_text", "Text", ffi_new_Text, 0);
jsB_propcon(J, "fz_path", "Path", ffi_new_Path, 0);
jsB_propcon(J, "fz_display_list", "DisplayList", ffi_new_DisplayList, 1);
jsB_propcon(J, "fz_device", "DrawDevice", ffi_new_DrawDevice, 2);
jsB_propcon(J, "fz_device", "DisplayListDevice", ffi_new_DisplayListDevice, 1);
jsB_propcon(J, "fz_document_writer", "DocumentWriter", ffi_new_DocumentWriter, 3);
jsB_propfun(J, "readFile", ffi_readFile, 1);
js_getregistry(J, "DeviceGray");
js_defproperty(J, -2, "DeviceGray", JS_DONTENUM | JS_READONLY | JS_DONTCONF);
js_getregistry(J, "DeviceRGB");
js_defproperty(J, -2, "DeviceRGB", JS_DONTENUM | JS_READONLY | JS_DONTCONF);
js_getregistry(J, "DeviceBGR");
js_defproperty(J, -2, "DeviceBGR", JS_DONTENUM | JS_READONLY | JS_DONTCONF);
js_getregistry(J, "DeviceCMYK");
js_defproperty(J, -2, "DeviceCMYK", JS_DONTENUM | JS_READONLY | JS_DONTCONF);
jsB_propfun(J, "setUserCSS", ffi_setUserCSS, 2);
}
/* re-implement matrix math in javascript */
js_dostring(J, "var Identity = Object.freeze([1,0,0,1,0,0]);");
js_dostring(J, "function Scale(sx,sy) { return [sx,0,0,sy,0,0]; }");
js_dostring(J, "function Translate(tx,ty) { return [1,0,0,1,tx,ty]; }");
js_dostring(J, "function Concat(a,b) { return ["
"a[0] * b[0] + a[1] * b[2],"
"a[0] * b[1] + a[1] * b[3],"
"a[2] * b[0] + a[3] * b[2],"
"a[2] * b[1] + a[3] * b[3],"
"a[4] * b[0] + a[5] * b[2] + b[4],"
"a[4] * b[1] + a[5] * b[3] + b[5]];}");
if (argc > 1) {
js_pushstring(J, argv[1]);
js_setglobal(J, "scriptPath");
js_newarray(J);
for (i = 2; i < argc; ++i) {
js_pushstring(J, argv[i]);
js_setindex(J, -2, i - 2);
}
js_setglobal(J, "scriptArgs");
if (js_dofile(J, argv[1]))
{
js_freestate(J);
fz_drop_context(ctx);
return 1;
}
} else {
char line[256];
fputs(PS1, stdout);
while (fgets(line, sizeof line, stdin)) {
eval_print(J, line);
fputs(PS1, stdout);
}
putchar('\n');
}
js_freestate(J);
fz_drop_context(ctx);
return 0;
}
#endif
|
muennich/mupdf
|
source/tools/murun.c
|
C
|
agpl-3.0
| 123,394
|
class AccessToken < ActiveRecord::Base
attr_reader :full_token
belongs_to :developer_key
belongs_to :user
attr_accessible :user, :purpose, :expires_at, :developer_key, :regenerate, :scopes, :remember_access
serialize :scopes, Array
validate :must_only_include_valid_scopes
# For user-generated tokens, purpose can be manually set.
# For app-generated tokens, this should be generated based
# on the scope defined in the auth process (scope has not
# yet been implemented)
scope :active, lambda { where("expires_at IS NULL OR expires_at>?", Time.zone.now) }
TOKEN_SIZE = 64
OAUTH2_SCOPE_NAMESPACE = '/auth/'
ALLOWED_SCOPES = ["#{OAUTH2_SCOPE_NAMESPACE}userinfo"]
before_create :generate_token
def self.authenticate(token_string)
token = self.where(:crypted_token => hashed_token(token_string)).first
token = nil unless token.try(:usable?)
token
end
def self.hashed_token(token)
# This use of hmac is a bit odd, since we aren't really signing a message
# other than the random token string itself.
# However, what we're essentially looking for is a hash of the token
# "signed" or concatenated with the secret encryption key, so this is perfect.
Canvas::Security.hmac_sha1(token)
end
def usable?
user_id && !expired?
end
def app_name
developer_key.try(:name) || "No App"
end
def record_last_used_threshold
Setting.get('access_token_last_used_threshold', 10.minutes).to_i
end
def used!
if !last_used_at || last_used_at < record_last_used_threshold.ago
self.last_used_at = Time.now
self.save
end
end
def expired?
expires_at && expires_at < Time.now
end
def token=(new_token)
self.crypted_token = AccessToken.hashed_token(new_token)
@full_token = new_token
self.token_hint = new_token[0,5]
end
def clear_full_token!
@full_token = nil
end
def generate_token(overwrite=false)
if overwrite || !self.crypted_token
self.token = AutoHandle.generate(nil, TOKEN_SIZE)
end
end
def protected_token?
developer_key != DeveloperKey.default
end
def regenerate=(val)
if val == '1' && !protected_token?
generate_token(true)
end
end
def visible_token
if protected_token?
nil
elsif full_token
full_token
else
"#{token_hint}..."
end
end
#Scoped token convenience method
def scoped_to?(req_scopes)
return req_scopes.size == 0 if scopes.nil?
scopes.size == req_scopes.size &&
scopes.all? do |scope|
req_scopes.any? {|req_scope| scope[/(^|\/)#{req_scope}$/]}
end
end
def must_only_include_valid_scopes
return true if scopes.nil?
errors.add(:scopes, "must match accepted scopes") unless scopes.all? {|scope| ALLOWED_SCOPES.include?(scope)}
end
# It's encrypted, but end users still shouldn't see this.
# The hint is only returned in visible_token, if protected_token is false.
def self.serialization_excludes; [:crypted_token, :token_hint]; end
end
|
loganrun/pincan
|
app/models/access_token.rb
|
Ruby
|
agpl-3.0
| 3,027
|
# -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import logging
import superdesk
from flask import current_app as app
from settings import DAYS_TO_KEEP
from datetime import timedelta
from werkzeug.exceptions import HTTPException
from superdesk.notification import push_notification
from superdesk.io import providers
from superdesk.celery_app import celery
from superdesk.utc import utcnow
from superdesk.workflow import set_default_state
from superdesk.errors import ProviderError
from superdesk.stats import stats
from superdesk.upload import url_for_media
from superdesk.media.media_operations import download_file_from_url, process_file
from superdesk.media.renditions import generate_renditions
UPDATE_SCHEDULE_DEFAULT = {'minutes': 5}
LAST_UPDATED = 'last_updated'
STATE_INGESTED = 'ingested'
logger = logging.getLogger(__name__)
superdesk.workflow_state(STATE_INGESTED)
superdesk.workflow_action(
name='ingest'
)
def is_valid_type(provider, provider_type_filter=None):
"""Test if given provider has valid type and should be updated.
:param provider: provider to be updated
:param provider_type_filter: active provider type filter
"""
provider_type = provider.get('type')
if provider_type not in providers:
return False
if provider_type_filter and provider_type != provider_type_filter:
return False
return True
def is_scheduled(provider):
"""Test if given provider should be scheduled for update.
:param provider: ingest provider
"""
now = utcnow()
last_updated = provider.get(LAST_UPDATED, now - timedelta(days=100)) # if never updated run now
update_schedule = provider.get('update_schedule', UPDATE_SCHEDULE_DEFAULT)
return last_updated + timedelta(**update_schedule) < now
def is_closed(provider):
"""Test if provider is closed.
:param provider: ingest provider
"""
return provider.get('is_closed', False)
def filter_expired_items(provider, items):
try:
days_to_keep_content = provider.get('days_to_keep', DAYS_TO_KEEP)
expiration_date = utcnow() - timedelta(days=days_to_keep_content)
return [item for item in items if item.get('versioncreated', utcnow()) > expiration_date]
except Exception as ex:
raise ProviderError.providerFilterExpiredContentError(ex, provider)
def get_provider_rule_set(provider):
if provider.get('rule_set'):
return superdesk.get_resource_service('rule_sets').find_one(_id=provider['rule_set'], req=None)
def get_task_ttl(provider):
update_schedule = provider.get('update_schedule', UPDATE_SCHEDULE_DEFAULT)
return update_schedule.get('minutes', 0) * 60 + update_schedule.get('hours', 0) * 3600
def get_task_id(provider):
return 'update-ingest-{0}-{1}'.format(provider.get('name'), provider.get('_id'))
class UpdateIngest(superdesk.Command):
"""Update ingest providers."""
option_list = (
superdesk.Option('--provider', '-p', dest='provider_type'),
)
def run(self, provider_type=None):
for provider in superdesk.get_resource_service('ingest_providers').get(req=None, lookup={}):
if is_valid_type(provider, provider_type) and is_scheduled(provider) and not is_closed(provider):
kwargs = {
'provider': provider,
'rule_set': get_provider_rule_set(provider)
}
update_provider.apply_async(
task_id=get_task_id(provider),
expires=get_task_ttl(provider),
kwargs=kwargs)
@celery.task
def update_provider(provider, rule_set=None):
"""
Fetches items from ingest provider as per the configuration, ingests them into Superdesk and
updates the provider.
"""
superdesk.get_resource_service('ingest_providers').update(provider['_id'], {
LAST_UPDATED: utcnow(),
# Providing the _etag as system updates to the documents shouldn't override _etag.
app.config['ETAG']: provider.get(app.config['ETAG'])
})
for items in providers[provider.get('type')].update(provider):
ingest_items(items, provider, rule_set)
stats.incr('ingest.ingested_items', len(items))
logger.info('Provider {0} updated'.format(provider['_id']))
push_notification('ingest:update')
def process_anpa_category(item, provider):
try:
anpa_categories = superdesk.get_resource_service('vocabularies').find_one(req=None, _id='categories')
if anpa_categories:
for anpa_category in anpa_categories['items']:
if anpa_category['is_active'] is True \
and item['anpa-category']['qcode'].lower() == anpa_category['value'].lower():
item['anpa-category'] = {'qcode': item['anpa-category']['qcode'], 'name': anpa_category['name']}
break
except Exception as ex:
raise ProviderError.anpaError(ex, provider)
def apply_rule_set(item, provider, rule_set=None):
"""
Applies rules set on the item to be ingested into the system. If there's no rule set then the item will
be returned without any change.
:param item: Item to be ingested
:param provider: provider object from whom the item was received
:return: item
"""
try:
if rule_set is None and provider.get('rule_set') is not None:
rule_set = superdesk.get_resource_service('rule_sets').find_one(_id=provider['rule_set'], req=None)
if rule_set and 'body_html' in item:
body = item['body_html']
for rule in rule_set['rules']:
body = body.replace(rule['old'], rule['new'])
item['body_html'] = body
return item
except Exception as ex:
raise ProviderError.ruleError(ex, provider)
def ingest_items(items, provider, rule_set=None):
all_items = filter_expired_items(provider, items)
items_dict = {doc['guid']: doc for doc in all_items}
for item in [doc for doc in all_items if doc.get('type') != 'composite']:
ingest_item(item, provider, rule_set)
for item in [doc for doc in all_items if doc.get('type') == 'composite']:
for ref in [ref for group in item.get('groups', [])
for ref in group.get('refs', []) if 'residRef' in ref]:
ref.setdefault('location', 'ingest')
itemRendition = items_dict.get(ref['residRef'], {}).get('renditions')
if itemRendition:
ref.setdefault('renditions', itemRendition)
ingest_item(item, provider, rule_set)
def ingest_item(item, provider, rule_set=None):
try:
item.setdefault('_id', item['guid'])
providers[provider.get('type')].provider = provider
item['ingest_provider'] = str(provider['_id'])
item.setdefault('source', provider.get('source', ''))
set_default_state(item, STATE_INGESTED)
if 'anpa-category' in item:
process_anpa_category(item, provider)
apply_rule_set(item, provider, rule_set)
ingest_service = superdesk.get_resource_service('ingest')
if item.get('ingest_provider_sequence') is None:
ingest_service.set_ingest_provider_sequence(item, provider)
rend = item.get('renditions', {})
if rend:
baseImageRend = rend.get('baseImage') or next(iter(rend.values()))
if baseImageRend:
href = providers[provider.get('type')].prepare_href(baseImageRend['href'])
update_renditions(item, href)
old_item = ingest_service.find_one(_id=item['guid'], req=None)
if old_item:
ingest_service.put(item['guid'], item)
else:
try:
ingest_service.post([item])
except HTTPException as e:
logger.error("Exception while persisting item in ingest collection", e)
ingest_service.put(item['guid'], item)
except ProviderError:
raise
except Exception as ex:
raise ProviderError.ingestError(ex, provider)
def update_renditions(item, href):
inserted = []
try:
content, filename, content_type = download_file_from_url(href)
file_type, ext = content_type.split('/')
metadata = process_file(content, file_type)
file_guid = app.media.put(content, filename, content_type, metadata)
inserted.append(file_guid)
rendition_spec = app.config.get('RENDITIONS', {}).get('picture', {})
renditions = generate_renditions(content, file_guid, inserted, file_type,
content_type, rendition_spec, url_for_media)
item['renditions'] = renditions
item['mimetype'] = content_type
item['filemeta'] = metadata
except Exception as io:
logger.exception(io)
for file_id in inserted:
app.media.delete(file_id)
raise
superdesk.command('ingest:update', UpdateIngest())
|
petrjasek/superdesk-server
|
superdesk/io/commands/update_ingest.py
|
Python
|
agpl-3.0
| 9,268
|
using wServer.realm.worlds;
namespace wServer.realm.setpieces
{
class GhostShip : ISetPiece
{
public int Size { get { return 40; } }
public void RenderSetPiece(World world, IntPoint pos)
{
var proto = world.Manager.Resources.Worlds["GhostShip"];
SetPieces.RenderFromProto(world, pos, proto);
}
}
}
|
cp-nilly/NR-CORE
|
wServer/realm/setpieces/GhostShip.cs
|
C#
|
agpl-3.0
| 371
|
"""
A Python "serializer". Doesn't do much serializing per se -- just converts to
and from basic Python data types (lists, dicts, strings, etc.). Useful as a basis for
other serializers.
"""
from __future__ import unicode_literals
from django.conf import settings
from keops.core.serializers import base
from django.db import models, DEFAULT_DB_ALIAS
from django.utils.encoding import smart_text, is_protected_type
from django.utils import six
class Serializer(base.Serializer):
"""
Serializes a QuerySet to basic Python objects.
"""
internal_use_only = True
def start_serialization(self):
self._current = None
self.objects = []
def end_serialization(self):
pass
def start_object(self, obj):
self._current = {}
def end_object(self, obj):
self.objects.append(self.get_dump_object(obj))
self._current = None
def get_dump_object(self, obj):
return {
"pk": smart_text(obj._get_pk_val(), strings_only=True),
"model": smart_text(obj._meta),
"fields": self._current
}
def handle_field(self, obj, field):
value = field._get_val_from_obj(obj)
# Protected types (i.e., primitives like None, numbers, dates,
# and Decimals) are passed through as is. All other values are
# converted to string first.
if is_protected_type(value):
self._current[field.name] = value
else:
self._current[field.name] = field.value_to_string(obj)
def handle_fk_field(self, obj, field):
if self.use_natural_keys and hasattr(field.rel.to, 'natural_key'):
related = getattr(obj, field.name)
if related:
value = related.natural_key()
else:
value = None
else:
value = getattr(obj, field.get_attname())
self._current[field.name] = value
def handle_m2m_field(self, obj, field):
if field.rel.through._meta.auto_created:
if self.use_natural_keys and hasattr(field.rel.to, 'natural_key'):
m2m_value = lambda value: value.natural_key()
else:
m2m_value = lambda value: smart_text(value._get_pk_val(), strings_only=True)
self._current[field.name] = [m2m_value(related)
for related in getattr(obj, field.name).iterator()]
def getvalue(self):
return self.objects
def Deserializer(object_list, **options):
"""
Deserialize simple Python objects back into Django ORM instances.
It's expected that you pass the Python objects themselves (instead of a
stream or a string) to the constructor
"""
db = options.pop('using', DEFAULT_DB_ALIAS)
ignore = options.pop('ignorenonexistent', True)
models.get_apps()
for d in object_list:
# Look up the model and starting build a dict of data for it.
Model = _get_model(d["model"])
data = {Model._meta.pk.attname: Model._meta.pk.to_python(d.get("pk"))}
rec = _id = None
if 'data-id' in d:
_id = d.pop('data-id')
from keops.modules.base.models import ModelData
try:
obj = ModelData.objects.using(db).get(name=_id)
rec = obj.content_object
except:
obj = ModelData(name=_id)
_id = obj
m2m_data = {}
model_fields = Model._meta.get_all_field_names()
# Handle each field
for (field_name, field_value) in six.iteritems(d["fields"]):
if isinstance(field_value, str):
field_value = smart_text(field_value, options.get("encoding", settings.DEFAULT_CHARSET), strings_only=True)
if field_name not in model_fields:
# skip fields no longer on model
data[field_name] = field_value
continue
field = Model._meta.get_field(field_name)
# Handle M2M relations
if field.rel and isinstance(field.rel, models.ManyToManyRel):
if hasattr(field.rel.to._default_manager, 'get_by_natural_key'):
def m2m_convert(value):
if hasattr(value, '__iter__') and not isinstance(value, six.text_type):
return field.rel.to._default_manager.db_manager(db).get_by_natural_key(*value).pk
else:
return smart_text(field.rel.to._meta.pk.to_python(value))
else:
m2m_convert = lambda v: smart_text(field.rel.to._meta.pk.to_python(v))
m2m_data[field.name] = [m2m_convert(pk) for pk in field_value]
# Handle FK fields
elif field.rel and isinstance(field.rel, models.ManyToOneRel):
if field_value is not None:
if isinstance(field_value, dict):
obj = field.rel.to.objects.db_manager(db).only('id').filter(**field_value)[0]
data[field.attname] = obj.pk
elif hasattr(field.rel.to._default_manager, 'get_by_natural_key'):
if hasattr(field_value, '__iter__') and not isinstance(field_value, six.text_type):
obj = field.rel.to._default_manager.db_manager(db).get_by_natural_key(*field_value)
value = getattr(obj, field.rel.field_name)
# If this is a natural foreign key to an object that
# has a FK/O2O as the foreign key, use the FK value
if field.rel.to._meta.pk.rel:
value = value.pk
else:
value = field.rel.to._meta.get_field(field.rel.field_name).to_python(field_value)
data[field.attname] = value
else:
data[field.attname] = field.rel.to._meta.get_field(field.rel.field_name).to_python(field_value)
else:
data[field.attname] = None
# Handle all other fields
else:
data[field.name] = field.to_python(field_value)
if not rec:
rec = Model()
rec._state.db = db
for k, v in data.items():
setattr(rec, k, v)
rec.save(using=db, update_fields=None)
if _id:
_id.content_object = rec
_id.save(using=db, update_fields=None)
yield base.DeserializedObject(rec, m2m_data)
def _get_model(model_identifier):
"""
Helper to look up a model from an "app_label.model_name" string.
"""
try:
Model = models.get_model(*model_identifier.split("."))
except TypeError:
Model = None
if Model is None:
raise base.DeserializationError("Invalid model identifier: '%s'" % model_identifier)
return Model
|
mrmuxl/keops
|
keops/core/serializers/python.py
|
Python
|
agpl-3.0
| 6,979
|
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.4.0
* @package Slim
*
* MIT LICENSE
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Slim\Http;
/**
* Slim HTTP Request
*
* This class provides a human-friendly interface to the Slim environment variables;
* environment variables are passed by reference and will be modified directly.
*
* @package Slim
* @author Josh Lockhart
* @since 1.0.0
*/
class Request {
const METHOD_HEAD = 'HEAD';
const METHOD_GET = 'GET';
const METHOD_POST = 'POST';
const METHOD_PUT = 'PUT';
const METHOD_PATCH = 'PATCH';
const METHOD_DELETE = 'DELETE';
const METHOD_OPTIONS = 'OPTIONS';
const METHOD_OVERRIDE = '_METHOD';
/**
* @var array
*/
protected static $formDataMediaTypes = array('application/x-www-form-urlencoded');
/**
* Application Environment
* @var \Slim\Environment
*/
protected $env;
/**
* HTTP Headers
* @var \Slim\Http\Headers
*/
public $headers;
/**
* HTTP Cookies
* @var \Slim\Helper\Set
*/
public $cookies;
/**
* Constructor
* @param \Slim\Environment $env
*/
public function __construct(\Slim\Environment $env) {
$this->env = $env;
$this->headers = new \Slim\Http\Headers(\Slim\Http\Headers::extract($env));
$this->cookies = new \Slim\Helper\Set(\Slim\Http\Util::parseCookieHeader($env['HTTP_COOKIE']));
}
/**
* Get HTTP method
* @return string
*/
public function getMethod() {
return $this->env['REQUEST_METHOD'];
}
/**
* Is this a GET request?
* @return bool
*/
public function isGet() {
return $this->getMethod() === self::METHOD_GET;
}
/**
* Is this a POST request?
* @return bool
*/
public function isPost() {
return $this->getMethod() === self::METHOD_POST;
}
/**
* Is this a PUT request?
* @return bool
*/
public function isPut() {
return $this->getMethod() === self::METHOD_PUT;
}
/**
* Is this a PATCH request?
* @return bool
*/
public function isPatch() {
return $this->getMethod() === self::METHOD_PATCH;
}
/**
* Is this a DELETE request?
* @return bool
*/
public function isDelete() {
return $this->getMethod() === self::METHOD_DELETE;
}
/**
* Is this a HEAD request?
* @return bool
*/
public function isHead() {
return $this->getMethod() === self::METHOD_HEAD;
}
/**
* Is this a OPTIONS request?
* @return bool
*/
public function isOptions() {
return $this->getMethod() === self::METHOD_OPTIONS;
}
/**
* Is this an AJAX request?
* @return bool
*/
public function isAjax() {
if ($this->params('isajax')) {
return true;
} elseif (isset($this->headers['X_REQUESTED_WITH']) && $this->headers['X_REQUESTED_WITH'] === 'XMLHttpRequest') {
return true;
} else {
return false;
}
}
/**
* Is this an XHR request? (alias of Slim_Http_Request::isAjax)
* @return bool
*/
public function isXhr() {
return $this->isAjax();
}
/**
* Fetch GET and POST data
*
* This method returns a union of GET and POST data as a key-value array, or the value
* of the array key if requested; if the array key does not exist, NULL is returned.
*
* @param string $key
* @return array|mixed|null
*/
public function params($key = null) {
$union = array_merge($this->get(), $this->post());
if ($key) {
return isset($union[$key]) ? $union[$key] : null;
}
return $union;
}
/**
* Fetch GET data
*
* This method returns a key-value array of data sent in the HTTP request query string, or
* the value of the array key if requested; if the array key does not exist, NULL is returned.
*
* @param string $key
* @param mixed $default Default return value when key does not exist
* @return array|mixed|null
*/
public function get($key = null, $default = null) {
if (!isset($this->env['slim.request.query_hash'])) {
$output = array();
if (function_exists('mb_parse_str') && !isset($this->env['slim.tests.ignore_multibyte'])) {
mb_parse_str($this->env['QUERY_STRING'], $output);
} else {
parse_str($this->env['QUERY_STRING'], $output);
}
$this->env['slim.request.query_hash'] = Util::stripSlashesIfMagicQuotes($output);
}
if ($key) {
if (isset($this->env['slim.request.query_hash'][$key])) {
return $this->env['slim.request.query_hash'][$key];
} else {
return $default;
}
} else {
return $this->env['slim.request.query_hash'];
}
}
/**
* Fetch POST data
*
* This method returns a key-value array of data sent in the HTTP request body, or
* the value of a hash key if requested; if the array key does not exist, NULL is returned.
*
* @param string $key
* @param mixed $default Default return value when key does not exist
* @return array|mixed|null
* @throws \RuntimeException If environment input is not available
*/
public function post($key = null, $default = null) {
if (!isset($this->env['slim.input'])) {
throw new \RuntimeException('Missing slim.input in environment variables');
}
if (!isset($this->env['slim.request.form_hash'])) {
$this->env['slim.request.form_hash'] = array();
if ($this->isFormData() && is_string($this->env['slim.input'])) {
$output = array();
if (function_exists('mb_parse_str') && !isset($this->env['slim.tests.ignore_multibyte'])) {
mb_parse_str($this->env['slim.input'], $output);
} else {
parse_str($this->env['slim.input'], $output);
}
$this->env['slim.request.form_hash'] = Util::stripSlashesIfMagicQuotes($output);
} else {
$this->env['slim.request.form_hash'] = Util::stripSlashesIfMagicQuotes($_POST);
}
}
if ($key) {
if (isset($this->env['slim.request.form_hash'][$key])) {
return $this->env['slim.request.form_hash'][$key];
} else {
return $default;
}
} else {
return $this->env['slim.request.form_hash'];
}
}
/**
* Fetch PUT data (alias for \Slim\Http\Request::post)
* @param string $key
* @param mixed $default Default return value when key does not exist
* @return array|mixed|null
*/
public function put($key = null, $default = null) {
return $this->post($key, $default);
}
/**
* Fetch PATCH data (alias for \Slim\Http\Request::post)
* @param string $key
* @param mixed $default Default return value when key does not exist
* @return array|mixed|null
*/
public function patch($key = null, $default = null) {
return $this->post($key, $default);
}
/**
* Fetch DELETE data (alias for \Slim\Http\Request::post)
* @param string $key
* @param mixed $default Default return value when key does not exist
* @return array|mixed|null
*/
public function delete($key = null, $default = null) {
return $this->post($key, $default);
}
/**
* Fetch COOKIE data
*
* This method returns a key-value array of Cookie data sent in the HTTP request, or
* the value of a array key if requested; if the array key does not exist, NULL is returned.
*
* @param string $key
* @return array|string|null
*/
public function cookies($key = null) {
if ($key) {
return $this->cookies->get($key);
}
return $this->cookies;
// if (!isset($this->env['slim.request.cookie_hash'])) {
// $cookieHeader = isset($this->env['COOKIE']) ? $this->env['COOKIE'] : '';
// $this->env['slim.request.cookie_hash'] = Util::parseCookieHeader($cookieHeader);
// }
// if ($key) {
// if (isset($this->env['slim.request.cookie_hash'][$key])) {
// return $this->env['slim.request.cookie_hash'][$key];
// } else {
// return null;
// }
// } else {
// return $this->env['slim.request.cookie_hash'];
// }
}
/**
* Does the Request body contain parsed form data?
* @return bool
*/
public function isFormData() {
$method = isset($this->env['slim.method_override.original_method']) ? $this->env['slim.method_override.original_method'] : $this->getMethod();
return ($method === self::METHOD_POST && is_null($this->getContentType())) || in_array($this->getMediaType(), self::$formDataMediaTypes);
}
/**
* Get Headers
*
* This method returns a key-value array of headers sent in the HTTP request, or
* the value of a hash key if requested; if the array key does not exist, NULL is returned.
*
* @param string $key
* @param mixed $default The default value returned if the requested header is not available
* @return mixed
*/
public function headers($key = null, $default = null) {
if ($key) {
return $this->headers->get($key, $default);
}
return $this->headers;
// if ($key) {
// $key = strtoupper($key);
// $key = str_replace('-', '_', $key);
// $key = preg_replace('@^HTTP_@', '', $key);
// if (isset($this->env[$key])) {
// return $this->env[$key];
// } else {
// return $default;
// }
// } else {
// $headers = array();
// foreach ($this->env as $key => $value) {
// if (strpos($key, 'slim.') !== 0) {
// $headers[$key] = $value;
// }
// }
//
// return $headers;
// }
}
/**
* Get Body
* @return string
*/
public function getBody() {
return $this->env['slim.input'];
}
/**
* Get Content Type
* @return string|null
*/
public function getContentType() {
return $this->headers->get('CONTENT_TYPE');
}
/**
* Get Media Type (type/subtype within Content Type header)
* @return string|null
*/
public function getMediaType() {
$contentType = $this->getContentType();
if ($contentType) {
$contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType);
return strtolower($contentTypeParts[0]);
}
return null;
}
/**
* Get Media Type Params
* @return array
*/
public function getMediaTypeParams() {
$contentType = $this->getContentType();
$contentTypeParams = array();
if ($contentType) {
$contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType);
$contentTypePartsLength = count($contentTypeParts);
for ($i = 1; $i < $contentTypePartsLength; $i++) {
$paramParts = explode('=', $contentTypeParts[$i]);
$contentTypeParams[strtolower($paramParts[0])] = $paramParts[1];
}
}
return $contentTypeParams;
}
/**
* Get Content Charset
* @return string|null
*/
public function getContentCharset() {
$mediaTypeParams = $this->getMediaTypeParams();
if (isset($mediaTypeParams['charset'])) {
return $mediaTypeParams['charset'];
}
return null;
}
/**
* Get Content-Length
* @return int
*/
public function getContentLength() {
return $this->headers->get('CONTENT_LENGTH', 0);
}
/**
* Get Host
* @return string
*/
public function getHost() {
if (isset($this->env['HTTP_HOST'])) {
if (strpos($this->env['HTTP_HOST'], ':') !== false) {
$hostParts = explode(':', $this->env['HTTP_HOST']);
return $hostParts[0];
}
return $this->env['HTTP_HOST'];
}
return $this->env['SERVER_NAME'];
}
/**
* Get Host with Port
* @return string
*/
public function getHostWithPort() {
return sprintf('%s:%s', $this->getHost(), $this->getPort());
}
/**
* Get Port
* @return int
*/
public function getPort() {
return (int) $this->env['SERVER_PORT'];
}
/**
* Get Scheme (https or http)
* @return string
*/
public function getScheme() {
return $this->env['slim.url_scheme'];
}
/**
* Get Script Name (physical path)
* @return string
*/
public function getScriptName() {
return $this->env['SCRIPT_NAME'];
}
/**
* LEGACY: Get Root URI (alias for Slim_Http_Request::getScriptName)
* @return string
*/
public function getRootUri() {
return $this->getScriptName();
}
/**
* Get Path (physical path + virtual path)
* @return string
*/
public function getPath() {
return $this->getScriptName() . $this->getPathInfo();
}
/**
* Get Path Info (virtual path)
* @return string
*/
public function getPathInfo() {
return $this->env['PATH_INFO'];
}
/**
* LEGACY: Get Resource URI (alias for Slim_Http_Request::getPathInfo)
* @return string
*/
public function getResourceUri() {
return $this->getPathInfo();
}
/**
* Get URL (scheme + host [ + port if non-standard ])
* @return string
*/
public function getUrl() {
$url = $this->getScheme() . '://' . $this->getHost();
if (($this->getScheme() === 'https' && $this->getPort() !== 443) || ($this->getScheme() === 'http' && $this->getPort() !== 80)) {
$url .= sprintf(':%s', $this->getPort());
}
return $url;
}
/**
* Get IP
* @return string
*/
public function getIp() {
if (isset($this->env['X_FORWARDED_FOR'])) {
return $this->env['X_FORWARDED_FOR'];
} elseif (isset($this->env['CLIENT_IP'])) {
return $this->env['CLIENT_IP'];
}
return $this->env['REMOTE_ADDR'];
}
/**
* Get Referrer
* @return string|null
*/
public function getReferrer() {
return $this->headers->get('HTTP_REFERER');
}
/**
* Get Referer (for those who can't spell)
* @return string|null
*/
public function getReferer() {
return $this->getReferrer();
}
/**
* Get User Agent
* @return string|null
*/
public function getUserAgent() {
return $this->headers->get('HTTP_USER_AGENT');
}
}
|
Davidfvkun/My-Freak-List
|
vendor/slim/slim/Slim/Http/Request.php
|
PHP
|
agpl-3.0
| 16,622
|
/*
* TeleStax, Open Source Cloud Communications Copyright 2012.
* and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.restcomm.protocols.ss7.m3ua.impl;
import javolution.util.FastList;
import org.apache.log4j.Logger;
import org.restcomm.protocols.ss7.m3ua.M3UAManagementEventListener;
import org.restcomm.protocols.ss7.m3ua.State;
import org.restcomm.protocols.ss7.m3ua.impl.fsm.FSM;
import org.restcomm.protocols.ss7.m3ua.impl.fsm.FSMState;
import org.restcomm.protocols.ss7.m3ua.impl.fsm.FSMStateEventHandler;
/**
*
* @author amit bhayani
*
*/
public abstract class SEHAsStateEnterPen implements FSMStateEventHandler {
private static final Logger logger = Logger.getLogger(SEHAsStateEnterPen.class);
protected AsImpl asImpl = null;
private FSM fsm;
public SEHAsStateEnterPen(AsImpl asImpl, FSM fsm) {
this.asImpl = asImpl;
this.fsm = fsm;
}
public void onEvent(FSMState state) {
if (logger.isDebugEnabled()) {
logger.debug(String.format("Entered in PENDING state for As=%s", asImpl.getName()));
}
if (!this.asImpl.state.getName().equals(State.STATE_PENDING)) {
AsState oldState = AsState.getState(this.asImpl.state.getName());
this.asImpl.state = AsState.PENDING;
FastList<M3UAManagementEventListener> managementEventListenersTmp = this.asImpl.m3UAManagementImpl.managementEventListeners;
for (FastList.Node<M3UAManagementEventListener> n = managementEventListenersTmp.head(), end = managementEventListenersTmp
.tail(); (n = n.getNext()) != end;) {
M3UAManagementEventListener m3uaManagementEventListener = n.getValue();
try {
m3uaManagementEventListener.onAsPending(this.asImpl, oldState);
} catch (Throwable ee) {
logger.error("Exception while invoking onAsPending", ee);
}
}
}
}
}
|
RestComm/jss7
|
m3ua/impl/src/main/java/org/restcomm/protocols/ss7/m3ua/impl/SEHAsStateEnterPen.java
|
Java
|
agpl-3.0
| 2,859
|
import {
createStyles,
FormControl,
Input,
InputAdornment,
InputLabel,
Theme,
WithStyles,
} from '@material-ui/core';
import Button from '@material-ui/core/Button';
import Divider from '@material-ui/core/Divider';
import IconButton from '@material-ui/core/IconButton';
import Paper from '@material-ui/core/Paper';
import { withStyles } from '@material-ui/core/styles';
import TextField from '@material-ui/core/TextField';
import Typography from '@material-ui/core/Typography';
import Visibility from '@material-ui/icons/Visibility';
import VisibilityOff from '@material-ui/icons/VisibilityOff';
import cookie from 'cookie';
import { gql, FetchResult, useMutation, useApolloClient } from '@apollo/client';
import React, { FormEventHandler } from 'react';
import redirect from '@olimat/web/utils/redirect';
import Link from '../Link';
const styles = (theme: Theme) =>
createStyles({
signUpBox: {
position: 'relative',
width: 350,
// maxHeight: 390,
padding: theme.spacing(4),
},
signUpHead: {
marginBottom: theme.spacing(2),
textAlign: 'center',
},
passwordInput: {
height: 'inherit',
},
signUpButton: {
marginTop: theme.spacing(2),
},
helpMessage: {
marginTop: theme.spacing(2),
},
});
interface Props extends WithStyles<typeof styles> {}
const signUpMutation = gql`
mutation signUpMutation($name: String!, $email: String!, $password: String!) {
signup(name: $name, email: $email, password: $password) {
token
}
}
`;
const SignUpForm: React.FC<Props> = (props) => {
const [state, setState] = React.useState({
password: '',
showPassword: false,
});
const [tryToSignUp, {}] = useMutation<Response, Variables>(signUpMutation);
const client = useApolloClient();
const handleCreateUser: FormEventHandler<HTMLFormElement> = (event) => {
/* global FormData */
const data = new FormData(event.currentTarget);
event.preventDefault();
event.stopPropagation();
tryToSignUp({
variables: {
email: data.get('email').toString(),
password: data.get('password').toString(),
name: data.get('name').toString(),
},
})
.then(
({
data: {
signup: { token },
},
}: FetchResult<Response>) => {
// Store the token in cookie
document.cookie = cookie.serialize('token', token, {
maxAge: 30 * 24 * 60 * 60, // 30 days
});
// Force a reload of all the current queries now that the user is
// logged in
client.resetStore().then(() => {
// Now redirect to the homepage
redirect({}, '/');
});
},
)
.catch((error) => {
// Something went wrong, such as incorrect password, or no network
// available, etc.
console.error(error);
});
};
const handleChange = (prop) => (event) => {
event.persist();
setState((state) => ({ ...state, [prop]: event.target.value }));
};
const handleMouseDownPassword = (event) => {
event.preventDefault();
};
const handleClickShowPasssword = () => {
setState((state) => ({ ...state, showPassword: !state.showPassword }));
};
const { classes } = props;
return (
<Paper className={classes.signUpBox}>
<Typography className={classes.signUpHead} variant="h5">
Crie uma conta!
</Typography>
<Divider />
<form onSubmit={handleCreateUser}>
<TextField
id="name"
name="name"
label="Nome"
margin="normal"
fullWidth
onChange={handleChange('name')}
/>
<TextField
id="email"
name="email"
label="Email"
margin="normal"
fullWidth
onChange={handleChange('email')}
/>
<TextField
id="confirmEmail"
name="confirmEmail"
label="Confirmar email"
margin="normal"
fullWidth
onChange={handleChange('confirmEmail')}
/>
<FormControl fullWidth margin="normal">
<InputLabel htmlFor="password">Senha</InputLabel>
<Input
id="password"
name="password"
inputProps={{ className: classes.passwordInput }}
type={state.showPassword ? 'text' : 'password'}
value={state.password}
onChange={handleChange('password')}
endAdornment={
<InputAdornment position="end">
<IconButton
style={{ width: 'auto' }}
onClick={handleClickShowPasssword}
onMouseDown={handleMouseDownPassword}
>
{state.showPassword ? <VisibilityOff /> : <Visibility />}
</IconButton>
</InputAdornment>
}
/>
</FormControl>
<Button
aria-label="Criar conta"
className={classes.signUpButton}
fullWidth
variant="contained"
color="secondary"
size="large"
type="submit"
>
Criar conta
</Button>
</form>
<Typography
className={classes.helpMessage}
variant="caption"
align="center"
>
Já possui uma conta?{' '}
<Link color="primary" href="/login">
Faça login aqui.
</Link>
</Typography>
</Paper>
);
};
interface Response {
signup: {
token: string;
};
}
interface Variables {
name: string;
email: string;
password: string;
}
export default withStyles(styles)(SignUpForm);
|
iquabius/olimat
|
packages/web/src/components/User/SignUpForm.tsx
|
TypeScript
|
agpl-3.0
| 5,100
|
# == Schema Information
#
# Table name: sponsors
#
# id :integer not null, primary key
# name :string(510)
# logo_file_name :string(510)
# logo_content_type :string(510)
# logo_file_size :integer
# logo_updated_at :datetime
# website :string(510)
# sponsorable_id :integer
# created_at :datetime not null
# updated_at :datetime not null
# sponsorable_type :string
#
FactoryBot.define do
factory :sponsor do
sequence(:name) { |n| "Sponsor-#{n}" }
website { 'www.example.com' }
logo { Rack::Test::UploadedFile.new Rails.root.join('spec/support/skyderby_logo.png'), 'image/png' }
sponsorable factory: :event
end
end
|
skyderby/skyderby
|
spec/factories/sponsors.rb
|
Ruby
|
agpl-3.0
| 734
|
<?php
// created: 2011-07-20 15:47:55
$dictionary['sphr_Client']['fields']['passport_number']['required']=false;
?>
|
yonkon/nedvig
|
custom/Extension/modules/sphr_Client/Ext/Vardefs/sugarfield_passport_number.php
|
PHP
|
agpl-3.0
| 118
|
<?php
/*
* @author Anakeen
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License
* @package FDL
*/
/**
* Workflow Class Document
*
* @author Anakeen 2002
* @version $Id: Class.WDoc.php,v 1.63 2009/01/08 17:47:07 eric Exp $
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License
* @package FDL
*/
/**
*/
include_once ('FDL/Class.Doc.php');
/**
* WorkFlow Class
*/
class WDoc extends Doc
{
/**
* WDoc has its own special access depend on transition
* by default the three access are always set
*
* @var array
*/
var $acls = array(
"view",
"edit",
"delete"
);
var $usefor = 'W';
var $defDoctype = 'W';
var $defClassname = 'WDoc';
var $attrPrefix = "WF"; // prefix attribute
var $stateactivity = array(); // label of states
// --------------------------------------------------------------------
//---------------------- TRANSITION DEFINITION --------------------
var $transitions = array(); // set by childs classes
var $cycle = array(); // set by childs classes
var $autonext = array(); // set by childs classes
var $firstState = ""; // first state in workflow
var $viewnext = "list"; // view interface as select list may be (list|button)
var $nosave = array(); // states where it is not permitted to save and stay (force next state)
/**
* document instance
* @var Doc
*/
public $doc = null;
function __construct($dbaccess = '', $id = '', $res = '', $dbid = 0)
{
// first construct acl array
$ka = POS_WF;
foreach ($this->transitions as $k => $trans) {
$this->dacls[$k] = array(
"pos" => $ka,
"description" => _($k)
);
$this->acls[] = $k;
$ka++;
}
if (isset($this->fromid)) $this->defProfFamId = $this->fromid; // it's a profil itself
// don't use Doc constructor because it could call this constructor => infinitive loop
DocCtrl::__construct($dbaccess, $id, $res, $dbid);
}
/**
* affect document instance
* @param Doc $doc
*/
function set(Doc & $doc)
{
if ((!isset($this->doc)) || ($this->doc->id != $doc->id)) {
$this->doc = & $doc;
if (($doc->doctype != 'C') && ($doc->state == "")) {
$doc->state = $this->getFirstState();
$this->changeProfil($doc->state);
$this->changeCv($doc->state);
}
}
}
function getFirstState()
{
return $this->firstState;
}
/**
* change profil according to state
* @param string $newstate new state of document
*/
function changeProfil($newstate)
{
if ($newstate != "") {
$profid = $this->getValue($this->_Aid("_ID", $newstate));
if (!is_numeric($profid)) $profid = getIdFromName($this->dbaccess, $profid);
if ($profid > 0) {
// change only if new profil
$err = $this->doc->setProfil($profid);
}
}
return $err;
}
/**
* change allocate user according to state
* @param string $newstate new state of document
*/
function changeAllocateUser($newstate)
{
$err = "";
if ($newstate != "") {
$auserref = trim($this->getValue($this->_Aid("_AFFECTREF", $newstate)));
if ($auserref) {
$uid = $this->getAllocatedUser($newstate);
if ($uid) $wuid = $this->getDocValue($uid, "us_whatid");
if ($wuid > 0) {
$lock = (trim($this->getValue($this->_Aid("_AFFECTLOCK", $newstate))) == "yes");
$err = $this->doc->allocate($wuid, "", false, $lock);
if ($err == "") {
$automail = (trim($this->getValue($this->_Aid("_AFFECTMAIL", $newstate))) == "yes");
if ($automail) {
include_once ("FDL/mailcard.php");
$to = trim($this->getDocValue($uid, "us_mail"));
if (!$to) addWarningMsg(sprintf(_("%s has no email address") , $this->getTitle($uid)));
else {
$subject = sprintf(_("allocation for %s document") , $this->doc->title);
$err = sendCard($action, $this->doc->id, $to, "", $subject, "", true, $commentaction, "", "", "htmlnotif");
if ($err != "") addWarningMsg($err);
}
}
}
}
} else $err = $this->doc->unallocate("", false);
}
return $err;
}
private function getAllocatedUser($newstate)
{
$auserref = trim($this->getValue($this->_Aid("_AFFECTREF", $newstate)));
$type = trim($this->getValue($this->_Aid("_AFFECTTYPE", $newstate)));
if (!$auserref) return false;
$wuid = false;
$aid = strtok($auserref, " ");
switch ($type) {
case 'F': // fixed address
// $wuid=$this->getDocValue($aid,"us_whatid");
$uid = $aid;
break;
case 'PR': // docid parameter
$uid = $this->doc->getparamValue($aid);
// if ($uid) $wuid=$this->getDocValue($uid,"us_whatid");
break;
case 'WPR': // workflow docid parameter
$uid = $this->getparamValue($aid);
// if ($uid) $wuid=$this->getDocValue($uid,"us_whatid");
break;
case 'D': // user relations
$uid = $this->doc->getRValue($aid);
// if ($uid) $wuid=$this->getDocValue($docid,'us_whatid');
break;
case 'WD': // user relations
$uid = $this->getRValue($aid);
// if ($uid) $wuid=$this->getDocValue($docid,'us_whatid');
break;
}
return $uid;
}
/**
* change cv according to state
* @param string $newstate new state of document
*/
function changeCv($newstate)
{
if ($newstate != "") {
$cvid = ($this->getValue($this->_Aid("_CVID", $newstate)));
if (!is_numeric($cvid)) $cvid = getIdFromName($this->dbaccess, $cvid);
if ($cvid > 0) {
// change only if set
$this->doc->cvid = $cvid;
} else {
$fdoc = $this->doc->getFamDoc();
$this->doc->cvid = $fdoc->ccvid;
}
}
}
private function _Aid($fix, $state)
{
return strtolower($this->attrPrefix . $fix . str_replace(":", "_", $state));
}
/**
* get the profile id according to state
* @param string $state
* @return string
*/
public function getStateProfil($state)
{
return $this->getValue($this->_Aid("_id", $state));
}
/**
* get the attribute id for profile id according to state
* @param string $state
* @return string
*/
public function getStateProfilAttribute($state)
{
return $this->_Aid("_id", $state);
}
/**
* get the mask id according to state
* @param string $state
* @return string
*/
public function getStateMask($state)
{
return $this->getValue($this->_Aid("_mskid", $state));
}
/**
* get the view control id according to state
* @param string $state
* @return string
*/
public function getStateViewControl($state)
{
return $this->getValue($this->_Aid("_cvid", $state));
}
/**
* get the timers ids according to state
* @param string $state
* @return string
*/
public function getStateTimers($state)
{
return $this->getValue($this->_Aid("_tmid", $state));
}
/**
* get the mail templates ids according to state
* @param string $state
* @return array
*/
public function getStateMailTemplate($state)
{
return $this->getTValue($this->_Aid("_mtid", $state));
}
/**
* create of parameters attributes of workflow
*/
function createProfileAttribute()
{
if ($this->doctype == 'C') $cid = $this->id;
else $cid = $this->fromid;
$ordered = 1000;
// delete old attributes before
$this->exec_query(sprintf("delete from docattr where docid=%d and options ~ 'autocreated=yes'", intval($cid)));
$this->getStates();
foreach ($this->states as $k => $state) {
// --------------------------
// frame
$aidframe = $this->_Aid("_FR", $state);
$oattr = new DocAttr($this->dbaccess, array(
$cid,
$aidframe
));
$oattr->docid = $cid;
$oattr->visibility = "W";
$oattr->type = "frame";
$oattr->id = $aidframe;
$oattr->frameid = "wf_tab_states";
$oattr->labeltext = sprintf(_("parameters for %s step") , _($state));
$oattr->link = "";
$oattr->phpfunc = "";
$oattr->options = "autocreated=yes";
$oattr->ordered = $ordered++;
if ($oattr->isAffected()) $oattr->Modify();
else $oattr->Add();
// --------------------------
// profil id
$aid = $this->_Aid("_", $state);
$aidprofilid = $this->_Aid("_ID", $state); //strtolower($this->attrPrefix."_ID".strtoupper($state));
$oattr = new DocAttr($this->dbaccess, array(
$cid,
$aidprofilid
));
$oattr->docid = $cid;
$oattr->visibility = "W";
$oattr->type = 'docid("PROFIL")';
$oattr->id = $aidprofilid;
$oattr->labeltext = sprintf(_("%s profile") , _($state));
$oattr->link = "";
$oattr->frameid = $aidframe;
$oattr->options = "autocreated=yes";
$oattr->phpfile = "fdl.php";
$oattr->phpfunc = "lprofil(D,CT,WF_FAMID):$aidprofilid,CT";
$oattr->ordered = $ordered++;
if ($oattr->isAffected()) $oattr->Modify();
else $oattr->Add();
// --------------------------
// mask id
$aid = $this->_Aid("_MSKID", $state);
$oattr = new DocAttr($this->dbaccess, array(
$cid,
$aid
));
$oattr->docid = $cid;
$oattr->visibility = "W";
$oattr->type = 'docid("MASK")';
$oattr->id = $aid;
$oattr->labeltext = sprintf(_("%s mask") , _($state));
$oattr->link = "";
$oattr->frameid = $aidframe;
$oattr->phpfile = "fdl.php";
$oattr->phpfunc = "lmask(D,CT,WF_FAMID):$aid,CT";
$oattr->elink = '';
$oattr->options = 'autocreated=yes|creation={autoclose:"yes",msk_famid:wf_famid,ba_title:"' . _($state) . '"}';
$oattr->ordered = $ordered++;
if ($oattr->isAffected()) $oattr->Modify();
else $oattr->Add();
// --------------------------
// state color
$aid = $this->_Aid("_COLOR", $state);
$oattr = new DocAttr($this->dbaccess, array(
$cid,
$aid
));
$oattr->docid = $cid;
$oattr->visibility = "W";
$oattr->type = "color";
$oattr->link = "";
$oattr->phpfile = "";
$oattr->id = $aid;
$oattr->frameid = $aidframe;
$oattr->ordered = $ordered++;
$oattr->phpfunc = "";
$oattr->options = "autocreated=yes";
$oattr->labeltext = sprintf(_("%s color") , _($state));
if ($oattr->isAffected()) $oattr->Modify();
else $oattr->Add();
// --------------------------
// CV link
$aid = $this->_Aid("_CVID", $state);
$oattr = new DocAttr($this->dbaccess, array(
$cid,
$aid
));
$oattr->docid = $cid;
$oattr->visibility = "W";
$oattr->type = 'docid("CVDOC")';
$oattr->link = "";
$oattr->phpfile = "fdl.php";
$oattr->phpfunc = "lcvdoc(D,CT,WF_FAMID):$aid,CT";
$oattr->elink = '';
$oattr->options = 'autocreated=yes|creation={autoclose:"yes",cv_famid:wf_famid,ba_title:"' . _($state) . '"}';
$oattr->id = $aid;
$oattr->frameid = $aidframe;
$oattr->ordered = $ordered++;
$oattr->labeltext = sprintf(_("%s cv") , _($state));
if ($oattr->isAffected()) $oattr->Modify();
else $oattr->Add();
// --------------------------
// Mail template link
$aid = $this->_Aid("_MTID", $state);
$oattr = new DocAttr($this->dbaccess, array(
$cid,
$aid
));
$oattr->docid = $cid;
$oattr->visibility = "W";
$oattr->type = 'docid("MAILTEMPLATE")';
$oattr->link = "";
$oattr->phpfile = "fdl.php";
$oattr->phpfunc = "lmailtemplatedoc(D,CT,WF_FAMID):$aid,CT";
$oattr->id = $aid;
$oattr->frameid = $aidframe;
$oattr->options = "multiple=yes|autocreated=yes";
$oattr->elink = '';
$oattr->options = 'autocreated=yes|multiple=yes|creation={autoclose:"yes",tmail_family:wf_famid,tmail_workflow:fromid}';
$oattr->ordered = $ordered++;
$oattr->labeltext = sprintf(_("%s mail template") , _($state));
if ($oattr->isAffected()) $oattr->Modify();
else $oattr->Add();
// --------------------------
// Timer link
$aid = $this->_Aid("_TMID", $state);
$oattr = new DocAttr($this->dbaccess, array(
$cid,
$aid
));
$oattr->docid = $cid;
$oattr->visibility = "W";
$oattr->type = 'docid("TIMER")';
$oattr->link = "";
$oattr->phpfile = "fdl.php";
$oattr->phpfunc = "ltimerdoc(D,CT,WF_FAMID):$aid,CT";
$oattr->id = $aid;
$oattr->elink = '';
$oattr->options = 'autocreated=yes|creation={autoclose:"yes",tm_family:wf_famid,tm_workflow:fromid,tm_title:"' . _($state) . '"}';
$oattr->frameid = $aidframe;
$oattr->ordered = $ordered++;
$oattr->labeltext = sprintf(_("%s timer") , _($state));
if ($oattr->isAffected()) $oattr->Modify();
else $oattr->Add();
// --------------------------
// Ask link
$aid = $this->_Aid("_ASKID", $state);
$oattr = new DocAttr($this->dbaccess, array(
$cid,
$aid
));
$oattr->docid = $cid;
$oattr->visibility = "W";
$oattr->type = 'docid("WASK")';
$oattr->link = "";
$oattr->phpfile = "";
$oattr->phpfunc = "";
$oattr->id = $aid;
$oattr->elink = '';
$oattr->options = 'multiple=yes|autocreated=yes|creation={autoclose:"yes"}';
$oattr->frameid = $aidframe;
$oattr->ordered = $ordered++;
$oattr->labeltext = sprintf(_("%s wask") , _($state));
if ($oattr->isAffected()) $oattr->Modify();
else $oattr->Add();
// --------------------------
// Label action
$aid = $this->_Aid("_ACTIVITYLABEL", $k);
$oattr = new DocAttr($this->dbaccess, array(
$cid,
$aid
));
$oattr->docid = $cid;
if ($this->stateactivity[$k]) {
$oattr->visibility = "S";
} else $oattr->visibility = "W";
$oattr->type = 'text';
$oattr->link = "";
$oattr->phpfile = "";
$oattr->phpfunc = "";
$oattr->id = $aid;
$oattr->options = "autocreated=yes";
$oattr->frameid = $aidframe;
$oattr->ordered = $ordered++;
$oattr->labeltext = sprintf(_("%s activity") , _($k));
if ($oattr->isAffected()) $oattr->Modify();
else $oattr->Add();
// --------------------------
// Affected user link
$aid = $this->_Aid("_T_AFFECT", $state);
$afaid = $aid;
$oattr = new DocAttr($this->dbaccess, array(
$cid,
$aid
));
$oattr->docid = $cid;
$oattr->visibility = "U";
$oattr->type = 'array';
$oattr->id = $aid;
$oattr->frameid = $aidframe;
$oattr->options = "vlabel=none|autocreated=yes";
$oattr->ordered = $ordered++;
$oattr->labeltext = sprintf(_("%s affectation") , _($state));
if ($oattr->isAffected()) $oattr->Modify();
else $oattr->Add();
$aid = $this->_Aid("_AFFECTTYPE", $state);
$aidtype = $aid;
$oattr = new DocAttr($this->dbaccess, array(
$cid,
$aid
));
$oattr->docid = $cid;
$oattr->visibility = "W";
$oattr->type = 'enum';
$oattr->options = "autocreated=yes";
$oattr->phpfunc = "F|" . _("Utilisateur fixe") . ",D|" . _("Attribut relation") . ",PR|" . _("Relation parametre") . ",WD|" . _("Relation cycle") . ",WPR|" . _("Parametre cycle");
$oattr->id = $aid;
$oattr->frameid = $afaid;
$oattr->ordered = $ordered++;
$oattr->labeltext = sprintf(_("%s affectation type") , _($state));
if ($oattr->isAffected()) $oattr->Modify();
else $oattr->Add();
$aid = $this->_Aid("_AFFECTREF", $state);
$oattr = new DocAttr($this->dbaccess, array(
$cid,
$aid
));
$oattr->docid = $cid;
$oattr->visibility = "W";
$oattr->type = 'text';
$oattr->link = "";
$oattr->options = "cwidth=160px|autocreated=yes";
$oattr->phpfile = "fdl.php";
$oattr->phpfunc = "tpluser(D,$aidtype,WF_FAMID,FROMID,$aid):$aid";
$oattr->id = $aid;
$oattr->frameid = $afaid;
$oattr->ordered = $ordered++;
$oattr->labeltext = sprintf(_("%s affected user") , _($state));
if ($oattr->isAffected()) $oattr->Modify();
else $oattr->Add();
$aid = $this->_Aid("_AFFECTLOCK", $state);
$oattr = new DocAttr($this->dbaccess, array(
$cid,
$aid
));
$oattr->docid = $cid;
$oattr->visibility = "W";
$oattr->type = 'enum';
$oattr->link = "";
$oattr->options = "eformat=bool|autocreated=yes";
$oattr->phpfunc = "no|" . _("affect no lock") . ",yes|" . _("affect auto lock");
$oattr->id = $aid;
$oattr->frameid = $afaid;
$oattr->ordered = $ordered++;
$oattr->labeltext = sprintf(_("%s autolock") , _($state));
if ($oattr->isAffected()) $oattr->Modify();
else $oattr->Add();
$aid = $this->_Aid("_AFFECTMAIL", $state);
$oattr = new DocAttr($this->dbaccess, array(
$cid,
$aid
));
$oattr->docid = $cid;
$oattr->visibility = "W";
$oattr->type = 'enum';
$oattr->link = "";
$oattr->options = "eformat=bool|autocreated=yes";
$oattr->phpfunc = "no|" . _("affect no mail") . ",yes|" . _("affect auto mail");
$oattr->id = $aid;
$oattr->frameid = $afaid;
$oattr->ordered = $ordered++;
$oattr->labeltext = sprintf(_("%s automail") , _($state));
if ($oattr->isAffected()) $oattr->Modify();
else $oattr->Add();
}
foreach ($this->transitions as $k => $trans) {
// --------------------------
// frame
$aidframe = $this->_Aid("_TRANS_FR", $k);
$oattr = new DocAttr($this->dbaccess, array(
$cid,
$aidframe
));
$oattr->docid = $cid;
$oattr->visibility = "W";
$oattr->type = "frame";
$oattr->id = $aidframe;
$oattr->frameid = "wf_tab_transitions";
$oattr->labeltext = sprintf(_("parameters for %s transition") , _($k));
$oattr->link = "";
$oattr->phpfunc = "";
$oattr->options = "autocreated=yes";
$oattr->ordered = $ordered++;
if ($oattr->isAffected()) $oattr->Modify();
else $oattr->Add();
// --------------------------
// Mail template link
$aid = $this->_Aid("_TRANS_MTID", $k);
$oattr = new DocAttr($this->dbaccess, array(
$cid,
$aid
));
$oattr->docid = $cid;
$oattr->visibility = "W";
$oattr->type = 'docid("MAILTEMPLATE")';
$oattr->link = "";
$oattr->phpfile = "fdl.php";
$oattr->phpfunc = "lmailtemplatedoc(D,CT,WF_FAMID):$aid,CT";
$oattr->elink = "";
$oattr->id = $aid;
$oattr->frameid = $aidframe;
$oattr->ordered = $ordered++;
$oattr->options = 'autocreated=yes|multiple=yes|creation={autoclose:"yes",tmail_family:wf_famid,tmail_workflow:fromid}';
$oattr->labeltext = sprintf(_("%s mail template") , _($k));
if ($oattr->isAffected()) $oattr->Modify();
else $oattr->Add();
// --------------------------
// Timer link
$aid = $this->_Aid("_TRANS_TMID", $k);
$oattr = new DocAttr($this->dbaccess, array(
$cid,
$aid
));
$oattr->docid = $cid;
$oattr->visibility = "W";
$oattr->type = 'docid("TIMER")';
$oattr->link = "";
$oattr->phpfile = "fdl.php";
$oattr->phpfunc = "ltimerdoc(D,CT,WF_FAMID):$aid,CT";
$oattr->elink = "";
$oattr->options = 'autocreated=yes|creation={autoclose:"yes",tm_family:wf_famid,tm_workflow:fromid,tm_title:"' . _($state) . '"}';
$oattr->id = $aid;
$oattr->frameid = $aidframe;
$oattr->ordered = $ordered++;
$oattr->labeltext = sprintf(_("%s timer") , _($k));
if ($oattr->isAffected()) $oattr->Modify();
else $oattr->Add();
// --------------------------
// Persistent Attach Timer link
$aid = $this->_Aid("_TRANS_PA_TMID", $k);
$oattr = new DocAttr($this->dbaccess, array(
$cid,
$aid
));
$oattr->docid = $cid;
$oattr->visibility = "W";
$oattr->type = 'docid("TIMER")';
$oattr->link = "";
$oattr->phpfile = "fdl.php";
$oattr->phpfunc = "ltimerdoc(D,CT,WF_FAMID):$aid,CT";
$oattr->elink = "";
$oattr->options = 'multiple=yes|autocreated=yes|creation={autoclose:"yes",tm_family:wf_famid,tm_workflow:fromid,tm_title:"' . _($state) . '"}';
$oattr->id = $aid;
$oattr->frameid = $aidframe;
$oattr->ordered = $ordered++;
$oattr->labeltext = sprintf(_("%s persistent timer") , _($k));
if ($oattr->isAffected()) $oattr->Modify();
else $oattr->Add();
// --------------------------
// Persistent UnAttach Timer link
$aid = $this->_Aid("_TRANS_PU_TMID", $k);
$oattr = new DocAttr($this->dbaccess, array(
$cid,
$aid
));
$oattr->docid = $cid;
$oattr->visibility = "W";
$oattr->type = 'docid("TIMER")';
$oattr->link = "";
$oattr->phpfile = "fdl.php";
$oattr->phpfunc = "ltimerdoc(D,CT,WF_FAMID):$aid,CT";
$oattr->elink = "";
$oattr->id = $aid;
$oattr->options = "multiple=yes|autocreated=yes";
$oattr->frameid = $aidframe;
$oattr->ordered = $ordered++;
$oattr->labeltext = sprintf(_("%s unattach timer") , _($k));
if ($oattr->isAffected()) $oattr->Modify();
else $oattr->Add();
}
refreshPhpPgDoc($this->dbaccess, $cid);
}
/**
* change state of a document
* the method {@link set()} must be call before
* @param string $newstate the next state
* @param string $comment comment to be set in history (describe why change state)
* @param bool $force is true when it is the second passage (without interactivity)
* @param bool $withcontrol set to false if you want to not verify control permission ot transition
* @param bool $wm1 set to false if you want to not apply m1 methods
* @param bool $wm2 set to false if you want to not apply m2 methods
* @param bool $need set to false if you want to not verify needed attribute are set
* @return string error message, if no error empty string
*/
function changeState($newstate, $addcomment = "", $force = false, $withcontrol = true, $wm1 = true, $wm2 = true, $wneed = true)
{
// if ($this->doc->state == $newstate) return ""; // no change => no action
// search if possible change in concordance with transition array
$foundFrom = false;
$foundTo = false;
reset($this->cycle);
while (list($k, $trans) = each($this->cycle)) {
if (($this->doc->state == $trans["e1"])) {
// from state OK
$foundFrom = true;
if ($newstate == $trans["e2"]) {
$foundTo = true;
$tr = $this->transitions[$trans["t"]];
$tname = $trans["t"];
}
}
}
if ($this->userid != 1) { // admin can go to any states
if (!$foundTo) return (sprintf(_("ChangeState :: the new state '%s' is not known or is not allowed from %s") , _($newstate) , _($this->doc->state)));
if (!$foundFrom) return (sprintf(_("ChangeState :: the initial state '%s' is not known") , _($this->doc->state)));
}
// verify if completed doc
if ($wneed) {
$err = $this->doc->isCompleteNeeded();
if ($err != "") return $err;
}
// verify if privilege granted
if ($withcontrol) $err = $this->control($tname);
if ($err != "") return $err;
if ($wm1 && ($tr["m1"] != "")) {
// apply first method (condition for the change)
if (!method_exists($this, $tr["m1"])) return (sprintf(_("the method '%s' is not known for the object class %s") , $tr["m1"], get_class($this)));
$err = call_user_func(array(
$this,
$tr["m1"]
) , $newstate, $this->doc->state, $addcomment);
if ($err == "->") {
if ($force) {
$err = ""; // it is the return of the report
SetHttpVar("redirect_app", ""); // override the redirect
SetHttpVar("redirect_act", "");
} else {
if ($addcomment != "") $this->doc->AddComment($addcomment); // add comment now because it will be lost
return ""; //it is not a real error, but don't change state (reported)
}
}
if ($err != "") {
$this->doc->unlock(true);
return (sprintf(_("The change state to %s has been aborted.\n%s") , _($newstate) , $err));
}
}
// change the state
$oldstate = $this->doc->state == "" ? " " : $this->doc->state;
$this->doc->state = $newstate;
$this->changeProfil($newstate);
$this->changeCv($newstate);
$this->doc->disableEditControl();
$err = $this->doc->Modify(); // don't control edit permission
if ($err != "") return $err;
$revcomment = sprintf(_("change state : %s to %s") , _($oldstate) , _($newstate));
if ($addcomment != "") $this->doc->AddComment($addcomment);
if (isset($tr["ask"])) {
foreach ($tr["ask"] as $vpid) {
$pv = $this->getValue($vpid);
if ($pv != "") {
$oa = $this->getAttribute($vpid);
$revcomment.= "\n-" . $oa->getLabel() . ":" . $pv;
}
}
}
$err = $this->doc->AddRevision($revcomment);
if ($err != "") {
$this->doc->disableEditControl(); // restore old states
$this->doc->state = $oldstate;
$this->changeProfil($oldstate);
$this->changeCv($oldstate);
$err2 = $this->doc->Modify(); // don't control edit permission
$this->doc->enableEditControl();
return $err . $err2;
}
AddLogMsg(sprintf(_("%s new state %s") , $this->doc->title, _($newstate)));
$this->doc->enableEditControl();
// post action
if ($wm2 && ($tr["m2"] != "")) {
if (!method_exists($this, $tr["m2"])) return (sprintf(_("the method '%s' is not known for the object class %s") , $tr["m2"], get_class($this)));
$err = call_user_func(array(
$this,
$tr["m2"]
) , $newstate, $oldstate, $addcomment);
if ($err == "->") $err = ""; //it is not a real error
if ($err != "") $err = sprintf(_("The change state to %s has been realized. But the following warning is appeared.\n%s") , _($newstate) , $err);
}
$this->doc->addLog("state", array(
"id" => $this->id,
"initid" => $this->initid,
"revision" => $this->revision,
"title" => $this->title,
"state" => $this->state,
"message" => $err
));
$this->doc->disableEditControl();
if (!$this->domainid) $this->doc->unlock(false, true);
$this->workflowSendMailTemplate($newstate, $addcomment, $tname);
$this->workflowAttachTimer($newstate, $tname);
$err.= $this->changeAllocateUser($newstate);
$this->doc->enableEditControl();
return $err;
}
// --------------------------------------------------------------------
function getFollowingStates()
{
// search if following states in concordance with transition array
if ($this->doc->locked == - 1) return array(); // no next state for revised document
if (($this->doc->locked > 0) && ($this->doc->locked != $this->doc->userid)) return array(); // no next state if locked by another person
$fstate = array();
if ($this->doc->state == "") $this->doc->state = $this->getFirstState();
if ($this->userid == 1) return $this->getStates(); // only admin can go to any states from anystates
reset($this->cycle);
while (list($k, $tr) = each($this->cycle)) {
if ($this->doc->state == $tr["e1"]) {
// from state OK
if ($this->control($tr["t"]) == "") $fstate[] = $tr["e2"];
}
}
return $fstate;
}
function getStates()
{
if (!isset($this->states)) {
$this->states = array();
reset($this->cycle);
while (list($k, $tr) = each($this->cycle)) {
if ($tr["e1"] != "") $this->states[$tr["e1"]] = $tr["e1"];
if ($tr["e2"] != "") $this->states[$tr["e2"]] = $tr["e2"];
}
}
return $this->states;
}
/**
* get associated color of a state
* @param string $state the state
* @return string the color (#RGB)
*/
function getColor($state, $def = "")
{
//$acolor=$this->attrPrefix."_COLOR".($state);
$acolor = $this->_Aid("_COLOR", $state);
return $this->getValue($acolor, $def);
}
/**
* get activity (localized language)
* @param string $state the state
* @return string the text of action
*/
function getActivity($state, $def = "")
{
//$acolor=$this->attrPrefix."_ACTIVITYLABEL".($state);
$acolor = $this->_Aid("_ACTIVITYLABEL", $state);
$v = $this->getValue($acolor);
if ($v) return _($v);
return $def;
}
/**
* get action (localized language)
* @deprecated
* @param string $state the state
* @return string the text of action
*/
function getAction($state, $def = "")
{
deprecatedFunction();
return $this->getActivity($state, $def);
}
/**
* get askes for a document
* searcj all WASK document which current user can see for a specific state
* @param string $state the state
* @param bool $control set to false to not control ask access
* @return string the text of action
*/
function getDocumentWasks($state, $control = true)
{
$aask = $this->_Aid("_ASKID", $state);
$vasks = $this->getTValue($aask);
if ($control) {
$cask = array();
foreach ($vasks as $askid) {
$ask = new_doc($this->dbaccess, $askid);
$ask->set($this->doc);
if ($ask->isAlive() && ($ask->control('answer') == "")) $cask[] = $ask->id;
}
return $cask;
} else {
return $vasks;
}
}
/**
* verify if askes are defined
*
* @return bool true if at least one ask is set in workflow
*/
function hasWasks()
{
$states = $this->getStates();
foreach ($states as $state) {
$aask = $this->_Aid("_ASKID", $state);
if ($this->getValue($aask)) return true;
}
return false;
}
/**
* send associated mail of a state
* @param string $state the state
* @param string $comment reason of change state
* @param array $tname transition name
* @return Doc
*/
function workflowSendMailTemplate($state, $comment = "", $tname = "")
{
$tmtid = $this->getTValue($this->_Aid("_TRANS_MTID", $tname));
$tr = $this->transitions[$tname];
if ($tmtid && (count($tmtid) > 0)) {
foreach ($tmtid as $mtid) {
$keys = array();
$mt = new_doc($this->dbaccess, $mtid);
if ($mt->isAlive()) {
$keys["WCOMMENT"] = nl2br($comment);
if (isset($tr["ask"])) {
foreach ($tr["ask"] as $vpid) {
$keys["V_" . strtoupper($vpid) ] = $this->getHtmlAttrValue($vpid);
$keys[strtoupper($vpid) ] = $this->getValue($vpid);
}
}
$err = $mt->sendDocument($this->doc, $keys);
}
}
}
$tmtid = $this->getTValue($this->_Aid("_MTID", $state));
if ($tmtid && (count($tmtid) > 0)) {
foreach ($tmtid as $mtid) {
$keys = array();
$mt = new_doc($this->dbaccess, $mtid);
if ($mt->isAlive()) {
$keys["WCOMMENT"] = nl2br($comment);
if (isset($tr["ask"])) {
foreach ($tr["ask"] as $vpid) {
$keys["V_" . strtoupper($vpid) ] = $this->getHtmlAttrValue($vpid);
$keys[strtoupper($vpid) ] = $this->getValue($vpid);
}
}
$err = $mt->sendDocument($this->doc, $keys);
}
}
}
return $err;
}
/**
* attach timer to a document
* @param string $state the state
* @param array $tname transition name
* @return Doc
*/
function workflowAttachTimer($state, $tname = "")
{
$mtid = $this->getValue($this->_Aid("_TRANS_TMID", $tname));
$this->doc->unattachAllTimers($this);
$tr = $this->transitions[$tname];
if ($mtid) {
$mt = new_doc($this->dbaccess, $mtid);
if ($mt->isAlive()) {
$err = $this->doc->attachTimer($mt, $this);
}
}
// unattach persistent
$tmtid = $this->getTValue($this->_Aid("_TRANS_PU_TMID", $tname));
if ($tmtid && (count($tmtid) > 0)) {
foreach ($tmtid as $mtid) {
$mt = new_doc($this->dbaccess, $mtid);
if ($mt->isAlive()) {
$err.= $this->doc->unattachTimer($mt);
}
}
}
$mtid = $this->getValue($this->_Aid("_TMID", $state));
if ($mtid) {
$mt = new_doc($this->dbaccess, $mtid);
if ($mt->isAlive()) {
$err.= $this->doc->attachTimer($mt, $this);
}
}
// attach persistent
$tmtid = $this->getTValue($this->_Aid("_TRANS_PA_TMID", $tname));
if ($tmtid && (count($tmtid) > 0)) {
foreach ($tmtid as $mtid) {
$mt = new_doc($this->dbaccess, $mtid);
if ($mt->isAlive()) {
$err.= $this->doc->attachTimer($mt);
}
}
}
return $err;
}
function changeStateOfDocid($docid, $newstate, $comment = "")
{
$cmd = new_Doc($this->dbaccess, $docid);
$cmdid = $cmd->latestId(); // get the latest
$cmd = new_Doc($this->dbaccess, $cmdid);
if ($cmd->wid > 0) {
$wdoc = new_Doc($this->dbaccess, $cmd->wid);
if (!$wdoc) $err = sprintf(_("cannot change state of document #%d to %s") , $cmd->wid, $newstate);
if ($err != "") return $err;
$wdoc->Set($cmd);
$err = $wdoc->ChangeState($newstate, sprintf(_("automaticaly by change state of %s\n%s") , $this->doc->title, $comment));
if ($err != "") return $err;
}
}
/**
* get transition array for the transition between $to and $from states
* @param string $to first state
* @param string $from next state
* @return array transition array (false if not found)
*/
function getTransition($from, $to)
{
foreach ($this->cycle as $v) {
if (($v["e1"] == $from) && ($v["e2"] == $to)) {
$t = $this->transitions[$v["t"]];
$t["id"] = $v["t"];
return $t;
}
}
return false;
}
function DocControl($aclname)
{
return Doc::Control($aclname);
}
/**
* Special control in case of dynamic controlled profil
*/
function Control($aclname)
{
$err = Doc::Control($aclname);
if ($err == "") return $err; // normal case
if ($this->getValue("DPDOC_FAMID") > 0) {
// special control for dynamic users
if (!isset($this->pdoc)) {
$pdoc = createDoc($this->dbaccess, $this->fromid, false);
$pdoc->doctype = "T"; // temporary
// $pdoc->setValue("DPDOC_FAMID",$this->getValue("DPDOC_FAMID"));
$err = $pdoc->Add();
if ($err != "") return "WDoc::Control:" . $err; // can't create profil
$pdoc->setProfil($this->profid, $this->doc);
$this->pdoc = & $pdoc;
}
$err = $this->pdoc->DocControl($aclname);
}
return $err;
}
/**
* affect action label
*/
function postModify()
{
foreach ($this->stateactivity as $k => $v) {
$this->setValue($this->_Aid("_ACTIVITYLABEL", $k) , $v);
}
$this->getStates();
foreach ($this->states as $k => $state) {
$allo = trim($this->getValue($this->_Aid("_AFFECTREF", $state)));
if (!$allo) $this->removeArrayRow($this->_Aid("_T_AFFECT", $state) , 0);
}
if ($this->isChanged()) $this->modify();
}
/**
* get value of instanced document
* @param string $attrid attribute identificator
* @return string return the value, false if attribute not exist or document not set
*/
function getInstanceValue($attrid, $def = false)
{
if ($this->doc) {
return $this->doc->getValue($attrid, $def);
}
return $def;
}
}
?>
|
Eric-Brison/dynacase-core
|
Class/Fdl/Class.WDoc.php
|
PHP
|
agpl-3.0
| 41,560
|
<?php
/*-------------------------------------------------------+
| PHP-Fusion Content Management System
| Copyright (C) PHP-Fusion Inc
| http://www.php-fusion.co.uk/
+--------------------------------------------------------+
| Filename: shoutbox_panel.php
| Author: Nick Jones (Digitanium)
+--------------------------------------------------------+
| This program is released as free software under the
| Affero GPL license. You can redistribute it and/or
| modify it under the terms of this license which you
| can read by viewing the included agpl.txt or online
| at www.gnu.org/licenses/agpl.html. Removal of this
| copyright header is strictly prohibited without
| written permission from the original author(s).
+--------------------------------------------------------*/
if (!defined("IN_FUSION")) {
die("Access Denied");
}
include_once INFUSIONS."shoutbox_panel/infusion_db.php";
include_once INCLUDES."infusions_include.php";
// Check if a locale file is available that match the selected locale.
if (file_exists(INFUSIONS."shoutbox_panel/locale/".LANGUAGE.".php")) {
// Load the locale file matching selection.
include INFUSIONS."shoutbox_panel/locale/".LANGUAGE.".php";
} else {
// Load the default locale file.
include INFUSIONS."shoutbox_panel/locale/English.php";
}
$shout_settings = get_settings("shoutbox_panel");
$link = FUSION_SELF.(FUSION_QUERY ? "?".FUSION_QUERY : "");
$link = preg_replace("^(&|\?)s_action=(edit|delete)&shout_id=\d*^", "", $link);
$sep = stristr($link, "?") ? "&" : "?";
$shout_link = "";
$shout_message = "";
if (iMEMBER && (isset($_GET['s_action']) && $_GET['s_action'] == "delete") && (isset($_GET['shout_id']) && isnum($_GET['shout_id']))) {
if ((iADMIN && checkrights("S")) || (iMEMBER && dbcount("(shout_id)", DB_SHOUTBOX, "shout_id='".$_GET['shout_id']."' AND shout_name='".$userdata['user_id']."'"))) {
$result = dbquery("DELETE FROM ".DB_SHOUTBOX." WHERE shout_id='".$_GET['shout_id']."'".(iADMIN ? "" : " AND shout_name='".$userdata['user_id']."'"));
}
redirect($link);
}
if (!function_exists("sbwrap")) {
function sbwrap($text) {
global $locale;
$i = 0;
$tags = 0;
$chars = 0;
$res = "";
$str_len = strlen($text);
for ($i = 0; $i < $str_len; $i++) {
$chr = mb_substr($text, $i, 1, $locale['charset']);
if ($chr == "<") {
if (mb_substr($text, ($i+1), 6, $locale['charset']) == "a href" || mb_substr($text, ($i+1), 3, $locale['charset']) == "img") {
$chr = " ".$chr;
$chars = 0;
}
$tags++;
} elseif ($chr == "&") {
if (mb_substr($text, ($i+1), 5, $locale['charset']) == "quot;") {
$chars = $chars-5;
} elseif (mb_substr($text, ($i+1), 4, $locale['charset']) == "amp;" || mb_substr($text, ($i+1), 4, $locale['charset']) == "#39;" || mb_substr($text, ($i+1), 4, $locale['charset']) == "#92;") {
$chars = $chars-4;
} elseif (mb_substr($text, ($i+1), 3, $locale['charset']) == "lt;" || mb_substr($text, ($i+1), 3, $locale['charset']) == "gt;") {
$chars = $chars-3;
}
} elseif ($chr == ">") {
$tags--;
} elseif ($chr == " ") {
$chars = 0;
} elseif (!$tags) {
$chars++;
}
if (!$tags && $chars == 18) {
$chr .= "<br />";
$chars = 0;
}
$res .= $chr;
}
return $res;
}
}
openside($locale['SB_title']);
if (iMEMBER || $shout_settings['guest_shouts'] == "1") {
include_once INCLUDES."bbcode_include.php";
if (isset($_POST['post_shout'])) {
$flood = FALSE;
if (iMEMBER) {
$shout_name = $userdata['user_id'];
} elseif ($shout_settings['guest_shouts'] == "1") {
$shout_name = trim(stripinput($_POST['shout_name']));
$shout_name = preg_replace("(^[+0-9\s]*)", "", $shout_name);
if (isnum($shout_name)) {
$shout_name = "";
}
include_once INCLUDES."captchas/securimage/securimage.php";
$securimage = new Securimage();
if (!isset($_POST['sb_captcha_code']) || $securimage->check($_POST['sb_captcha_code']) == FALSE) {
redirect($link);
}
}
$shout_message = str_replace("\n", " ", $_POST['shout_message']);
$shout_message = preg_replace("/^(.{255}).*$/", "$1", $shout_message);
$shout_message = trim(stripinput(censorwords($shout_message)));
if (iMEMBER && (isset($_GET['s_action']) && $_GET['s_action'] == "edit") && (isset($_GET['shout_id']) && isnum($_GET['shout_id']))) {
$comment_updated = FALSE;
if ((iADMIN && checkrights("S")) || (iMEMBER && dbcount("(shout_id)", DB_SHOUTBOX, "shout_id='".$_GET['shout_id']."' AND shout_name='".$userdata['user_id']."'"))) {
if ($shout_message) {
$result = dbquery("UPDATE ".DB_SHOUTBOX." SET shout_message='$shout_message' WHERE shout_id='".$_GET['shout_id']."'".(iADMIN ? "" : " AND shout_name='".$userdata['user_id']."'"));
}
}
redirect($link);
} elseif ($shout_name && $shout_message) {
require_once INCLUDES."flood_include.php";
if (!flood_control("shout_datestamp", DB_SHOUTBOX, "shout_ip='".USER_IP."'")) {
$result = dbquery("INSERT INTO ".DB_SHOUTBOX." (shout_name, shout_message, shout_datestamp, shout_ip, shout_ip_type, shout_hidden".(multilang_table("SB") ? ", shout_language)" : ")")." VALUES ('$shout_name', '$shout_message', '".time()."', '".USER_IP."', '".USER_IP_TYPE."', '0'".(multilang_table("SB") ? ", '".LANGUAGE."')" : ")"));
}
}
redirect($link);
}
if (iMEMBER && (isset($_GET['s_action']) && $_GET['s_action'] == "edit") && (isset($_GET['shout_id']) && isnum($_GET['shout_id']))) {
$esresult = dbquery("SELECT ts.shout_id, ts.shout_name, ts.shout_message, tu.user_id, tu.user_name
FROM ".DB_SHOUTBOX." ts
LEFT JOIN ".DB_USERS." tu ON ts.shout_name=tu.user_id
".(multilang_table("SB") ? "WHERE shout_language='".LANGUAGE."' AND" : "WHERE")." ts.shout_id='".$_GET['shout_id']."'");
if (dbrows($esresult)) {
$esdata = dbarray($esresult);
if ((iADMIN && checkrights("S")) || (iMEMBER && $esdata['shout_name'] == $userdata['user_id'] && isset($esdata['user_name']))) {
if ((isset($_GET['s_action']) && $_GET['s_action'] == "edit") && (isset($_GET['shout_id']) && isnum($_GET['shout_id']))) {
$edit_url = $sep."s_action=edit&shout_id=".$esdata['shout_id'];
} else {
$edit_url = "";
}
$shout_link = $link.$edit_url;
$shout_message = $esdata['shout_message'];
}
} else {
$shout_link = $link;
$shout_message = "";
}
} else {
$shout_link = $link;
$shout_message = "";
}
echo "<a id='edit_shout' name='edit_shout'></a>\n";
echo openform('shout_form', 'post', $shout_link, array('notice' => 0, 'max_tokens' => 1));
if (iGUEST) {
echo $locale['SB_name']."<br />\n";
echo "<input type='text' name='shout_name' value='' class='textbox' maxlength='30' style='width:140px' /><br />\n";
echo $locale['SB_message']."<br />\n";
}
echo display_bbcodes("150px;", "shout_message", "shout_form", "smiley|b|u|url|color")."\n";
echo form_textarea('shout_message', '', $shout_message);
if (iGUEST) {
echo $locale['SB_validation_code']."<br />\n";
echo "<img id='sb_captcha' src='".INCLUDES."captchas/securimage/securimage_show.php' alt='' /><br />\n";
echo "<a href='".INCLUDES."captchas/securimage/securimage_play.php'><img src='".INCLUDES."captchas/securimage/images/audio_icon.gif' alt='' class='tbl-border' style='margin-bottom:1px' /></a>\n";
echo "<a href='#' onclick=\"document.getElementById('sb_captcha').src = '".INCLUDES."captchas/securimage/securimage_show.php?sid=' + Math.random(); return false\"><img src='".INCLUDES."captchas/securimage/images/refresh.gif' alt='' class='tbl-border' /></a><br />\n";
echo $locale['SB_enter_validation_code']."<br />\n<input type='text' name='sb_captcha_code' class='textbox' style='width:100px' /><br />\n";
}
echo form_button('post_shout', $locale['SB_shout'], $locale['SB_shout'], array('class' => 'btn-block btn-primary button',
'icon' => "entypo icomment"));
echo closeform();
} else {
echo "<div style='text-align:center'>".$locale['SB_login_req']."</div><br />\n";
}
$numrows = dbcount("(shout_id)", DB_SHOUTBOX, "shout_hidden='0'");
$result = dbquery("SELECT ts.shout_id, ts.shout_name, ts.shout_message, ts.shout_datestamp, tu.user_id, tu.user_name, tu.user_status, tu.user_avatar
FROM ".DB_SHOUTBOX." ts
LEFT JOIN ".DB_USERS." tu ON ts.shout_name=tu.user_id
".(multilang_table("SB") ? "WHERE shout_language='".LANGUAGE."' AND" : "WHERE")." shout_hidden='0'
ORDER BY ts.shout_datestamp DESC LIMIT 0,".$shout_settings['visible_shouts']);
if (dbrows($result)) {
$i = 0;
while ($data = dbarray($result)) {
echo "<div class='display-block shoutboxwrapper clearfix' style='width:100%;'>\n";
echo "<div class='shoutboxavatar pull-left m-r-10 m-t-5'>\n";
echo display_avatar($data, '50px');
echo "</div>\n";
if ((iADMIN && checkrights("S")) || (iMEMBER && $data['shout_name'] == $userdata['user_id'] && isset($data['user_name']))) {
echo "<div class='pull-right btn-group'>\n";
echo "<a class='btn btn-default btn-xs' title='".$locale['SB_edit']."' href='".$link.$sep."s_action=edit&shout_id=".$data['shout_id']."#edit_shout"."' class='side'><i class='entypo pencil'></i></a>\n"; //
echo "<a class='btn btn-default btn-xs' title='".$locale['SB_delete']."' href='".$link.$sep."s_action=delete&shout_id=".$data['shout_id']."' onclick=\"return confirm('".$locale['SB_warning_shout']."');\" class='side'><i class='entypo trash'></i></a>\n"; //
echo "</div>\n";
}
echo "<div class='shoutboxname'>\n";
echo ($data['user_name']) ? "<span class='side'>".profile_link($data['shout_name'], $data['user_name'], $data['user_status'])."</span>\n" : $data['shout_name']."\n";
echo "</div>\n";
echo "<div class='shoutboxdate'>".timer($data['shout_datestamp'])."</div>\n"; //".showdate("forumdate", $data['shout_datestamp'])."</div>";
echo "<div class='shoutbox'>".sbwrap(parseubb(parsesmileys($data['shout_message']), "b|i|u|url|color"))."</div>\n";
//if ($i != $numrows) { echo "<br />\n"; }
echo "</div>\n";
}
if ($numrows > $shout_settings['visible_shouts']) {
echo "<div style='text-align:center'>\n<a href='".INFUSIONS."shoutbox_panel/shoutbox_archive.php' class='side'>".$locale['SB_archive']."</a>\n</div>\n";
}
} else {
echo "<div>".$locale['SB_no_msgs']."</div>\n";
}
closeside();
|
Talocha/PHP-Fusion
|
infusions/shoutbox_panel/shoutbox_panel.php
|
PHP
|
agpl-3.0
| 10,415
|
package com.puresoltechnologies.purifinity.server.core.impl.analysis.job;
import java.util.Map;
import javax.batch.api.Batchlet;
import javax.batch.runtime.context.JobContext;
import javax.batch.runtime.context.StepContext;
import javax.inject.Inject;
import javax.inject.Named;
import org.slf4j.Logger;
import com.puresoltechnologies.parsers.source.SourceCodeLocation;
import com.puresoltechnologies.purifinity.analysis.api.AnalysisProject;
import com.puresoltechnologies.purifinity.analysis.api.AnalysisProjectSettings;
import com.puresoltechnologies.purifinity.analysis.api.AnalysisRunInformation;
import com.puresoltechnologies.purifinity.server.common.job.PersistentStepUserData;
import com.puresoltechnologies.purifinity.server.core.api.analysis.AnalysisRunFileTree;
import com.puresoltechnologies.purifinity.server.core.api.analysis.store.FileInformation;
import com.puresoltechnologies.purifinity.server.core.api.analysis.store.ProjectManager;
@Named("FileTreeCreationBatchlet")
public class FileTreeCreationBatchlet implements Batchlet {
@Inject
private Logger logger;
@Inject
private ProjectManager analysisStoreService;
@Inject
private JobContext jobContext;
@Inject
private StepContext stepContext;
@Override
public String process() throws Exception {
logger.info("Create and store analysis run file tree...");
PersistentStepUserData persistentUserData = new PersistentStepUserData("Create and Store File Tree",
"For the project the complete file tree is generated and stored in database.", 2);
stepContext.setPersistentUserData(persistentUserData);
AnalysisJobContext analysisJobContext = (AnalysisJobContext) jobContext.getTransientUserData();
AnalysisProject analysisProject = analysisJobContext.getAnalysisProject();
AnalysisRunInformation analysisRunInformation = analysisJobContext.getAnalysisRunInformation();
AnalysisProjectSettings projectSettings = analysisProject.getSettings();
Map<SourceCodeLocation, FileInformation> storedSources = analysisJobContext.getStoredFiles();
persistentUserData.increaseCurrentItem(1);
stepContext.setPersistentUserData(persistentUserData);
AnalysisRunFileTree analysisRunFileTree = analysisStoreService.createAndStoreFileAndContentTree(
analysisRunInformation.getProjectId(), analysisRunInformation.getRunId(), projectSettings.getName(),
storedSources);
analysisJobContext.setAnalysisRunFileTree(analysisRunFileTree);
logger.info("analysis run file tree created and stored.");
return AnalysisJobExitString.SUCCESSFUL.get();
}
@Override
public void stop() throws Exception {
// unfortunately not supported...
}
}
|
PureSolTechnologies/Purifinity
|
analysis/server/server/core.impl/src/main/java/com/puresoltechnologies/purifinity/server/core/impl/analysis/job/FileTreeCreationBatchlet.java
|
Java
|
agpl-3.0
| 2,659
|
require "rails_helper"
describe "Moderate users" do
scenario "Hide" do
citizen = create(:user)
moderator = create(:moderator)
debate1 = create(:debate, author: citizen)
debate2 = create(:debate, author: citizen)
debate3 = create(:debate)
comment3 = create(:comment, user: citizen, commentable: debate3, body: "SPAMMER")
login_as(moderator.user)
visit debates_path
expect(page).to have_content(debate1.title)
expect(page).to have_content(debate2.title)
expect(page).to have_content(debate3.title)
visit debate_path(debate3)
expect(page).to have_content(comment3.body)
visit debate_path(debate1)
within("#debate_#{debate1.id}") do
accept_confirm("Are you sure? This will hide the user \"#{debate1.author.name}\" and all their contents.") do
click_button "Block author"
end
end
expect(page).to have_current_path(debates_path)
expect(page).not_to have_content(debate1.title)
expect(page).not_to have_content(debate2.title)
expect(page).to have_content(debate3.title)
visit debate_path(debate3)
expect(page).not_to have_content(comment3.body)
click_link("Sign out")
visit root_path
click_link "Sign in"
fill_in "user_login", with: citizen.email
fill_in "user_password", with: citizen.password
click_button "Enter"
expect(page).to have_content "Invalid Email or username or password"
expect(page).to have_current_path(new_user_session_path)
end
scenario "Search and ban users" do
citizen = create(:user, username: "Wanda Maximoff")
moderator = create(:moderator)
login_as(moderator.user)
visit moderation_users_path
expect(page).not_to have_content citizen.name
fill_in "search", with: "Wanda"
click_button "Search"
within("#moderation_users") do
expect(page).to have_content citizen.name
expect(page).not_to have_content "Blocked"
accept_confirm { click_button "Block" }
end
within("#moderation_users") do
expect(page).to have_content citizen.name
expect(page).to have_content "Blocked"
end
end
scenario "Hide users in the moderation section" do
create(:user, username: "Rick")
login_as(create(:moderator).user)
visit moderation_users_path(search: "Rick")
within("#moderation_users") do
accept_confirm('This will hide the user "Rick" without hiding their contents') do
click_button "Hide"
end
end
expect(page).to have_content "The user has been hidden"
within("#moderation_users") do
expect(page).to have_content "Hidden"
end
end
end
|
consul/consul
|
spec/system/moderation/users_spec.rb
|
Ruby
|
agpl-3.0
| 2,643
|
/*
sb0t ares chat server
Copyright (C) 2017 AresChat
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/>.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using iconnect;
namespace commands
{
class CustomNames
{
private class Item
{
public Guid Guid { get; set; }
public String Name { get; set; }
public String Text { get; set; }
}
private static List<Item> list { get; set; }
public static void Set(IUser client)
{
Item i = list.Find(x => x.Guid.Equals(client.Guid) && x.Name == client.Name);
if (i != null)
client.CustomName = i.Text;
}
public static void UpdateCustomName(IUser client)
{
list.RemoveAll(x => x.Guid.Equals(client.Guid) && x.Name == client.Name);
if (!String.IsNullOrEmpty(client.CustomName))
list.Add(new Item
{
Guid = client.Guid,
Name = client.Name,
Text = client.CustomName
});
Save();
}
public static void Load()
{
list = new List<Item>();
try
{
XmlDocument xml = new XmlDocument();
xml.PreserveWhitespace = true;
xml.Load(Path.Combine(Server.DataPath, "customnames.xml"));
XmlNodeList nodes = xml.GetElementsByTagName("item");
foreach (XmlElement e in nodes)
list.Add(new Item
{
Guid = new Guid(e.GetElementsByTagName("guid")[0].InnerText),
Name = e.GetElementsByTagName("name")[0].InnerText,
Text = e.GetElementsByTagName("text")[0].InnerText
});
}
catch { }
}
private static void Save()
{
XmlDocument xml = new XmlDocument();
xml.PreserveWhitespace = true;
xml.AppendChild(xml.CreateXmlDeclaration("1.0", null, null));
XmlNode root = xml.AppendChild(xml.CreateElement("customnames"));
foreach (Item i in list)
{
XmlNode item = root.OwnerDocument.CreateNode(XmlNodeType.Element, "item", root.BaseURI);
root.AppendChild(item);
XmlNode guid = item.OwnerDocument.CreateNode(XmlNodeType.Element, "guid", item.BaseURI);
item.AppendChild(guid);
guid.InnerText = i.Guid.ToString();
XmlNode name = item.OwnerDocument.CreateNode(XmlNodeType.Element, "name", item.BaseURI);
item.AppendChild(name);
name.InnerText = i.Name;
XmlNode text = item.OwnerDocument.CreateNode(XmlNodeType.Element, "text", item.BaseURI);
item.AppendChild(text);
text.InnerText = i.Text;
}
try { xml.Save(Path.Combine(Server.DataPath, "customnames.xml")); }
catch { }
}
}
}
|
AresChat/sb0t
|
commands/CustomNames.cs
|
C#
|
agpl-3.0
| 3,919
|
/**
* This file is part of Superdesk.
*
* Copyright 2015 Sourcefabric z.u. and contributors.
*
* For the full copyright and license information, please see the
* AUTHORS and LICENSE files distributed with this source code, or
* at https://www.sourcefabric.org/superdesk/license
*/
(function() {
'use strict';
WorkqueueService.$inject = ['session', 'api'];
function WorkqueueService(session, api) {
this.items = [];
/**
* Get all items locked by current user
*/
this.fetch = function() {
return session.getIdentity()
.then(angular.bind(this, function(identity) {
return api.query('archive', {source: {filter: {term: {lock_user: identity._id}}}})
.then(angular.bind(this, function(res) {
this.items = null;
this.items = res._items || [];
return this.items;
}));
}));
};
/**
* Update given item
*/
this.updateItem = function(itemId) {
var old = _.find(this.items, {_id: itemId});
if (old) {
return api.find('archive', itemId).then(function(item) {
return angular.extend(old, item);
});
}
};
}
WorkqueueCtrl.$inject = ['$scope', '$route', 'workqueue', 'authoringWorkspace', 'multiEdit', 'superdesk', 'lock', '$location'];
function WorkqueueCtrl($scope, $route, workqueue, authoringWorkspace, multiEdit, superdesk, lock, $location) {
$scope.active = null;
$scope.workqueue = workqueue;
$scope.multiEdit = multiEdit;
$scope.$on('item:lock', updateWorkqueue);
$scope.$on('item:unlock', updateWorkqueue);
$scope.$on('media_archive', function(e, data) {
workqueue.updateItem(data.item);
});
updateWorkqueue();
/**
* Update list of opened items and set one active if its id is in current route path.
*/
function updateWorkqueue() {
workqueue.fetch().then(function() {
var route = $route.current || {_id: null, params: {}};
$scope.isMultiedit = route._id === 'multiedit';
$scope.active = null;
if (route.params.item) {
$scope.active = _.find(workqueue.items, {_id: route.params.item});
}
});
}
$scope.openDashboard = function() {
superdesk.intent('author', 'dashboard');
};
/**
* Closes item. If item is opened, close authoring workspace.
* Updates multiedit items, if item is part of multiedit.
* When closing last item that was in multiedit(no more items in multiedit), redirects to monitoring.
*/
$scope.closeItem = function(item) {
lock.unlock(item);
if (authoringWorkspace.item && item._id === authoringWorkspace.item._id){
authoringWorkspace.close();
}
multiEdit.items = _.without(multiEdit.items, _.find(multiEdit.items, {article: item._id}));
if (multiEdit.items.length === 0){
$scope.redirectOnCloseMulti();
}
};
$scope.openMulti = function() {
$scope.isMultiedit = true;
multiEdit.open();
};
/**
* Close multiedit and all items that were in multiedit.
*/
$scope.closeMulti = function() {
multiEdit.exit();
_.forEach(multiEdit.items, function(item) {
lock.unlock(_.find(workqueue.items, {_id: item.article}));
});
$scope.redirectOnCloseMulti();
};
/**
* If multi edit screen is opened, redirect to monitoring.
*/
$scope.redirectOnCloseMulti = function() {
if (this.isMultiedit){
this.isMultiedit = false;
$location.url('/workspace/monitoring');
}
};
}
WorkqueueListDirective.$inject = ['$rootScope', 'authoringWorkspace', '$location'];
function WorkqueueListDirective($rootScope, authoringWorkspace, $location) {
return {
templateUrl: 'scripts/superdesk-authoring/views/opened-articles.html',
controller: 'Workqueue',
scope: {},
link: function(scope) {
scope.edit = function(item, event) {
if (!event.ctrlKey) {
scope.active = item;
authoringWorkspace.edit(item);
scope.redirectOnCloseMulti();
event.preventDefault();
}
};
scope.link = function(item) {
if (item) {
return $rootScope.link('authoring', item);
}
};
}
};
}
function ArticleDashboardDirective() {
return {
templateUrl: 'scripts/superdesk-authoring/views/dashboard-articles.html',
controller: 'Workqueue'
};
}
angular.module('superdesk.authoring.workqueue', [
'superdesk.activity',
'superdesk.notification',
'superdesk.authoring.multiedit'
])
.service('workqueue', WorkqueueService)
.controller('Workqueue', WorkqueueCtrl)
.directive('sdWorkqueue', WorkqueueListDirective)
.directive('sdDashboardArticles', ArticleDashboardDirective);
})();
|
amagdas/superdesk
|
client/app/scripts/superdesk-authoring/workqueue/workqueue.js
|
JavaScript
|
agpl-3.0
| 5,140
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<title></title>
<link href="css/mui.min.css" rel="stylesheet"/>
<link href="css/app.css" rel="stylesheet" />
<link href="css/main.css" rel="stylesheet" />
<link href="css/register.css" rel="stylesheet" />
</head>
<body>
<header class="mui-bar mui-bar-nav">
<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
<h1 class="mui-title">登陆/注册</h1>
</header>
<div class="mui-content">
<div class="regContainer">
<h3>注册</h3>
<div class="regPanel2">
<div class="mui-input-row">
<input id="reName" class="mui-input-clear" type="text" placeholder="姓名(真实姓名)" />
</div>
<div class="mui-input-row">
<input id="agentNo" class="mui-input-clear" type="text" placeholder="Agent ID NO." />
</div>
<div class="mui-input-row">
<input id="comName" class="mui-input-clear" type="text" placeholder="公司名称" />
</div>
<button id="next">下一步</button>
</div>
</div>
<img class="regStep" src="images/register/reg_step2.png" />
<div class="he250"></div>
</div>
<script src="js/mui.min.js"></script>
<script src="js/jquery-1.11.0.js"></script>
<script type="text/javascript" charset="UTF-8">
mui.plusReady(function(){
mui.init();
var self=plus.webview.currentWebview();
var registerData=self.registerData;
document.getElementById('next').addEventListener('tap', function() {
registerData.agent_no=$('#agentNo').val();
if(registerData.agent_no.trim()===""){
mui.toast('请输入agentNo');
return;
}
//打开注册页面
mui.openWindow({
url: 'register3.html',
id:'register3',
extras:{
registerData:registerData
}
});
});
})
</script>
</body>
</html>
|
zuofang/work
|
ruiyin-agent/register2.html
|
HTML
|
agpl-3.0
| 2,052
|
package nl.wietmazairac.bimql.set.attribute;
/******************************************************************************
* Copyright (C) 2009-2017 BIMserver.org
*
* 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 {@literal<http://www.gnu.org/licenses/>}.
*****************************************************************************/
public class SetAttributeSubIfcClassificationReference {
// fields
private Object object;
private String attributeName;
private String attributeNewValue;
// constructors
public SetAttributeSubIfcClassificationReference() {
}
public SetAttributeSubIfcClassificationReference(Object object, String attributeName, String attributeNewValue) {
this.object = object;
this.attributeName = attributeName;
this.attributeNewValue = attributeNewValue;
}
// methods
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
public String getAttributeName() {
return attributeName;
}
public void setAttributeName(String attributeName) {
this.attributeName = attributeName;
}
public String getAttributeNewValue() {
return attributeNewValue;
}
public void setAttributeNewValue(String attributeNewValue) {
this.attributeNewValue = attributeNewValue;
}
public void setAttribute() {
if (attributeName.equals("ReferencedSource")) {
//1NoEList
//1void
//1IfcClassification
}
}
}
|
opensourceBIM/bimql
|
BimQL/src/nl/wietmazairac/bimql/set/attribute/SetAttributeSubIfcClassificationReference.java
|
Java
|
agpl-3.0
| 2,056
|
<?php
/**
* @package Billing
* @copyright Copyright (C) 2012-2016 BillRun Technologies Ltd. All rights reserved.
* @license GNU Affero General Public License Version 3; see LICENSE.txt
*/
/**
* Billapi model for operations on BillRun entities
*
* @package Billapi
* @since 5.3
*/
class Models_Entity {
use Models_Verification;
/**
* Entirty available statuses values
*/
const FUTURE = 'future';
const EXPIRED = 'expired';
const ACTIVE = 'active';
const UNLIMITED_DATE = '+149 years';
/**
* The entity name
* @var string
*/
protected $entityName;
/**
* The DB collection name
* @var string
*/
protected $collectionName;
/**
* The DB collection
* @var Mongodloid_Collection
*/
protected $collection;
/**
* The entity billapi configuration
* @var array
*/
protected $config;
/**
* The wanted query
* @var array
*/
protected $query = array();
/**
* The new data
* @var array
*/
protected $update = array();
/**
* The update data from request without changes
* @var array
*/
protected $originalUpdate = array();
/**
* Additional data to save
* @var array
*/
protected $additional = array();
/**
* The update options
* @var array
*/
protected $queryOptions = array();
/**
* The wanted sort (for get operations)
* @var array
*/
protected $sort = array();
/**
* Page number for get operations
* @var int
*/
protected $page = 0;
/**
* Page size for get operations
* @var int
*/
protected $size = 10;
/**
* the entity before the change
*
* @var array
*/
protected $before = null;
/**
* the entity after the change
*
* @var array
*/
protected $after = null;
/**
* the previous revision of the entity
*
* @var array
*/
protected $previousEntry = null;
/**
* the line that was added as part of the action
*
* @var array
*/
protected $line = null;
/**
* the change action applied on the entity
*
* @var string
*/
protected $action = 'change';
/**
* Gets the minimum date for moving entities in time (unix timestamp)
*
* @var array (for multi day cycle mode - save minimum date to each invoicing day)
*/
protected static $minUpdateDatetime = [];
/**
* the change action applied on the entity
*
* @var string
*/
protected $availableOperations = array('query', 'update', 'sort');
/**
* Flag to indicate that action triggered by import
* @var Boolean
*/
protected $is_import = false;
public static function getInstance($params) {
$modelPrefix = 'Models_';
$className = $modelPrefix . ucfirst($params['collection']);
if (!@class_exists($className)) {
$className = $modelPrefix . 'Entity';
}
return new $className($params);
}
public function __construct($params) {
$this->entityName = $params['collection'];
if ($params['collection'] == 'accounts') { //TODO: remove coupling on this condition
$this->collectionName = 'subscribers';
} else {
$this->collectionName = $params['collection'];
}
$this->collection = Billrun_Factory::db()->{$this->collectionName . 'Collection'}();
Billrun_Factory::config()->addConfig(APPLICATION_PATH . '/conf/modules/billapi/' . $params['collection'] . '.ini');
$this->config = Billrun_Factory::config()->getConfigValue('billapi.' . $params['collection'], array());
if (isset($params['no_init']) && $params['no_init']) {
return;
}
if (isset($params['request']['action'])) {
$this->action = $params['request']['action'];
}
$this->init($params);
}
protected function init($params) {
$query = isset($params['request']['query']) ? @json_decode($params['request']['query'], TRUE) : array();
$update = isset($params['request']['update']) ? @json_decode($params['request']['update'], TRUE) : array();
$this->originalUpdate = $update;
$options = isset($params['request']['options']) ? @json_decode($params['request']['options'], TRUE) : array();
if (json_last_error() != JSON_ERROR_NONE) {
throw new Billrun_Exceptions_Api(0, array(), 'Input parsing error');
}
$customFields = $this->getCustomFields($update);
$duplicateCheck = isset($this->config['duplicate_check']) ? $this->config['duplicate_check'] : array();
$config = array_merge(array('fields' => Billrun_Factory::config()->getConfigValue($this->getCustomFieldsPath(), [])), $this->config[$this->action]);
list($translatedQuery, $translatedUpdate, $translatedQueryOptions) = $this->validateRequest($query, $update, $this->action, $config, 999999, true, $options, $duplicateCheck, $customFields);
$this->setQuery($translatedQuery);
$this->setUpdate($translatedUpdate);
$this->setQueryOptions($translatedQueryOptions);
foreach ($this->availableOperations as $operation) {
if (isset($params[$operation])) {
$this->{$operation} = $params[$operation];
}
}
$page = Billrun_Util::getFieldVal($params['page'], 0);
$this->page = Billrun_Util::IsIntegerValue($page) ? $page : 0;
$size = Billrun_Util::getFieldVal($params['size'], 10);
$this->size = Billrun_Util::IsIntegerValue($size) ? $size : 10;
if (isset($this->query['_id'])) {
$this->setBefore($this->loadById($this->query['_id']));
}
if (isset($this->config[$this->action]['custom_fields']) && $this->config[$this->action]['custom_fields']) {
$this->addCustomFields($this->config[$this->action]['custom_fields'], $update);
}
$this->is_import = isset($params['request']['is_import']) ? boolval($params['request']['is_import']) : false;
//transalte all date fields
Billrun_Utils_Mongo::convertQueryMongodloidDates($this->update);
}
/**
* method to retrieve entity name that we are running on
*
* @return string
*/
public function getEntityName() {
return $this->entityName;
}
/**
* method to retrieve action that we are running
*
* @return string
*/
public function getAction() {
return $this->action;
}
/**
* method to add entity custom fields values from request
*
* @param array $fields array of field settings
*/
protected function addCustomFields($fields, $originalUpdate) {
// $ad = $this->getCustomFields();
$customFields = $this->getCustomFields($this->update);
$additionalFields = array_column($customFields, 'field_name');
$mandatoryFields = array();
$uniqueFields = array();
$defaultFieldsValues = array();
$fieldTypes = array();
//all the options that value can be, so if selected will not throw an api exception.
$selectOptionsFields = array();
foreach ($customFields as $customField) {
$fieldName = $customField['field_name'];
$mandatoryFields[$fieldName] = Billrun_Util::getFieldVal($customField['mandatory'], false);
$uniqueFields[$fieldName] = Billrun_Util::getFieldVal($customField['unique'], false);
$defaultFieldsValues[$fieldName] = Billrun_Util::getFieldVal($customField['default_value'], null);
$fieldTypes[$fieldName] = Billrun_Util::getFieldVal($customField['type'], 'string');
$selectOptionsFields[$fieldName] = Billrun_Util::getFieldVal($customField['select_options'], null);
}
$defaultFields = array_column($this->config[$this->action]['update_parameters'], 'name');
if (is_null($defaultFields)) {
$defaultFields = array();
}
$customFields = array_diff($additionalFields, $defaultFields);
// print_R($customFields);
foreach ($customFields as $field) {
if ($this->action == 'create' && $mandatoryFields[$field] && (Billrun_Util::getIn($originalUpdate, $field, '') === '')) {
throw new Billrun_Exceptions_Api(0, array(), "Mandatory field: $field is missing");
}
$val = Billrun_Util::getIn($originalUpdate, $field, null);
$uniqueVal = Billrun_Util::getIn($originalUpdate, $field, Billrun_Util::getIn($this->before, $field, false));
if ($uniqueVal !== FALSE && $uniqueFields[$field] && $this->hasEntitiesWithSameUniqueFieldValue($originalUpdate, $field, $uniqueVal, $fieldTypes[$field])) {
throw new Billrun_Exceptions_Api(0, array(), "Unique field: $field has other entity with same value $uniqueVal");
}
if (!is_null($selectOptionsFields[$field])) {
$selectOptions = is_string($selectOptionsFields[$field]) ? explode(",", $selectOptionsFields[$field]) : $selectOptionsFields[$field];
if (!in_array($val, $selectOptions)) {
if(!$mandatoryFields[$field] && empty($val)){
$val = null;
}else{
throw new Billrun_Exceptions_Api(0, array(), "Invalid field: $field, with value: $val");
}
}
}
if (!is_null($val)) {
Billrun_Util::setIn($this->update, $field, $val);
} else if ($this->action === 'create' && !is_null($defaultFieldsValues[$field])) {
Billrun_Util::setIn($this->update, $field, $defaultFieldsValues[$field]);
}
}
// print_R($this->update);die;
}
protected function hasEntitiesWithSameUniqueFieldValue($data, $field, $val, $fieldType = 'string') {
$nonRevisionsQuery = $this->getNotRevisionsOfEntity($data);
if ($fieldType == 'ranges') {
$uniqueQuery = Api_Translator_RangesModel::getOverlapQuery($field, $val);
} else if (is_array($val)) {
$uniqueQuery = array($field => array('$in' => $val)); // not revisions of same entity, but has same unique value
} else {
$uniqueQuery = array($field => $val); // not revisions of same entity, but has same unique value
}
$startTime = strtotime(isset($data['from'])? $data['from'] : $this->getDefaultFrom());
$endTime = strtotime(isset($data['to'])? $data['to'] : $this->getDefaultTo());
$overlapingDatesQuery = Billrun_Utils_Mongo::getOverlappingWithRange('from', 'to', $startTime, $endTime);
$query = array('$and' => array($uniqueQuery, $overlapingDatesQuery));
if ($nonRevisionsQuery) {
$query['$and'][] = $nonRevisionsQuery;
}
return $this->collection->query($query)->count() > 0;
}
/**
* builds a query that gets all entities that are not revisions of the current entity
*
* @param type $data
*/
protected function getNotRevisionsOfEntity($data) {
$query = array();
foreach (Billrun_Util::getFieldVal($this->config['collection_subset_query'], []) as $fieldName => $fieldValue) {
$query[$fieldName] = $fieldValue;
}
$query['$or'] = array();
foreach (Billrun_Util::getFieldVal($this->config['duplicate_check'], []) as $fieldName) {
if (!isset($data[$fieldName])) {
$dupFieldVal = Billrun_Util::getIn($data, $fieldName, Billrun_Util::getIn($this->before, $fieldName, false));
$data[$fieldName] = $dupFieldVal;
}
$query['$or'][] = array(
$fieldName => array('$ne' => $data[$fieldName]),
);
}
if (empty($query['$or'])) {
unset($query['$or']);
}
return $query;
}
protected function getCustomFields($update = array()) {
return array_filter(Billrun_Factory::config()->getConfigValue($this->collectionName . ".fields", array()), function($customField) {
return !Billrun_Util::getFieldVal($customField['system'], false);
});
}
public function getCustomFieldsPath() {
return $this->collectionName . ".fields";
}
/**
* Create a new entity
* @param type $data the entity to create
* @return boolean
* @throws Billrun_Exceptions_Api
*/
public function create() {
$this->action = 'create';
unset($this->update['_id']);
if (empty($this->update['from'])) {
$this->update['from'] = new Mongodloid_Date();
}
if (empty($this->update['to'])) {
$this->update['to'] = new Mongodloid_Date(strtotime(self::UNLIMITED_DATE));
}
if (empty($this->update['creation_time'])) {
$this->update['creation_time'] = $this->update['from'];
}
if ($this->duplicateCheck($this->update)) {
$status = $this->insert($this->update);
$this->fixEntityFields($this->before);
$this->trackChanges($this->update['_id']);
return isset($status['ok']) && $status['ok'];
} else {
throw new Billrun_Exceptions_Api(0, array(), 'Entity already exists');
}
}
/**
* Performs the update action by a query and data to update
* @param array $query
* @param array $data
*/
public function update() {
$this->action = 'update';
$this->checkUpdate();
$this->fixEntityFields($this->before);
$this->trackChanges($this->query['_id']);
return true;
}
/**
* Performs the permanentchange action by a query.
*/
public function permanentChange() {
Billrun_Factory::log("Performs the permanentchange action", Zend_Log::DEBUG);
$this->action = 'permanentchange';
if (!$this->query || empty($this->query) || !isset($this->query['_id'])) {
return;
}
if ($this->update['from']->sec < $this->before['from']->sec || $this->update['from']->sec > $this->before['to']->sec) {
throw new Billrun_Exceptions_Api(1, array(), 'From field must be between ' . date('Y-m-d', $this->before['from']->sec) . ' to ' . date('Y-m-d', $this->before['to']->sec));
}
$this->protectKeyField();
$permanentQuery = $this->getPermanentChangeQuery();
$permanentUpdate = $this->getPermanentChangeUpdate();
$this->checkMinimumDate($this->update, 'from', 'Revision update');
$field = $this->getKeyField();
if ($this->update['from']->sec != $this->before['from']->sec && $this->update['from']->sec != $this->before['to']->sec) {
$res = $this->collection->update($this->query, array('$set' => array('to' => $this->update['from'])));
if (!isset($res['nModified']) || !$res['nModified']) {
return false;
}
if($this->before === null){
throw new Exception('No entity before the change was found. stack:' . print_r(debug_backtrace(), 1));
}
$newRevision = $this->before->getRawData();
$newRevision['to'] = $this->update['from'];
$key = $this->before[$field];
Billrun_AuditTrail_Util::trackChanges($this->action, $key, $this->entityName, $this->before->getRawData(), $newRevision);
$prevEntity = $this->before->getRawData();
unset($prevEntity['_id']);
$prevEntity['from'] = $this->update['from'];
$this->insert($prevEntity);
}
$beforeChangeRevisions = $this->collection->query($permanentQuery)->cursor();
$oldRevisions = iterator_to_array($beforeChangeRevisions);
$this->collection->update($permanentQuery, $permanentUpdate, array('multiple' => true));
$afterChangeRevisions = $this->collection->query($permanentQuery)->cursor();
$this->fixEntityFields($this->before);
foreach ($afterChangeRevisions as $newRevision) {
$currentId = $newRevision['_id']->getMongoId()->{'$id'};
$oldRevision = $oldRevisions[$currentId];
$key = $oldRevision[$field];
if($oldRevision === null){
throw new Exception('No old Revision was found. stack:' . print_r(debug_backtrace(), 1));
}
if ($newRevision === null){
throw new Exception('No new Revision was found. stack:' . print_r(debug_backtrace(), 1));
}
Billrun_AuditTrail_Util::trackChanges($this->action, $key, $this->entityName, $oldRevision->getRawData(), $newRevision->getRawData());
}
return true;
}
protected function getPermanentChangeQuery() {
$duplicateCheck = isset($this->config['duplicate_check']) ? $this->config['duplicate_check'] : array();
foreach ($duplicateCheck as $fieldName) {
$query[$fieldName] = $this->before[$fieldName];
}
$query['from'] = array('$gte' => $this->update['from']);
return $query;
}
protected function getPermanentChangeUpdate() {
$update = $this->update;
unset($update['from']);
return $this->generateUpdateParameter($update, $this->queryOptions);
}
/**
* Performs the changepassword action by a query and data to update
* @param array $query
* @param array $data
*/
public function changePassword() {
$this->action = 'changepassword';
$this->checkUpdate();
Billrun_Factory::log("Password changed successfully for " . $this->before['username'], Zend_Log::INFO);
return true;
}
protected function checkUpdate() {
if (!$this->query || empty($this->query) || !isset($this->query['_id'])) {
return;
}
$this->protectKeyField();
if ($this->preCheckUpdate() !== TRUE) {
return false;
}
$status = $this->dbUpdate($this->query, $this->update);
if (!isset($status['nModified']) || !$status['nModified']) {
return false;
}
}
/**
* method to check if the update is valid
* actual for update and closeandnew methods
*
* @throws Billrun_Exceptions_Api
*/
protected function preCheckUpdate($time = null) {
$ret = $this->checkDateRangeFields($time);
Billrun_Factory::dispatcher()->trigger('beforeBillApiUpdate', array($this->before, &$this->query, &$this->update, &$ret));
return $ret;
}
/**
* method to check date range fields
* by default checking only to field (not in the past)
*
* @param int $time (optional) unix timestamp for minimum to value
*
* @return true if check success else false
*/
protected function checkDateRangeFields($time = null) {
if (static::isAllowedChangeDuringClosedCycle()) {
return true;
}
if (is_null($time)) {
$time = time();
}
$invoicing_day = ($this instanceof Models_Accounts) ? $this->invoicing_day : null;
if (isset($this->before['to']->sec) && $this->before['to']->sec < self::getMinimumUpdateDate($invoicing_day)) {
return false;
}
return true;
}
/**
* method to close the current entity and open a new one (for in-advance changes of entities)
*
* @return mixed array of insert status, on failure false
*
* @todo avoid overlapping of entities
*/
public function closeandnew() {
$this->action = 'closeandnew';
if (!isset($this->update['from'])) {
$this->update['from'] = new Mongodloid_Date();
}
if (!is_null($this->before)) {
$prevEntity = $this->before->getRawData();
unset($prevEntity['_id']);
$this->update = array_merge($prevEntity, $this->update);
}
if ($this->preCheckUpdate() !== TRUE) {
return false;
}
$this->protectKeyField();
$this->checkMinimumDate($this->update, 'from', 'Revision update');
$this->verifyLastEntry();
if ($this->before['from']->sec >= $this->update['from']->sec) {
throw new Billrun_Exceptions_Api(1, array(), 'Revision update minimum date is ' . date('Y-m-d', $this->before['from']->sec));
return false;
}
$closeAndNewPreUpdateOperation = $this->getCloseAndNewPreUpdateCommand();
$res = $this->collection->update($this->query, $closeAndNewPreUpdateOperation);
if (!isset($res['nModified']) || !$res['nModified']) {
return false;
}
// $oldId = $this->query['_id'];
unset($this->update['_id']);
$status = $this->insert($this->update);
$newId = $this->update['_id'];
$this->fixEntityFields($this->before);
$this->trackChanges($newId);
return isset($status['ok']) && $status['ok'];
}
/**
* method to get the db command that run on close and new operation
*
* @return array db update command
*/
protected function getCloseAndNewPreUpdateCommand() {
return array(
'$set' => array(
'to' => new Mongodloid_Date($this->update['from']->sec)
)
);
}
/**
* method to protect key field update
* used on update & closeandnew operation
*/
protected function protectKeyField() {
$keyField = $this->getKeyField();
if (isset($this->update[$keyField]) && $this->update[$keyField] != $this->before[$keyField]) {
$this->update[$keyField] = $this->before[$keyField];
}
}
/**
* method get the minimum time to update
* @param string $invoicing_day - in multi day cycle system mode - need to send account's invoicing day
* @return unix timestamp
*/
public static function getMinimumUpdateDate($invoicing_day = null) {
if (empty(self::$minUpdateDatetime)) {
if (!Billrun_Factory::config()->isMultiDayCycle() && is_null($invoicing_day)) {
self::$minUpdateDatetime[0] = ($billrunKey = Billrun_Billingcycle::getLastNonRerunnableCycle()) ? Billrun_Billingcycle::getEndTime($billrunKey) : 0;
} else {
$invoicing_day = !is_null($invoicing_day) ? $invoicing_day : Billrun_Factory::config()->getConfigChargingDay();
self::$minUpdateDatetime[$invoicing_day] = ($billrunKey = Billrun_Billingcycle::getLastNonRerunnableCycle($invoicing_day)) ? Billrun_Billingcycle::getEndTime($billrunKey, $invoicing_day) : 0;
}
}
return is_null($invoicing_day) ? self::$minUpdateDatetime[0] : self::$minUpdateDatetime[$invoicing_day];
}
public static function isAllowedChangeDuringClosedCycle() {
return Billrun_Factory::config()->getConfigValue('system.closed_cycle_changes', false);
}
/**
* Gets an entity by a query
* @param array $query
* @param array $data
* @return array the entities found
*/
public function get() {
if (isset($this->config['active_documents']) && $this->config['active_documents']) {
$add_query = Billrun_Utils_Mongo::getDateBoundQuery();
$this->query = array_merge($add_query, $this->query);
}
$ret = $this->runQuery($this->query, $this->sort);
if (isset($this->config['get']['columns_filter_out']) && count($this->config['get']['columns_filter_out'])) {
$filter_columns = $this->config['get']['columns_filter_out'];
array_walk($ret, function(&$item) use ($filter_columns) {
$item = array_diff_key($item, array_flip($filter_columns));
});
}
return $ret;
}
/**
* Verify that an entity can be deleted.
*
* @return boolean
*/
protected function canEntityBeDeleted() {
return true;
}
/**
* method to check if the current query allocate the last entry
*
* @return boolean true if the last entry else false
*/
protected function verifyLastEntry() {
$entry = $this->collection->query($this->query)->cursor()->sort(array('_id' => 1))->current();
if (isset($entry['_id']) && $this->before['_id'] != $entry['_id']) {
throw new Billrun_Exceptions_Api(1500, array(), "Cannot remove old entries, but only the last created entry that exists");
}
return true;
}
/**
* method to check minimum date by the last billing cycle
*
* @param array $params the parameters the field exists
* @param string $field the field to check
* @param string $action the action that is checking
*
* @return true on success else false
*
* @throws Billrun_Exceptions_Api
*/
protected function checkMinimumDate($params, $field = 'to', $action = null) {
if (static::isAllowedChangeDuringClosedCycle()) {
return true;
}
if (is_null($action)) {
$action = $this->action;
}
$invoicing_day = ($this instanceof Models_Accounts) ? $this->invoicing_day : null;
$fromMinTime = self::getMinimumUpdateDate($invoicing_day);
if (isset($params[$field]->sec) && $params[$field]->sec < $fromMinTime) {
throw new Billrun_Exceptions_Api(1, array(), ucfirst($action) . ' minimum date is ' . date('Y-m-d', $fromMinTime));
return false;
}
return true;
}
/**
* Deletes an entity by a query
* @param array $query
* @param array $update
* @return type
*/
public function delete() {
$this->action = 'delete';
if (!$this->canEntityBeDeleted()) {
throw new Billrun_Exceptions_Api(2, array(), 'entity cannot be deleted');
}
if (!$this->validateQuery()) {
return false;
}
if (isset($this->config['collection_subset_query'])) {
foreach ($this->config['collection_subset_query'] as $key => $value) {
$this->query[$key] = $value;
}
}
$this->verifyLastEntry();
$this->checkMinimumDate($this->before, 'from');
$status = $this->remove($this->query); // TODO: check return value (success to remove?)
if (!isset($status['ok']) || !$status['ok']) {
return false;
}
$this->trackChanges(null); // assuming remove by _id
if ($this->shouldReopenPreviousEntry()) {
return $this->reopenPreviousEntry();
}
$this->fixEntityFields($this->before);
return true;
}
/**
* validates that the query is legitimate
*
* @return boolean
*/
protected function validateQuery() {
if (!$this->query || empty($this->query) || !isset($this->query['_id']) || !isset($this->before) && $this->before->isEmpty()) { // currently must have some query
return false;
}
return true;
}
/**
* make entity expired by setting to field with datetime of now
*
* @return boolean true on success else false
*/
public function close() {
$this->action = 'close';
if (!$this->query || empty($this->query)) { // currently must have some query
return;
}
if (!isset($this->update['to'])) {
$this->update = array(
'to' => new Mongodloid_Date()
);
}
$this->checkMinimumDate($this->update);
$status = $this->dbUpdate($this->query, $this->update);
if (!isset($status['nModified']) || !$status['nModified']) {
return false;
}
$this->fixEntityFields($this->before);
$this->trackChanges($this->query['_id']);
return true;
}
public function move() {
$this->action = 'move';
if (!$this->query || empty($this->query)) { // currently must have some query
return;
}
if (!isset($this->update['from']) && !isset($this->update['to'])) {
throw new Billrun_Exceptions_Api(0, array(), 'Move operation must have from or to input');
}
if (isset($this->update['from'])) { // default is move from
$ret = $this->moveEntry('from');
$this->fixEntityFields($this->before);
return $ret;
}
$ret = $this->moveEntry('to');
$this->fixEntityFields($this->before);
return $ret;
}
public function reopen() {
$this->action = 'reopen';
if (!$this->query || empty($this->query) || !isset($this->query['_id']) || !isset($this->before) || $this->before->isEmpty()) { // currently must have some query
return false;
}
if (!isset($this->update['from'])) {
throw new Billrun_Exceptions_Api(2, array(), 'reopen "from" field is missing');
}
$lastRevision = $this->getLastRevisionOfEntity($this->before, $this->collectionName);
if (!$lastRevision || !isset($lastRevision['to']) || !self::isItemExpired($lastRevision) || $lastRevision['to']->sec > $this->update['from']->sec) {
throw new Billrun_Exceptions_Api(3, array(), 'cannot reopen entity - reopen "from" date must be greater than last revision\'s "to" date');
}
$changeDuringClosedCycle = static::isAllowedChangeDuringClosedCycle();
$invoicing_day = ($this instanceof Models_Accounts) ? $this->invoicing_day : null;
if (!$changeDuringClosedCycle && $this->update['from']->sec < self::getMinimumUpdateDate($invoicing_day)) {
throw new Billrun_Exceptions_Api(3, array(), 'cannot reopen entity in a closed cycle');
}
$prevEntity = $this->before->getRawData();
$this->update = array_merge($prevEntity, $this->update);
unset($this->update['_id']);
$this->update['to'] = new Mongodloid_Date(strtotime(self::UNLIMITED_DATE));
$status = $this->insert($this->update);
$newId = $this->update['_id'];
$this->fixEntityFields($this->before);
$this->trackChanges($newId);
return isset($status['ok']) && $status['ok'];
}
/**
* move from date of entity including change the previous entity to field
*
* @return boolean true on success else false
*/
protected function moveEntry($edge = 'from') {
if ($edge == 'from') {
$otherEdge = 'to';
} else { // $current == 'to'
$otherEdge = 'from';
}
if (!isset($this->update[$edge])) {
$this->update = array(
$edge => new Mongodloid_Date()
);
}
if (($edge == 'from' && $this->update[$edge]->sec >= $this->before[$otherEdge]->sec) || ($edge == 'to' && $this->update[$edge]->sec <= $this->before[$otherEdge]->sec)) {
throw new Billrun_Exceptions_Api(0, array(), 'Requested start date greater than or equal to end date');
}
$this->checkMinimumDate($this->update, $edge);
$keyField = $this->getKeyField();
if ($edge == 'from') {
$query = array(
$keyField => $this->before[$keyField],
$otherEdge => array(
'$lte' => $this->before[$edge],
)
);
$sort = -1;
$rangeError = 'Requested start date is less than previous end date';
} else {
$query = array(
$keyField => $this->before[$keyField],
$otherEdge => array(
'$gte' => $this->before[$edge],
)
);
$sort = 1;
$rangeError = 'Requested end date is greater than next start date';
}
// previous entry on move from, next entry on move to
$followingEntry = $this->collection->query($query)->cursor()
->sort(array($otherEdge => $sort))
->current();
if (!empty($followingEntry) && !$followingEntry->isEmpty() && (
($edge == 'from' && $followingEntry[$edge]->sec > $this->update[$edge]->sec) ||
($edge == 'to' && $followingEntry[$edge]->sec < $this->update[$edge]->sec)
)
) {
throw new Billrun_Exceptions_Api(0, array(), $rangeError);
}
$status = $this->dbUpdate($this->query, $this->update);
if (!isset($status['nModified']) || !$status['nModified']) {
return false;
}
if ($edge == 'from') {
$this->updateCreationTime($keyField, $edge);
}
$this->trackChanges($this->query['_id']);
if (!empty($followingEntry) && !$followingEntry->isEmpty() && ($this->before[$edge]->sec === $followingEntry[$otherEdge]->sec)) {
$this->setQuery(array('_id' => $followingEntry['_id']->getMongoID()));
$this->setUpdate(array($otherEdge => new Mongodloid_Date($this->update[$edge]->sec)));
$this->setBefore($followingEntry);
return $this->update();
}
return true;
}
/**
* Convert keys that was received as dot annotation back to dot annotation
*/
protected function dataToDbUpdateFormat(&$data) {
foreach ($this->originalUpdate as $update_key => $value) {
$keys = explode('.', $update_key);
if (count($keys) > 1) {
$val = Billrun_Util::getIn($data, $update_key);
$data[$update_key] = $val;
Billrun_Util::unsetInPath($data, $keys, true);
}
}
}
protected function generateUpdateParameter($data, $options = array()) {
$update = array();
unset($data['_id']);
if(!empty($data)) {
$this->dataToDbUpdateFormat($data);
$update = array(
'$set' => $data,
);
}
if(!empty($options)) {
$update = array_merge($update, $options);
}
return $update;
}
/**
* DB update currently limited to update of one record
* @param type $query
* @param type $data
*/
protected function dbUpdate($query, $data) {
$update = $this->generateUpdateParameter($data, $this->queryOptions);
return $this->collection->update($query, $update);
}
/**
* Run a DB query against the current collection
* @param array $query
* @return array the result set
*/
protected function runQuery($query, $sort) {
$res = $this->collection->find($query);
if ($this->page != -1) {
$res->skip($this->page * $this->size);
}
if ($this->size != -1) {
$res->limit($this->size);
}
if ($sort) {
$res = $res->sort($sort);
}
$records = array_values(iterator_to_array($res));
foreach ($records as &$record) {
$record = Billrun_Utils_Mongo::recursiveConvertRecordMongodloidDatetimeFields($record);
}
return $records;
}
/**
* Performs a delete from the DB by a query
* @param array $query
*/
protected function remove($query) {
return $this->collection->remove($query);
}
/**
* gets the previous revision of the entity
*
* @return Mongodloid_Entity
*/
protected function getPreviousEntity() {
$key = $this->getKeyField();
$previousEntryQuery = array(
$key => $this->before[$key],
);
$previousEntrySort = array(
'_id' => -1
);
return $this->collection->query($previousEntryQuery)->cursor()
->sort($previousEntrySort)->limit(1)->current();
}
/**
* future entity was removed - checks if needs to reopen the previous entity
*
* @return boolean - is reopen required
*/
protected function shouldReopenPreviousEntry() {
$invoicing_day = ($this instanceof Models_Accounts) ? $this->invoicing_day : null;
if (!(isset($this->before['from']->sec) && $this->before['from']->sec >= self::getMinimumUpdateDate($invoicing_day))) {
return false;
}
$this->previousEntry = $this->getPreviousEntity();
return !$this->previousEntry->isEmpty() &&
($this->before['from'] == $this->previousEntry['to']);
}
/**
* future entity was removed - need to update the to of the previous change
*/
protected function reopenPreviousEntry() {
if (!$this->previousEntry->isEmpty()) {
$this->setQuery(array('_id' => $this->previousEntry['_id']->getMongoID()));
$this->setUpdate(array('to' => $this->before['to']));
$this->setBefore($this->previousEntry);
return $this->update();
}
return TRUE;
}
/**
* method to update the update instruct
* @param array $u mongo update instruct
*/
public function setUpdate($u) {
$this->update = $u;
}
/**
* method to update the update options instruct
* @param array $o mongo update options instruct
*/
public function setQueryOptions($o) {
$queryOptions = array();
if (isset($o['push_fields'])) {
foreach ($o['push_fields'] as $push_field) {
$queryOptions['$push'][$push_field['field_name']] = array(
'$each' => $push_field['field_values']
);
}
}
if (isset($o['pull_fields'])) {
foreach ($o['pull_fields'] as $pull_field) {
if(isset($pull_field['pull_by_key'])) {
$queryOptions['$pull'][$pull_field['field_name']][$pull_field['pull_by_key']]['$in'] = $pull_field['field_values'];
} else {
$queryOptions['$pull'][$pull_field['field_name']]['$in'] = $pull_field['field_values'];
}
}
}
$this->queryOptions = $queryOptions;
}
/**
* method to update the query instruct
* @param array $q mongo query instruct
*/
public function setQuery($q) {
$this->query = $q;
}
/**
* method to update the before entity
* @param array $b the before entity
*/
public function setBefore($b) {
$this->before = $b;
}
/**
* method to return the before state of the entity
*
* @return array $b the before state entity
*/
public function getBefore() {
return $this->before;
}
/**
* method to return the after state of the entity
*
* @return array $b the after state entity
*/
public function getAfter() {
return $this->after;
}
/**
* method to return the affected line
*
* @return array
*/
public function getAffectedLine() {
return $this->line;
}
/**
* method to track changes with audit trail
*
* @param MongoId $newId the new id; if null take from update array _id field
* @param MongoId $oldId the old id; if null this is new document (insert operation)
*
* @return boolean true on success else false
*/
protected function trackChanges($newId = null) {
$field = $this->getKeyField();
if (is_null($newId) && isset($this->update['_id'])) {
$newId = $this->update['_id'];
}
if ($newId) {
$this->after = $this->loadById($newId, true);
}
$old = !is_null($this->before) ? $this->before->getRawData() : null;
$new = !is_null($this->after) ? $this->after->getRawData() : null;
$key = isset($this->update[$field]) ? $this->update[$field] :
(isset($this->before[$field]) ? $this->before[$field] : null);
return Billrun_AuditTrail_Util::trackChanges($this->action, $key, $this->entityName, $old, $new);
}
/**
* method to load the entity from DB by _id
*
* @param mixed $id MongoId or id (string) of the entity
*
* @return array the entity loaded
*/
protected function loadById($id, $readPrimary = false) {
$fetchQuery = array('_id' => ($id instanceof Mongodloid_Id) ? $id : new Mongodloid_Id($id));
$cursor = $this->collection->query($fetchQuery)->cursor();
if ($readPrimary) {
$cursor->setReadPreference('RP_PRIMARY');
}
return $cursor->current();
}
/**
* Inserts a document to the DB, as is
* @param array $data
*/
protected function insert(&$data) {
$ret = $this->collection->insert($data, array('w' => 1, 'j' => true));
return $ret;
}
/**
* Returns true if current record does not overlap with existing records in the DB
* @param array $data
* @param array $ignoreIds
* @return boolean
*/
protected function duplicateCheck($data, $ignoreIds = array()) {
$query = array();
foreach (Billrun_Util::getFieldVal($this->config['duplicate_check'], []) as $fieldName) {
$query[$fieldName] = $data[$fieldName];
}
if ($ignoreIds) {
$query['_id'] = array(
'$nin' => $ignoreIds,
);
}
return $query ? !$this->collection->query($query)->count() : TRUE;
}
/**
* Return the key field by collection
*
* @return String
*/
protected function getKeyField() {
switch ($this->collectionName) {
case 'users':
return 'username';
case 'discounts':
case 'reports':
case 'taxes':
case 'rates':
return 'key';
default:
return 'name';
}
}
/**
* Add revision info (status, early_expiration) to record
*
* @param array $record - Record to set revision info.
* @param string $collection - Record collection
*
* @return The record with revision info.
*/
public static function setRevisionInfo($record, $collection, $entityName) {
$status = self::getStatus($record, $collection);
$isLast = self::getIsLast($record, $collection, $entityName);
$earlyExpiration = self::isEarlyExpiration($record, $status, $isLast);
$invoicing_day = in_array('invoicing_day', array_keys($record)) ? (!is_null($record['invoicing_day']) ? $record['invoicing_day'] : Billrun_Factory::config()->getConfigChargingDay()) : null;
$isCurrentCycle = $record['from']->sec >= self::getMinimumUpdateDate($invoicing_day);
$record['revision_info'] = array(
"status" => $status,
"is_last" => $isLast,
"early_expiration" => $earlyExpiration,
"updatable" => $isCurrentCycle,
"closeandnewable" => $isCurrentCycle,
"movable" => $isCurrentCycle,
"removable" => $isCurrentCycle,
"movable_from" => self::isDateMovable($record['from']->sec, $invoicing_day),
"movable_to" => self::isDateMovable($record['to']->sec, $invoicing_day)
);
return $record;
}
protected static function isDateMovable($timestamp, $invoicing_day = null) {
if (static::isAllowedChangeDuringClosedCycle()) {
return true;
}
$chosen_invoicing_day = is_null($invoicing_day) ? Billrun_Factory::config()->getConfigChargingDay() : $invoicing_day;
return self::getMinimumUpdateDate($chosen_invoicing_day) <= $timestamp;
}
/**
* Calculate record status
*
* @param array $record - Record to set revision info.
* @param string $collection - Record collection name
*
* @return string Status, available values are: "future", "expired", "active"
*/
static function getStatus($record, $collection) {
if ($record['to']->sec < time()) {
return self::EXPIRED;
}
if ($record['from']->sec > time()) {
return self::FUTURE;
}
return self::ACTIVE;
}
/**
* Calculate record status
*
* @param array $record - Record to set revision info.
* @param string $collection - Record collection name
* @param string $entityName - Record entity name
*
* @return string Status, available values are: "future", "expired", "active"
*/
static function getIsLast($record, $collection, $entityName) {
// For active records, check if it has furure revisions
$query = Billrun_Utils_Mongo::getDateBoundQuery($record['to']->sec, true, $record['to']->usec);
$uniqueFields = Billrun_Factory::config()->getConfigValue("billapi.{$entityName}.duplicate_check", array());
foreach ($uniqueFields as $fieldName) {
$query[$fieldName] = $record[$fieldName];
}
$recordCollection = Billrun_Factory::db()->{$collection . 'Collection'}();
return $recordCollection->query($query)->count() === 0;
}
/**
* Check if record was closed by close action.
* true if the "to" field is less than 50 years from record "from" date.
*
* @param array $record - Record to set revision info.
* @param string $status - Record status, available values are: "expired", "active", "future"
*
* @return bool
*/
protected static function isEarlyExpiration($record, $status, $isLast) {
if ($status === self::FUTURE || ($status === self::ACTIVE && $isLast)) {
return self::isItemExpired($record);
}
return false;
}
public function getCollectionName() {
return $this->collectionName;
}
public function getCollection() {
return $this->collection;
}
public function getMatchSubQuery() {
$query = array();
foreach (Billrun_Util::getFieldVal($this->config['collection_subset_query'], []) as $fieldName => $fieldValue) {
$query[$fieldName] = $fieldValue;
}
return $query;
}
protected function updateCreationTime($keyField, $edge) {
if(isset($this->update['_id'])) {
$queryCreation = array(
$keyField => $this->before[$keyField],
);
$firstRevision = $this->collection->query($queryCreation)->cursor()->sort(array($edge => 1))->limit(1)->current();
if ($this->update['_id'] == strval($firstRevision->getId())) {
$this->collection->update($queryCreation, array('$set' => array('creation_time' => $this->update[$edge])), array('multiple' => 1));
}
}
}
/**
* checks if item is not "unlimited", which means it has an expiration date
*
* @param array $item
* @param string $expiredField
* @return boolean
*/
protected static function isItemExpired($item, $expiredField = 'to') {
return $item[$expiredField]->sec < strtotime("+10 years");
}
/**
* gets the last revision of the entity (might be expired, active, future)
*
* @param array $entity
*/
public function getLastRevisionOfEntity($entity) {
$query = array();
foreach (Billrun_Util::getFieldVal($this->config['duplicate_check'], []) as $fieldName) {
$query[$fieldName] = $entity[$fieldName];
}
$sort = array('_id' => -1);
return $this->collection->find($query)->sort($sort)->limit(1)->getNext();
}
protected function fixEntityFields($entity) {
return;
}
protected function getDefaultFrom() {
switch ($this->action) {
case 'permanentchange':
return '1970-01-02 00:00:00';
case 'create':
return Billrun_Util::generateCurrentTime();
default:
return $this->before['from'];
}
}
protected function getDefaultTo() {
switch ($this->action) {
case 'permanentchange':
case 'create':
return '+100 years';
default:
return $this->before['to'];
}
}
protected function validateAdditionalData($additional) {
if (!is_array($additional)) {
return [];
}
return $additional;
}
}
|
BillRun/system
|
application/modules/Billapi/Models/Entity.php
|
PHP
|
agpl-3.0
| 42,017
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.