filename
stringlengths 4
51
| language
stringclasses 51
values | vulnerable_code
stringlengths 6
3.06M
⌀ | fixed_code
stringlengths 6
3.06M
| commit_id
stringlengths 40
40
| repository_url
stringlengths 26
73
|
|---|---|---|---|---|---|
controller.php
|
php
|
<?php
dd(User::all());
|
<?php
|
269320e0e0e06a1785e1a1556da769a34280b7e6
|
https://github.com/microweber/microweber
|
trace.h
|
objective-c
|
/* SPDX-License-Identifier: GPL-2.0 */
/*
* Copyright (c) 2014 Christoph Hellwig.
*/
#undef TRACE_SYSTEM
#define TRACE_SYSTEM nfsd
#if !defined(_NFSD_TRACE_H) || defined(TRACE_HEADER_MULTI_READ)
#define _NFSD_TRACE_H
#include <linux/tracepoint.h>
#include "export.h"
#include "nfsfh.h"
#define NFSD_TRACE_PROC_ARG_FIELDS \
__field(unsigned int, netns_ino) \
__field(u32, xid) \
__array(unsigned char, server, sizeof(struct sockaddr_in6)) \
__array(unsigned char, client, sizeof(struct sockaddr_in6))
#define NFSD_TRACE_PROC_ARG_ASSIGNMENTS \
do { \
__entry->netns_ino = SVC_NET(rqstp)->ns.inum; \
__entry->xid = be32_to_cpu(rqstp->rq_xid); \
memcpy(__entry->server, &rqstp->rq_xprt->xpt_local, \
rqstp->rq_xprt->xpt_locallen); \
memcpy(__entry->client, &rqstp->rq_xprt->xpt_remote, \
rqstp->rq_xprt->xpt_remotelen); \
} while (0);
#define NFSD_TRACE_PROC_RES_FIELDS \
__field(unsigned int, netns_ino) \
__field(u32, xid) \
__field(unsigned long, status) \
__array(unsigned char, server, sizeof(struct sockaddr_in6)) \
__array(unsigned char, client, sizeof(struct sockaddr_in6))
#define NFSD_TRACE_PROC_RES_ASSIGNMENTS(error) \
do { \
__entry->netns_ino = SVC_NET(rqstp)->ns.inum; \
__entry->xid = be32_to_cpu(rqstp->rq_xid); \
__entry->status = be32_to_cpu(error); \
memcpy(__entry->server, &rqstp->rq_xprt->xpt_local, \
rqstp->rq_xprt->xpt_locallen); \
memcpy(__entry->client, &rqstp->rq_xprt->xpt_remote, \
rqstp->rq_xprt->xpt_remotelen); \
} while (0);
TRACE_EVENT(nfsd_garbage_args_err,
TP_PROTO(
const struct svc_rqst *rqstp
),
TP_ARGS(rqstp),
TP_STRUCT__entry(
NFSD_TRACE_PROC_ARG_FIELDS
__field(u32, vers)
__field(u32, proc)
),
TP_fast_assign(
NFSD_TRACE_PROC_ARG_ASSIGNMENTS
__entry->vers = rqstp->rq_vers;
__entry->proc = rqstp->rq_proc;
),
TP_printk("xid=0x%08x vers=%u proc=%u",
__entry->xid, __entry->vers, __entry->proc
)
);
TRACE_EVENT(nfsd_cant_encode_err,
TP_PROTO(
const struct svc_rqst *rqstp
),
TP_ARGS(rqstp),
TP_STRUCT__entry(
NFSD_TRACE_PROC_ARG_FIELDS
__field(u32, vers)
__field(u32, proc)
),
TP_fast_assign(
NFSD_TRACE_PROC_ARG_ASSIGNMENTS
__entry->vers = rqstp->rq_vers;
__entry->proc = rqstp->rq_proc;
),
TP_printk("xid=0x%08x vers=%u proc=%u",
__entry->xid, __entry->vers, __entry->proc
)
);
#define show_nfsd_may_flags(x) \
__print_flags(x, "|", \
{ NFSD_MAY_EXEC, "EXEC" }, \
{ NFSD_MAY_WRITE, "WRITE" }, \
{ NFSD_MAY_READ, "READ" }, \
{ NFSD_MAY_SATTR, "SATTR" }, \
{ NFSD_MAY_TRUNC, "TRUNC" }, \
{ NFSD_MAY_LOCK, "LOCK" }, \
{ NFSD_MAY_OWNER_OVERRIDE, "OWNER_OVERRIDE" }, \
{ NFSD_MAY_LOCAL_ACCESS, "LOCAL_ACCESS" }, \
{ NFSD_MAY_BYPASS_GSS_ON_ROOT, "BYPASS_GSS_ON_ROOT" }, \
{ NFSD_MAY_NOT_BREAK_LEASE, "NOT_BREAK_LEASE" }, \
{ NFSD_MAY_BYPASS_GSS, "BYPASS_GSS" }, \
{ NFSD_MAY_READ_IF_EXEC, "READ_IF_EXEC" }, \
{ NFSD_MAY_64BIT_COOKIE, "64BIT_COOKIE" })
TRACE_EVENT(nfsd_compound,
TP_PROTO(const struct svc_rqst *rqst,
u32 args_opcnt),
TP_ARGS(rqst, args_opcnt),
TP_STRUCT__entry(
__field(u32, xid)
__field(u32, args_opcnt)
),
TP_fast_assign(
__entry->xid = be32_to_cpu(rqst->rq_xid);
__entry->args_opcnt = args_opcnt;
),
TP_printk("xid=0x%08x opcnt=%u",
__entry->xid, __entry->args_opcnt)
)
TRACE_EVENT(nfsd_compound_status,
TP_PROTO(u32 args_opcnt,
u32 resp_opcnt,
__be32 status,
const char *name),
TP_ARGS(args_opcnt, resp_opcnt, status, name),
TP_STRUCT__entry(
__field(u32, args_opcnt)
__field(u32, resp_opcnt)
__field(int, status)
__string(name, name)
),
TP_fast_assign(
__entry->args_opcnt = args_opcnt;
__entry->resp_opcnt = resp_opcnt;
__entry->status = be32_to_cpu(status);
__assign_str(name, name);
),
TP_printk("op=%u/%u %s status=%d",
__entry->resp_opcnt, __entry->args_opcnt,
__get_str(name), __entry->status)
)
TRACE_EVENT(nfsd_compound_decode_err,
TP_PROTO(
const struct svc_rqst *rqstp,
u32 args_opcnt,
u32 resp_opcnt,
u32 opnum,
__be32 status
),
TP_ARGS(rqstp, args_opcnt, resp_opcnt, opnum, status),
TP_STRUCT__entry(
NFSD_TRACE_PROC_RES_FIELDS
__field(u32, args_opcnt)
__field(u32, resp_opcnt)
__field(u32, opnum)
),
TP_fast_assign(
NFSD_TRACE_PROC_RES_ASSIGNMENTS(status)
__entry->args_opcnt = args_opcnt;
__entry->resp_opcnt = resp_opcnt;
__entry->opnum = opnum;
),
TP_printk("op=%u/%u opnum=%u status=%lu",
__entry->resp_opcnt, __entry->args_opcnt,
__entry->opnum, __entry->status)
);
TRACE_EVENT(nfsd_compound_encode_err,
TP_PROTO(
const struct svc_rqst *rqstp,
u32 opnum,
__be32 status
),
TP_ARGS(rqstp, opnum, status),
TP_STRUCT__entry(
NFSD_TRACE_PROC_RES_FIELDS
__field(u32, opnum)
),
TP_fast_assign(
NFSD_TRACE_PROC_RES_ASSIGNMENTS(status)
__entry->opnum = opnum;
),
TP_printk("opnum=%u status=%lu",
__entry->opnum, __entry->status)
);
DECLARE_EVENT_CLASS(nfsd_fh_err_class,
TP_PROTO(struct svc_rqst *rqstp,
struct svc_fh *fhp,
int status),
TP_ARGS(rqstp, fhp, status),
TP_STRUCT__entry(
__field(u32, xid)
__field(u32, fh_hash)
__field(int, status)
),
TP_fast_assign(
__entry->xid = be32_to_cpu(rqstp->rq_xid);
__entry->fh_hash = knfsd_fh_hash(&fhp->fh_handle);
__entry->status = status;
),
TP_printk("xid=0x%08x fh_hash=0x%08x status=%d",
__entry->xid, __entry->fh_hash,
__entry->status)
)
#define DEFINE_NFSD_FH_ERR_EVENT(name) \
DEFINE_EVENT(nfsd_fh_err_class, nfsd_##name, \
TP_PROTO(struct svc_rqst *rqstp, \
struct svc_fh *fhp, \
int status), \
TP_ARGS(rqstp, fhp, status))
DEFINE_NFSD_FH_ERR_EVENT(set_fh_dentry_badexport);
DEFINE_NFSD_FH_ERR_EVENT(set_fh_dentry_badhandle);
TRACE_EVENT(nfsd_exp_find_key,
TP_PROTO(const struct svc_expkey *key,
int status),
TP_ARGS(key, status),
TP_STRUCT__entry(
__field(int, fsidtype)
__array(u32, fsid, 6)
__string(auth_domain, key->ek_client->name)
__field(int, status)
),
TP_fast_assign(
__entry->fsidtype = key->ek_fsidtype;
memcpy(__entry->fsid, key->ek_fsid, 4*6);
__assign_str(auth_domain, key->ek_client->name);
__entry->status = status;
),
TP_printk("fsid=%x::%s domain=%s status=%d",
__entry->fsidtype,
__print_array(__entry->fsid, 6, 4),
__get_str(auth_domain),
__entry->status
)
);
TRACE_EVENT(nfsd_expkey_update,
TP_PROTO(const struct svc_expkey *key, const char *exp_path),
TP_ARGS(key, exp_path),
TP_STRUCT__entry(
__field(int, fsidtype)
__array(u32, fsid, 6)
__string(auth_domain, key->ek_client->name)
__string(path, exp_path)
__field(bool, cache)
),
TP_fast_assign(
__entry->fsidtype = key->ek_fsidtype;
memcpy(__entry->fsid, key->ek_fsid, 4*6);
__assign_str(auth_domain, key->ek_client->name);
__assign_str(path, exp_path);
__entry->cache = !test_bit(CACHE_NEGATIVE, &key->h.flags);
),
TP_printk("fsid=%x::%s domain=%s path=%s cache=%s",
__entry->fsidtype,
__print_array(__entry->fsid, 6, 4),
__get_str(auth_domain),
__get_str(path),
__entry->cache ? "pos" : "neg"
)
);
TRACE_EVENT(nfsd_exp_get_by_name,
TP_PROTO(const struct svc_export *key,
int status),
TP_ARGS(key, status),
TP_STRUCT__entry(
__string(path, key->ex_path.dentry->d_name.name)
__string(auth_domain, key->ex_client->name)
__field(int, status)
),
TP_fast_assign(
__assign_str(path, key->ex_path.dentry->d_name.name);
__assign_str(auth_domain, key->ex_client->name);
__entry->status = status;
),
TP_printk("path=%s domain=%s status=%d",
__get_str(path),
__get_str(auth_domain),
__entry->status
)
);
TRACE_EVENT(nfsd_export_update,
TP_PROTO(const struct svc_export *key),
TP_ARGS(key),
TP_STRUCT__entry(
__string(path, key->ex_path.dentry->d_name.name)
__string(auth_domain, key->ex_client->name)
__field(bool, cache)
),
TP_fast_assign(
__assign_str(path, key->ex_path.dentry->d_name.name);
__assign_str(auth_domain, key->ex_client->name);
__entry->cache = !test_bit(CACHE_NEGATIVE, &key->h.flags);
),
TP_printk("path=%s domain=%s cache=%s",
__get_str(path),
__get_str(auth_domain),
__entry->cache ? "pos" : "neg"
)
);
DECLARE_EVENT_CLASS(nfsd_io_class,
TP_PROTO(struct svc_rqst *rqstp,
struct svc_fh *fhp,
loff_t offset,
unsigned long len),
TP_ARGS(rqstp, fhp, offset, len),
TP_STRUCT__entry(
__field(u32, xid)
__field(u32, fh_hash)
__field(loff_t, offset)
__field(unsigned long, len)
),
TP_fast_assign(
__entry->xid = be32_to_cpu(rqstp->rq_xid);
__entry->fh_hash = knfsd_fh_hash(&fhp->fh_handle);
__entry->offset = offset;
__entry->len = len;
),
TP_printk("xid=0x%08x fh_hash=0x%08x offset=%lld len=%lu",
__entry->xid, __entry->fh_hash,
__entry->offset, __entry->len)
)
#define DEFINE_NFSD_IO_EVENT(name) \
DEFINE_EVENT(nfsd_io_class, nfsd_##name, \
TP_PROTO(struct svc_rqst *rqstp, \
struct svc_fh *fhp, \
loff_t offset, \
unsigned long len), \
TP_ARGS(rqstp, fhp, offset, len))
DEFINE_NFSD_IO_EVENT(read_start);
DEFINE_NFSD_IO_EVENT(read_splice);
DEFINE_NFSD_IO_EVENT(read_vector);
DEFINE_NFSD_IO_EVENT(read_io_done);
DEFINE_NFSD_IO_EVENT(read_done);
DEFINE_NFSD_IO_EVENT(write_start);
DEFINE_NFSD_IO_EVENT(write_opened);
DEFINE_NFSD_IO_EVENT(write_io_done);
DEFINE_NFSD_IO_EVENT(write_done);
DECLARE_EVENT_CLASS(nfsd_err_class,
TP_PROTO(struct svc_rqst *rqstp,
struct svc_fh *fhp,
loff_t offset,
int status),
TP_ARGS(rqstp, fhp, offset, status),
TP_STRUCT__entry(
__field(u32, xid)
__field(u32, fh_hash)
__field(loff_t, offset)
__field(int, status)
),
TP_fast_assign(
__entry->xid = be32_to_cpu(rqstp->rq_xid);
__entry->fh_hash = knfsd_fh_hash(&fhp->fh_handle);
__entry->offset = offset;
__entry->status = status;
),
TP_printk("xid=0x%08x fh_hash=0x%08x offset=%lld status=%d",
__entry->xid, __entry->fh_hash,
__entry->offset, __entry->status)
)
#define DEFINE_NFSD_ERR_EVENT(name) \
DEFINE_EVENT(nfsd_err_class, nfsd_##name, \
TP_PROTO(struct svc_rqst *rqstp, \
struct svc_fh *fhp, \
loff_t offset, \
int len), \
TP_ARGS(rqstp, fhp, offset, len))
DEFINE_NFSD_ERR_EVENT(read_err);
DEFINE_NFSD_ERR_EVENT(write_err);
TRACE_EVENT(nfsd_dirent,
TP_PROTO(struct svc_fh *fhp,
u64 ino,
const char *name,
int namlen),
TP_ARGS(fhp, ino, name, namlen),
TP_STRUCT__entry(
__field(u32, fh_hash)
__field(u64, ino)
__field(int, len)
__dynamic_array(unsigned char, name, namlen)
),
TP_fast_assign(
__entry->fh_hash = fhp ? knfsd_fh_hash(&fhp->fh_handle) : 0;
__entry->ino = ino;
__entry->len = namlen;
memcpy(__get_str(name), name, namlen);
__assign_str(name, name);
),
TP_printk("fh_hash=0x%08x ino=%llu name=%.*s",
__entry->fh_hash, __entry->ino,
__entry->len, __get_str(name))
)
#include "state.h"
#include "filecache.h"
#include "vfs.h"
DECLARE_EVENT_CLASS(nfsd_stateid_class,
TP_PROTO(stateid_t *stp),
TP_ARGS(stp),
TP_STRUCT__entry(
__field(u32, cl_boot)
__field(u32, cl_id)
__field(u32, si_id)
__field(u32, si_generation)
),
TP_fast_assign(
__entry->cl_boot = stp->si_opaque.so_clid.cl_boot;
__entry->cl_id = stp->si_opaque.so_clid.cl_id;
__entry->si_id = stp->si_opaque.so_id;
__entry->si_generation = stp->si_generation;
),
TP_printk("client %08x:%08x stateid %08x:%08x",
__entry->cl_boot,
__entry->cl_id,
__entry->si_id,
__entry->si_generation)
)
#define DEFINE_STATEID_EVENT(name) \
DEFINE_EVENT(nfsd_stateid_class, nfsd_##name, \
TP_PROTO(stateid_t *stp), \
TP_ARGS(stp))
DEFINE_STATEID_EVENT(layoutstate_alloc);
DEFINE_STATEID_EVENT(layoutstate_unhash);
DEFINE_STATEID_EVENT(layoutstate_free);
DEFINE_STATEID_EVENT(layout_get_lookup_fail);
DEFINE_STATEID_EVENT(layout_commit_lookup_fail);
DEFINE_STATEID_EVENT(layout_return_lookup_fail);
DEFINE_STATEID_EVENT(layout_recall);
DEFINE_STATEID_EVENT(layout_recall_done);
DEFINE_STATEID_EVENT(layout_recall_fail);
DEFINE_STATEID_EVENT(layout_recall_release);
DEFINE_STATEID_EVENT(open);
DEFINE_STATEID_EVENT(deleg_read);
DEFINE_STATEID_EVENT(deleg_recall);
DECLARE_EVENT_CLASS(nfsd_stateseqid_class,
TP_PROTO(u32 seqid, const stateid_t *stp),
TP_ARGS(seqid, stp),
TP_STRUCT__entry(
__field(u32, seqid)
__field(u32, cl_boot)
__field(u32, cl_id)
__field(u32, si_id)
__field(u32, si_generation)
),
TP_fast_assign(
__entry->seqid = seqid;
__entry->cl_boot = stp->si_opaque.so_clid.cl_boot;
__entry->cl_id = stp->si_opaque.so_clid.cl_id;
__entry->si_id = stp->si_opaque.so_id;
__entry->si_generation = stp->si_generation;
),
TP_printk("seqid=%u client %08x:%08x stateid %08x:%08x",
__entry->seqid, __entry->cl_boot, __entry->cl_id,
__entry->si_id, __entry->si_generation)
)
#define DEFINE_STATESEQID_EVENT(name) \
DEFINE_EVENT(nfsd_stateseqid_class, nfsd_##name, \
TP_PROTO(u32 seqid, const stateid_t *stp), \
TP_ARGS(seqid, stp))
DEFINE_STATESEQID_EVENT(preprocess);
DEFINE_STATESEQID_EVENT(open_confirm);
DECLARE_EVENT_CLASS(nfsd_clientid_class,
TP_PROTO(const clientid_t *clid),
TP_ARGS(clid),
TP_STRUCT__entry(
__field(u32, cl_boot)
__field(u32, cl_id)
),
TP_fast_assign(
__entry->cl_boot = clid->cl_boot;
__entry->cl_id = clid->cl_id;
),
TP_printk("client %08x:%08x", __entry->cl_boot, __entry->cl_id)
)
#define DEFINE_CLIENTID_EVENT(name) \
DEFINE_EVENT(nfsd_clientid_class, nfsd_clid_##name, \
TP_PROTO(const clientid_t *clid), \
TP_ARGS(clid))
DEFINE_CLIENTID_EVENT(expire_unconf);
DEFINE_CLIENTID_EVENT(reclaim_complete);
DEFINE_CLIENTID_EVENT(confirmed);
DEFINE_CLIENTID_EVENT(destroyed);
DEFINE_CLIENTID_EVENT(admin_expired);
DEFINE_CLIENTID_EVENT(replaced);
DEFINE_CLIENTID_EVENT(purged);
DEFINE_CLIENTID_EVENT(renew);
DEFINE_CLIENTID_EVENT(stale);
DECLARE_EVENT_CLASS(nfsd_net_class,
TP_PROTO(const struct nfsd_net *nn),
TP_ARGS(nn),
TP_STRUCT__entry(
__field(unsigned long long, boot_time)
),
TP_fast_assign(
__entry->boot_time = nn->boot_time;
),
TP_printk("boot_time=%16llx", __entry->boot_time)
)
#define DEFINE_NET_EVENT(name) \
DEFINE_EVENT(nfsd_net_class, nfsd_##name, \
TP_PROTO(const struct nfsd_net *nn), \
TP_ARGS(nn))
DEFINE_NET_EVENT(grace_start);
DEFINE_NET_EVENT(grace_complete);
TRACE_EVENT(nfsd_clid_cred_mismatch,
TP_PROTO(
const struct nfs4_client *clp,
const struct svc_rqst *rqstp
),
TP_ARGS(clp, rqstp),
TP_STRUCT__entry(
__field(u32, cl_boot)
__field(u32, cl_id)
__field(unsigned long, cl_flavor)
__field(unsigned long, new_flavor)
__array(unsigned char, addr, sizeof(struct sockaddr_in6))
),
TP_fast_assign(
__entry->cl_boot = clp->cl_clientid.cl_boot;
__entry->cl_id = clp->cl_clientid.cl_id;
__entry->cl_flavor = clp->cl_cred.cr_flavor;
__entry->new_flavor = rqstp->rq_cred.cr_flavor;
memcpy(__entry->addr, &rqstp->rq_xprt->xpt_remote,
sizeof(struct sockaddr_in6));
),
TP_printk("client %08x:%08x flavor=%s, conflict=%s from addr=%pISpc",
__entry->cl_boot, __entry->cl_id,
show_nfsd_authflavor(__entry->cl_flavor),
show_nfsd_authflavor(__entry->new_flavor), __entry->addr
)
)
TRACE_EVENT(nfsd_clid_verf_mismatch,
TP_PROTO(
const struct nfs4_client *clp,
const struct svc_rqst *rqstp,
const nfs4_verifier *verf
),
TP_ARGS(clp, rqstp, verf),
TP_STRUCT__entry(
__field(u32, cl_boot)
__field(u32, cl_id)
__array(unsigned char, cl_verifier, NFS4_VERIFIER_SIZE)
__array(unsigned char, new_verifier, NFS4_VERIFIER_SIZE)
__array(unsigned char, addr, sizeof(struct sockaddr_in6))
),
TP_fast_assign(
__entry->cl_boot = clp->cl_clientid.cl_boot;
__entry->cl_id = clp->cl_clientid.cl_id;
memcpy(__entry->cl_verifier, (void *)&clp->cl_verifier,
NFS4_VERIFIER_SIZE);
memcpy(__entry->new_verifier, (void *)verf,
NFS4_VERIFIER_SIZE);
memcpy(__entry->addr, &rqstp->rq_xprt->xpt_remote,
sizeof(struct sockaddr_in6));
),
TP_printk("client %08x:%08x verf=0x%s, updated=0x%s from addr=%pISpc",
__entry->cl_boot, __entry->cl_id,
__print_hex_str(__entry->cl_verifier, NFS4_VERIFIER_SIZE),
__print_hex_str(__entry->new_verifier, NFS4_VERIFIER_SIZE),
__entry->addr
)
);
DECLARE_EVENT_CLASS(nfsd_clid_class,
TP_PROTO(const struct nfs4_client *clp),
TP_ARGS(clp),
TP_STRUCT__entry(
__field(u32, cl_boot)
__field(u32, cl_id)
__array(unsigned char, addr, sizeof(struct sockaddr_in6))
__field(unsigned long, flavor)
__array(unsigned char, verifier, NFS4_VERIFIER_SIZE)
__dynamic_array(char, name, clp->cl_name.len + 1)
),
TP_fast_assign(
__entry->cl_boot = clp->cl_clientid.cl_boot;
__entry->cl_id = clp->cl_clientid.cl_id;
memcpy(__entry->addr, &clp->cl_addr,
sizeof(struct sockaddr_in6));
__entry->flavor = clp->cl_cred.cr_flavor;
memcpy(__entry->verifier, (void *)&clp->cl_verifier,
NFS4_VERIFIER_SIZE);
memcpy(__get_str(name), clp->cl_name.data, clp->cl_name.len);
__get_str(name)[clp->cl_name.len] = '\0';
),
TP_printk("addr=%pISpc name='%s' verifier=0x%s flavor=%s client=%08x:%08x",
__entry->addr, __get_str(name),
__print_hex_str(__entry->verifier, NFS4_VERIFIER_SIZE),
show_nfsd_authflavor(__entry->flavor),
__entry->cl_boot, __entry->cl_id)
);
#define DEFINE_CLID_EVENT(name) \
DEFINE_EVENT(nfsd_clid_class, nfsd_clid_##name, \
TP_PROTO(const struct nfs4_client *clp), \
TP_ARGS(clp))
DEFINE_CLID_EVENT(fresh);
DEFINE_CLID_EVENT(confirmed_r);
/*
* from fs/nfsd/filecache.h
*/
TRACE_DEFINE_ENUM(NFSD_FILE_HASHED);
TRACE_DEFINE_ENUM(NFSD_FILE_PENDING);
TRACE_DEFINE_ENUM(NFSD_FILE_BREAK_READ);
TRACE_DEFINE_ENUM(NFSD_FILE_BREAK_WRITE);
TRACE_DEFINE_ENUM(NFSD_FILE_REFERENCED);
#define show_nf_flags(val) \
__print_flags(val, "|", \
{ 1 << NFSD_FILE_HASHED, "HASHED" }, \
{ 1 << NFSD_FILE_PENDING, "PENDING" }, \
{ 1 << NFSD_FILE_BREAK_READ, "BREAK_READ" }, \
{ 1 << NFSD_FILE_BREAK_WRITE, "BREAK_WRITE" }, \
{ 1 << NFSD_FILE_REFERENCED, "REFERENCED"})
DECLARE_EVENT_CLASS(nfsd_file_class,
TP_PROTO(struct nfsd_file *nf),
TP_ARGS(nf),
TP_STRUCT__entry(
__field(unsigned int, nf_hashval)
__field(void *, nf_inode)
__field(int, nf_ref)
__field(unsigned long, nf_flags)
__field(unsigned char, nf_may)
__field(struct file *, nf_file)
),
TP_fast_assign(
__entry->nf_hashval = nf->nf_hashval;
__entry->nf_inode = nf->nf_inode;
__entry->nf_ref = refcount_read(&nf->nf_ref);
__entry->nf_flags = nf->nf_flags;
__entry->nf_may = nf->nf_may;
__entry->nf_file = nf->nf_file;
),
TP_printk("hash=0x%x inode=%p ref=%d flags=%s may=%s file=%p",
__entry->nf_hashval,
__entry->nf_inode,
__entry->nf_ref,
show_nf_flags(__entry->nf_flags),
show_nfsd_may_flags(__entry->nf_may),
__entry->nf_file)
)
#define DEFINE_NFSD_FILE_EVENT(name) \
DEFINE_EVENT(nfsd_file_class, name, \
TP_PROTO(struct nfsd_file *nf), \
TP_ARGS(nf))
DEFINE_NFSD_FILE_EVENT(nfsd_file_alloc);
DEFINE_NFSD_FILE_EVENT(nfsd_file_put_final);
DEFINE_NFSD_FILE_EVENT(nfsd_file_unhash);
DEFINE_NFSD_FILE_EVENT(nfsd_file_put);
DEFINE_NFSD_FILE_EVENT(nfsd_file_unhash_and_release_locked);
TRACE_EVENT(nfsd_file_acquire,
TP_PROTO(struct svc_rqst *rqstp, unsigned int hash,
struct inode *inode, unsigned int may_flags,
struct nfsd_file *nf, __be32 status),
TP_ARGS(rqstp, hash, inode, may_flags, nf, status),
TP_STRUCT__entry(
__field(u32, xid)
__field(unsigned int, hash)
__field(void *, inode)
__field(unsigned long, may_flags)
__field(int, nf_ref)
__field(unsigned long, nf_flags)
__field(unsigned long, nf_may)
__field(struct file *, nf_file)
__field(u32, status)
),
TP_fast_assign(
__entry->xid = be32_to_cpu(rqstp->rq_xid);
__entry->hash = hash;
__entry->inode = inode;
__entry->may_flags = may_flags;
__entry->nf_ref = nf ? refcount_read(&nf->nf_ref) : 0;
__entry->nf_flags = nf ? nf->nf_flags : 0;
__entry->nf_may = nf ? nf->nf_may : 0;
__entry->nf_file = nf ? nf->nf_file : NULL;
__entry->status = be32_to_cpu(status);
),
TP_printk("xid=0x%x hash=0x%x inode=%p may_flags=%s ref=%d nf_flags=%s nf_may=%s nf_file=%p status=%u",
__entry->xid, __entry->hash, __entry->inode,
show_nfsd_may_flags(__entry->may_flags),
__entry->nf_ref, show_nf_flags(__entry->nf_flags),
show_nfsd_may_flags(__entry->nf_may),
__entry->nf_file, __entry->status)
);
DECLARE_EVENT_CLASS(nfsd_file_search_class,
TP_PROTO(struct inode *inode, unsigned int hash, int found),
TP_ARGS(inode, hash, found),
TP_STRUCT__entry(
__field(struct inode *, inode)
__field(unsigned int, hash)
__field(int, found)
),
TP_fast_assign(
__entry->inode = inode;
__entry->hash = hash;
__entry->found = found;
),
TP_printk("hash=0x%x inode=%p found=%d", __entry->hash,
__entry->inode, __entry->found)
);
#define DEFINE_NFSD_FILE_SEARCH_EVENT(name) \
DEFINE_EVENT(nfsd_file_search_class, name, \
TP_PROTO(struct inode *inode, unsigned int hash, int found), \
TP_ARGS(inode, hash, found))
DEFINE_NFSD_FILE_SEARCH_EVENT(nfsd_file_close_inode_sync);
DEFINE_NFSD_FILE_SEARCH_EVENT(nfsd_file_close_inode);
DEFINE_NFSD_FILE_SEARCH_EVENT(nfsd_file_is_cached);
TRACE_EVENT(nfsd_file_fsnotify_handle_event,
TP_PROTO(struct inode *inode, u32 mask),
TP_ARGS(inode, mask),
TP_STRUCT__entry(
__field(struct inode *, inode)
__field(unsigned int, nlink)
__field(umode_t, mode)
__field(u32, mask)
),
TP_fast_assign(
__entry->inode = inode;
__entry->nlink = inode->i_nlink;
__entry->mode = inode->i_mode;
__entry->mask = mask;
),
TP_printk("inode=%p nlink=%u mode=0%ho mask=0x%x", __entry->inode,
__entry->nlink, __entry->mode, __entry->mask)
);
#include "cache.h"
TRACE_DEFINE_ENUM(RC_DROPIT);
TRACE_DEFINE_ENUM(RC_REPLY);
TRACE_DEFINE_ENUM(RC_DOIT);
#define show_drc_retval(x) \
__print_symbolic(x, \
{ RC_DROPIT, "DROPIT" }, \
{ RC_REPLY, "REPLY" }, \
{ RC_DOIT, "DOIT" })
TRACE_EVENT(nfsd_drc_found,
TP_PROTO(
const struct nfsd_net *nn,
const struct svc_rqst *rqstp,
int result
),
TP_ARGS(nn, rqstp, result),
TP_STRUCT__entry(
__field(unsigned long long, boot_time)
__field(unsigned long, result)
__field(u32, xid)
),
TP_fast_assign(
__entry->boot_time = nn->boot_time;
__entry->result = result;
__entry->xid = be32_to_cpu(rqstp->rq_xid);
),
TP_printk("boot_time=%16llx xid=0x%08x result=%s",
__entry->boot_time, __entry->xid,
show_drc_retval(__entry->result))
);
TRACE_EVENT(nfsd_drc_mismatch,
TP_PROTO(
const struct nfsd_net *nn,
const struct svc_cacherep *key,
const struct svc_cacherep *rp
),
TP_ARGS(nn, key, rp),
TP_STRUCT__entry(
__field(unsigned long long, boot_time)
__field(u32, xid)
__field(u32, cached)
__field(u32, ingress)
),
TP_fast_assign(
__entry->boot_time = nn->boot_time;
__entry->xid = be32_to_cpu(key->c_key.k_xid);
__entry->cached = (__force u32)key->c_key.k_csum;
__entry->ingress = (__force u32)rp->c_key.k_csum;
),
TP_printk("boot_time=%16llx xid=0x%08x cached-csum=0x%08x ingress-csum=0x%08x",
__entry->boot_time, __entry->xid, __entry->cached,
__entry->ingress)
);
TRACE_EVENT(nfsd_cb_args,
TP_PROTO(
const struct nfs4_client *clp,
const struct nfs4_cb_conn *conn
),
TP_ARGS(clp, conn),
TP_STRUCT__entry(
__field(u32, cl_boot)
__field(u32, cl_id)
__field(u32, prog)
__field(u32, ident)
__array(unsigned char, addr, sizeof(struct sockaddr_in6))
),
TP_fast_assign(
__entry->cl_boot = clp->cl_clientid.cl_boot;
__entry->cl_id = clp->cl_clientid.cl_id;
__entry->prog = conn->cb_prog;
__entry->ident = conn->cb_ident;
memcpy(__entry->addr, &conn->cb_addr,
sizeof(struct sockaddr_in6));
),
TP_printk("addr=%pISpc client %08x:%08x prog=%u ident=%u",
__entry->addr, __entry->cl_boot, __entry->cl_id,
__entry->prog, __entry->ident)
);
TRACE_EVENT(nfsd_cb_nodelegs,
TP_PROTO(const struct nfs4_client *clp),
TP_ARGS(clp),
TP_STRUCT__entry(
__field(u32, cl_boot)
__field(u32, cl_id)
),
TP_fast_assign(
__entry->cl_boot = clp->cl_clientid.cl_boot;
__entry->cl_id = clp->cl_clientid.cl_id;
),
TP_printk("client %08x:%08x", __entry->cl_boot, __entry->cl_id)
)
#define show_cb_state(val) \
__print_symbolic(val, \
{ NFSD4_CB_UP, "UP" }, \
{ NFSD4_CB_UNKNOWN, "UNKNOWN" }, \
{ NFSD4_CB_DOWN, "DOWN" }, \
{ NFSD4_CB_FAULT, "FAULT"})
DECLARE_EVENT_CLASS(nfsd_cb_class,
TP_PROTO(const struct nfs4_client *clp),
TP_ARGS(clp),
TP_STRUCT__entry(
__field(unsigned long, state)
__field(u32, cl_boot)
__field(u32, cl_id)
__array(unsigned char, addr, sizeof(struct sockaddr_in6))
),
TP_fast_assign(
__entry->state = clp->cl_cb_state;
__entry->cl_boot = clp->cl_clientid.cl_boot;
__entry->cl_id = clp->cl_clientid.cl_id;
memcpy(__entry->addr, &clp->cl_cb_conn.cb_addr,
sizeof(struct sockaddr_in6));
),
TP_printk("addr=%pISpc client %08x:%08x state=%s",
__entry->addr, __entry->cl_boot, __entry->cl_id,
show_cb_state(__entry->state))
);
#define DEFINE_NFSD_CB_EVENT(name) \
DEFINE_EVENT(nfsd_cb_class, nfsd_cb_##name, \
TP_PROTO(const struct nfs4_client *clp), \
TP_ARGS(clp))
DEFINE_NFSD_CB_EVENT(state);
DEFINE_NFSD_CB_EVENT(probe);
DEFINE_NFSD_CB_EVENT(lost);
DEFINE_NFSD_CB_EVENT(shutdown);
TRACE_DEFINE_ENUM(RPC_AUTH_NULL);
TRACE_DEFINE_ENUM(RPC_AUTH_UNIX);
TRACE_DEFINE_ENUM(RPC_AUTH_GSS);
TRACE_DEFINE_ENUM(RPC_AUTH_GSS_KRB5);
TRACE_DEFINE_ENUM(RPC_AUTH_GSS_KRB5I);
TRACE_DEFINE_ENUM(RPC_AUTH_GSS_KRB5P);
#define show_nfsd_authflavor(val) \
__print_symbolic(val, \
{ RPC_AUTH_NULL, "none" }, \
{ RPC_AUTH_UNIX, "sys" }, \
{ RPC_AUTH_GSS, "gss" }, \
{ RPC_AUTH_GSS_KRB5, "krb5" }, \
{ RPC_AUTH_GSS_KRB5I, "krb5i" }, \
{ RPC_AUTH_GSS_KRB5P, "krb5p" })
TRACE_EVENT(nfsd_cb_setup,
TP_PROTO(const struct nfs4_client *clp,
const char *netid,
rpc_authflavor_t authflavor
),
TP_ARGS(clp, netid, authflavor),
TP_STRUCT__entry(
__field(u32, cl_boot)
__field(u32, cl_id)
__field(unsigned long, authflavor)
__array(unsigned char, addr, sizeof(struct sockaddr_in6))
__array(unsigned char, netid, 8)
),
TP_fast_assign(
__entry->cl_boot = clp->cl_clientid.cl_boot;
__entry->cl_id = clp->cl_clientid.cl_id;
strlcpy(__entry->netid, netid, sizeof(__entry->netid));
__entry->authflavor = authflavor;
memcpy(__entry->addr, &clp->cl_cb_conn.cb_addr,
sizeof(struct sockaddr_in6));
),
TP_printk("addr=%pISpc client %08x:%08x proto=%s flavor=%s",
__entry->addr, __entry->cl_boot, __entry->cl_id,
__entry->netid, show_nfsd_authflavor(__entry->authflavor))
);
TRACE_EVENT(nfsd_cb_setup_err,
TP_PROTO(
const struct nfs4_client *clp,
long error
),
TP_ARGS(clp, error),
TP_STRUCT__entry(
__field(long, error)
__field(u32, cl_boot)
__field(u32, cl_id)
__array(unsigned char, addr, sizeof(struct sockaddr_in6))
),
TP_fast_assign(
__entry->error = error;
__entry->cl_boot = clp->cl_clientid.cl_boot;
__entry->cl_id = clp->cl_clientid.cl_id;
memcpy(__entry->addr, &clp->cl_cb_conn.cb_addr,
sizeof(struct sockaddr_in6));
),
TP_printk("addr=%pISpc client %08x:%08x error=%ld",
__entry->addr, __entry->cl_boot, __entry->cl_id, __entry->error)
);
TRACE_EVENT(nfsd_cb_recall,
TP_PROTO(
const struct nfs4_stid *stid
),
TP_ARGS(stid),
TP_STRUCT__entry(
__field(u32, cl_boot)
__field(u32, cl_id)
__field(u32, si_id)
__field(u32, si_generation)
__array(unsigned char, addr, sizeof(struct sockaddr_in6))
),
TP_fast_assign(
const stateid_t *stp = &stid->sc_stateid;
const struct nfs4_client *clp = stid->sc_client;
__entry->cl_boot = stp->si_opaque.so_clid.cl_boot;
__entry->cl_id = stp->si_opaque.so_clid.cl_id;
__entry->si_id = stp->si_opaque.so_id;
__entry->si_generation = stp->si_generation;
if (clp)
memcpy(__entry->addr, &clp->cl_cb_conn.cb_addr,
sizeof(struct sockaddr_in6));
else
memset(__entry->addr, 0, sizeof(struct sockaddr_in6));
),
TP_printk("addr=%pISpc client %08x:%08x stateid %08x:%08x",
__entry->addr, __entry->cl_boot, __entry->cl_id,
__entry->si_id, __entry->si_generation)
);
TRACE_EVENT(nfsd_cb_notify_lock,
TP_PROTO(
const struct nfs4_lockowner *lo,
const struct nfsd4_blocked_lock *nbl
),
TP_ARGS(lo, nbl),
TP_STRUCT__entry(
__field(u32, cl_boot)
__field(u32, cl_id)
__field(u32, fh_hash)
__array(unsigned char, addr, sizeof(struct sockaddr_in6))
),
TP_fast_assign(
const struct nfs4_client *clp = lo->lo_owner.so_client;
__entry->cl_boot = clp->cl_clientid.cl_boot;
__entry->cl_id = clp->cl_clientid.cl_id;
__entry->fh_hash = knfsd_fh_hash(&nbl->nbl_fh);
memcpy(__entry->addr, &clp->cl_cb_conn.cb_addr,
sizeof(struct sockaddr_in6));
),
TP_printk("addr=%pISpc client %08x:%08x fh_hash=0x%08x",
__entry->addr, __entry->cl_boot, __entry->cl_id,
__entry->fh_hash)
);
TRACE_EVENT(nfsd_cb_offload,
TP_PROTO(
const struct nfs4_client *clp,
const stateid_t *stp,
const struct knfsd_fh *fh,
u64 count,
__be32 status
),
TP_ARGS(clp, stp, fh, count, status),
TP_STRUCT__entry(
__field(u32, cl_boot)
__field(u32, cl_id)
__field(u32, si_id)
__field(u32, si_generation)
__field(u32, fh_hash)
__field(int, status)
__field(u64, count)
__array(unsigned char, addr, sizeof(struct sockaddr_in6))
),
TP_fast_assign(
__entry->cl_boot = stp->si_opaque.so_clid.cl_boot;
__entry->cl_id = stp->si_opaque.so_clid.cl_id;
__entry->si_id = stp->si_opaque.so_id;
__entry->si_generation = stp->si_generation;
__entry->fh_hash = knfsd_fh_hash(fh);
__entry->status = be32_to_cpu(status);
__entry->count = count;
memcpy(__entry->addr, &clp->cl_cb_conn.cb_addr,
sizeof(struct sockaddr_in6));
),
TP_printk("addr=%pISpc client %08x:%08x stateid %08x:%08x fh_hash=0x%08x count=%llu status=%d",
__entry->addr, __entry->cl_boot, __entry->cl_id,
__entry->si_id, __entry->si_generation,
__entry->fh_hash, __entry->count, __entry->status)
);
#endif /* _NFSD_TRACE_H */
#undef TRACE_INCLUDE_PATH
#define TRACE_INCLUDE_PATH .
#define TRACE_INCLUDE_FILE trace
#include <trace/define_trace.h>
|
/* SPDX-License-Identifier: GPL-2.0 */
/*
* Copyright (c) 2014 Christoph Hellwig.
*/
#undef TRACE_SYSTEM
#define TRACE_SYSTEM nfsd
#if !defined(_NFSD_TRACE_H) || defined(TRACE_HEADER_MULTI_READ)
#define _NFSD_TRACE_H
#include <linux/tracepoint.h>
#include "export.h"
#include "nfsfh.h"
#define NFSD_TRACE_PROC_ARG_FIELDS \
__field(unsigned int, netns_ino) \
__field(u32, xid) \
__array(unsigned char, server, sizeof(struct sockaddr_in6)) \
__array(unsigned char, client, sizeof(struct sockaddr_in6))
#define NFSD_TRACE_PROC_ARG_ASSIGNMENTS \
do { \
__entry->netns_ino = SVC_NET(rqstp)->ns.inum; \
__entry->xid = be32_to_cpu(rqstp->rq_xid); \
memcpy(__entry->server, &rqstp->rq_xprt->xpt_local, \
rqstp->rq_xprt->xpt_locallen); \
memcpy(__entry->client, &rqstp->rq_xprt->xpt_remote, \
rqstp->rq_xprt->xpt_remotelen); \
} while (0);
#define NFSD_TRACE_PROC_RES_FIELDS \
__field(unsigned int, netns_ino) \
__field(u32, xid) \
__field(unsigned long, status) \
__array(unsigned char, server, sizeof(struct sockaddr_in6)) \
__array(unsigned char, client, sizeof(struct sockaddr_in6))
#define NFSD_TRACE_PROC_RES_ASSIGNMENTS(error) \
do { \
__entry->netns_ino = SVC_NET(rqstp)->ns.inum; \
__entry->xid = be32_to_cpu(rqstp->rq_xid); \
__entry->status = be32_to_cpu(error); \
memcpy(__entry->server, &rqstp->rq_xprt->xpt_local, \
rqstp->rq_xprt->xpt_locallen); \
memcpy(__entry->client, &rqstp->rq_xprt->xpt_remote, \
rqstp->rq_xprt->xpt_remotelen); \
} while (0);
TRACE_EVENT(nfsd_garbage_args_err,
TP_PROTO(
const struct svc_rqst *rqstp
),
TP_ARGS(rqstp),
TP_STRUCT__entry(
NFSD_TRACE_PROC_ARG_FIELDS
__field(u32, vers)
__field(u32, proc)
),
TP_fast_assign(
NFSD_TRACE_PROC_ARG_ASSIGNMENTS
__entry->vers = rqstp->rq_vers;
__entry->proc = rqstp->rq_proc;
),
TP_printk("xid=0x%08x vers=%u proc=%u",
__entry->xid, __entry->vers, __entry->proc
)
);
TRACE_EVENT(nfsd_cant_encode_err,
TP_PROTO(
const struct svc_rqst *rqstp
),
TP_ARGS(rqstp),
TP_STRUCT__entry(
NFSD_TRACE_PROC_ARG_FIELDS
__field(u32, vers)
__field(u32, proc)
),
TP_fast_assign(
NFSD_TRACE_PROC_ARG_ASSIGNMENTS
__entry->vers = rqstp->rq_vers;
__entry->proc = rqstp->rq_proc;
),
TP_printk("xid=0x%08x vers=%u proc=%u",
__entry->xid, __entry->vers, __entry->proc
)
);
#define show_nfsd_may_flags(x) \
__print_flags(x, "|", \
{ NFSD_MAY_EXEC, "EXEC" }, \
{ NFSD_MAY_WRITE, "WRITE" }, \
{ NFSD_MAY_READ, "READ" }, \
{ NFSD_MAY_SATTR, "SATTR" }, \
{ NFSD_MAY_TRUNC, "TRUNC" }, \
{ NFSD_MAY_LOCK, "LOCK" }, \
{ NFSD_MAY_OWNER_OVERRIDE, "OWNER_OVERRIDE" }, \
{ NFSD_MAY_LOCAL_ACCESS, "LOCAL_ACCESS" }, \
{ NFSD_MAY_BYPASS_GSS_ON_ROOT, "BYPASS_GSS_ON_ROOT" }, \
{ NFSD_MAY_NOT_BREAK_LEASE, "NOT_BREAK_LEASE" }, \
{ NFSD_MAY_BYPASS_GSS, "BYPASS_GSS" }, \
{ NFSD_MAY_READ_IF_EXEC, "READ_IF_EXEC" }, \
{ NFSD_MAY_64BIT_COOKIE, "64BIT_COOKIE" })
TRACE_EVENT(nfsd_compound,
TP_PROTO(const struct svc_rqst *rqst,
u32 args_opcnt),
TP_ARGS(rqst, args_opcnt),
TP_STRUCT__entry(
__field(u32, xid)
__field(u32, args_opcnt)
),
TP_fast_assign(
__entry->xid = be32_to_cpu(rqst->rq_xid);
__entry->args_opcnt = args_opcnt;
),
TP_printk("xid=0x%08x opcnt=%u",
__entry->xid, __entry->args_opcnt)
)
TRACE_EVENT(nfsd_compound_status,
TP_PROTO(u32 args_opcnt,
u32 resp_opcnt,
__be32 status,
const char *name),
TP_ARGS(args_opcnt, resp_opcnt, status, name),
TP_STRUCT__entry(
__field(u32, args_opcnt)
__field(u32, resp_opcnt)
__field(int, status)
__string(name, name)
),
TP_fast_assign(
__entry->args_opcnt = args_opcnt;
__entry->resp_opcnt = resp_opcnt;
__entry->status = be32_to_cpu(status);
__assign_str(name, name);
),
TP_printk("op=%u/%u %s status=%d",
__entry->resp_opcnt, __entry->args_opcnt,
__get_str(name), __entry->status)
)
TRACE_EVENT(nfsd_compound_decode_err,
TP_PROTO(
const struct svc_rqst *rqstp,
u32 args_opcnt,
u32 resp_opcnt,
u32 opnum,
__be32 status
),
TP_ARGS(rqstp, args_opcnt, resp_opcnt, opnum, status),
TP_STRUCT__entry(
NFSD_TRACE_PROC_RES_FIELDS
__field(u32, args_opcnt)
__field(u32, resp_opcnt)
__field(u32, opnum)
),
TP_fast_assign(
NFSD_TRACE_PROC_RES_ASSIGNMENTS(status)
__entry->args_opcnt = args_opcnt;
__entry->resp_opcnt = resp_opcnt;
__entry->opnum = opnum;
),
TP_printk("op=%u/%u opnum=%u status=%lu",
__entry->resp_opcnt, __entry->args_opcnt,
__entry->opnum, __entry->status)
);
TRACE_EVENT(nfsd_compound_encode_err,
TP_PROTO(
const struct svc_rqst *rqstp,
u32 opnum,
__be32 status
),
TP_ARGS(rqstp, opnum, status),
TP_STRUCT__entry(
NFSD_TRACE_PROC_RES_FIELDS
__field(u32, opnum)
),
TP_fast_assign(
NFSD_TRACE_PROC_RES_ASSIGNMENTS(status)
__entry->opnum = opnum;
),
TP_printk("opnum=%u status=%lu",
__entry->opnum, __entry->status)
);
DECLARE_EVENT_CLASS(nfsd_fh_err_class,
TP_PROTO(struct svc_rqst *rqstp,
struct svc_fh *fhp,
int status),
TP_ARGS(rqstp, fhp, status),
TP_STRUCT__entry(
__field(u32, xid)
__field(u32, fh_hash)
__field(int, status)
),
TP_fast_assign(
__entry->xid = be32_to_cpu(rqstp->rq_xid);
__entry->fh_hash = knfsd_fh_hash(&fhp->fh_handle);
__entry->status = status;
),
TP_printk("xid=0x%08x fh_hash=0x%08x status=%d",
__entry->xid, __entry->fh_hash,
__entry->status)
)
#define DEFINE_NFSD_FH_ERR_EVENT(name) \
DEFINE_EVENT(nfsd_fh_err_class, nfsd_##name, \
TP_PROTO(struct svc_rqst *rqstp, \
struct svc_fh *fhp, \
int status), \
TP_ARGS(rqstp, fhp, status))
DEFINE_NFSD_FH_ERR_EVENT(set_fh_dentry_badexport);
DEFINE_NFSD_FH_ERR_EVENT(set_fh_dentry_badhandle);
TRACE_EVENT(nfsd_exp_find_key,
TP_PROTO(const struct svc_expkey *key,
int status),
TP_ARGS(key, status),
TP_STRUCT__entry(
__field(int, fsidtype)
__array(u32, fsid, 6)
__string(auth_domain, key->ek_client->name)
__field(int, status)
),
TP_fast_assign(
__entry->fsidtype = key->ek_fsidtype;
memcpy(__entry->fsid, key->ek_fsid, 4*6);
__assign_str(auth_domain, key->ek_client->name);
__entry->status = status;
),
TP_printk("fsid=%x::%s domain=%s status=%d",
__entry->fsidtype,
__print_array(__entry->fsid, 6, 4),
__get_str(auth_domain),
__entry->status
)
);
TRACE_EVENT(nfsd_expkey_update,
TP_PROTO(const struct svc_expkey *key, const char *exp_path),
TP_ARGS(key, exp_path),
TP_STRUCT__entry(
__field(int, fsidtype)
__array(u32, fsid, 6)
__string(auth_domain, key->ek_client->name)
__string(path, exp_path)
__field(bool, cache)
),
TP_fast_assign(
__entry->fsidtype = key->ek_fsidtype;
memcpy(__entry->fsid, key->ek_fsid, 4*6);
__assign_str(auth_domain, key->ek_client->name);
__assign_str(path, exp_path);
__entry->cache = !test_bit(CACHE_NEGATIVE, &key->h.flags);
),
TP_printk("fsid=%x::%s domain=%s path=%s cache=%s",
__entry->fsidtype,
__print_array(__entry->fsid, 6, 4),
__get_str(auth_domain),
__get_str(path),
__entry->cache ? "pos" : "neg"
)
);
TRACE_EVENT(nfsd_exp_get_by_name,
TP_PROTO(const struct svc_export *key,
int status),
TP_ARGS(key, status),
TP_STRUCT__entry(
__string(path, key->ex_path.dentry->d_name.name)
__string(auth_domain, key->ex_client->name)
__field(int, status)
),
TP_fast_assign(
__assign_str(path, key->ex_path.dentry->d_name.name);
__assign_str(auth_domain, key->ex_client->name);
__entry->status = status;
),
TP_printk("path=%s domain=%s status=%d",
__get_str(path),
__get_str(auth_domain),
__entry->status
)
);
TRACE_EVENT(nfsd_export_update,
TP_PROTO(const struct svc_export *key),
TP_ARGS(key),
TP_STRUCT__entry(
__string(path, key->ex_path.dentry->d_name.name)
__string(auth_domain, key->ex_client->name)
__field(bool, cache)
),
TP_fast_assign(
__assign_str(path, key->ex_path.dentry->d_name.name);
__assign_str(auth_domain, key->ex_client->name);
__entry->cache = !test_bit(CACHE_NEGATIVE, &key->h.flags);
),
TP_printk("path=%s domain=%s cache=%s",
__get_str(path),
__get_str(auth_domain),
__entry->cache ? "pos" : "neg"
)
);
DECLARE_EVENT_CLASS(nfsd_io_class,
TP_PROTO(struct svc_rqst *rqstp,
struct svc_fh *fhp,
loff_t offset,
unsigned long len),
TP_ARGS(rqstp, fhp, offset, len),
TP_STRUCT__entry(
__field(u32, xid)
__field(u32, fh_hash)
__field(loff_t, offset)
__field(unsigned long, len)
),
TP_fast_assign(
__entry->xid = be32_to_cpu(rqstp->rq_xid);
__entry->fh_hash = knfsd_fh_hash(&fhp->fh_handle);
__entry->offset = offset;
__entry->len = len;
),
TP_printk("xid=0x%08x fh_hash=0x%08x offset=%lld len=%lu",
__entry->xid, __entry->fh_hash,
__entry->offset, __entry->len)
)
#define DEFINE_NFSD_IO_EVENT(name) \
DEFINE_EVENT(nfsd_io_class, nfsd_##name, \
TP_PROTO(struct svc_rqst *rqstp, \
struct svc_fh *fhp, \
loff_t offset, \
unsigned long len), \
TP_ARGS(rqstp, fhp, offset, len))
DEFINE_NFSD_IO_EVENT(read_start);
DEFINE_NFSD_IO_EVENT(read_splice);
DEFINE_NFSD_IO_EVENT(read_vector);
DEFINE_NFSD_IO_EVENT(read_io_done);
DEFINE_NFSD_IO_EVENT(read_done);
DEFINE_NFSD_IO_EVENT(write_start);
DEFINE_NFSD_IO_EVENT(write_opened);
DEFINE_NFSD_IO_EVENT(write_io_done);
DEFINE_NFSD_IO_EVENT(write_done);
DECLARE_EVENT_CLASS(nfsd_err_class,
TP_PROTO(struct svc_rqst *rqstp,
struct svc_fh *fhp,
loff_t offset,
int status),
TP_ARGS(rqstp, fhp, offset, status),
TP_STRUCT__entry(
__field(u32, xid)
__field(u32, fh_hash)
__field(loff_t, offset)
__field(int, status)
),
TP_fast_assign(
__entry->xid = be32_to_cpu(rqstp->rq_xid);
__entry->fh_hash = knfsd_fh_hash(&fhp->fh_handle);
__entry->offset = offset;
__entry->status = status;
),
TP_printk("xid=0x%08x fh_hash=0x%08x offset=%lld status=%d",
__entry->xid, __entry->fh_hash,
__entry->offset, __entry->status)
)
#define DEFINE_NFSD_ERR_EVENT(name) \
DEFINE_EVENT(nfsd_err_class, nfsd_##name, \
TP_PROTO(struct svc_rqst *rqstp, \
struct svc_fh *fhp, \
loff_t offset, \
int len), \
TP_ARGS(rqstp, fhp, offset, len))
DEFINE_NFSD_ERR_EVENT(read_err);
DEFINE_NFSD_ERR_EVENT(write_err);
TRACE_EVENT(nfsd_dirent,
TP_PROTO(struct svc_fh *fhp,
u64 ino,
const char *name,
int namlen),
TP_ARGS(fhp, ino, name, namlen),
TP_STRUCT__entry(
__field(u32, fh_hash)
__field(u64, ino)
__field(int, len)
__dynamic_array(unsigned char, name, namlen)
),
TP_fast_assign(
__entry->fh_hash = fhp ? knfsd_fh_hash(&fhp->fh_handle) : 0;
__entry->ino = ino;
__entry->len = namlen;
memcpy(__get_str(name), name, namlen);
),
TP_printk("fh_hash=0x%08x ino=%llu name=%.*s",
__entry->fh_hash, __entry->ino,
__entry->len, __get_str(name))
)
#include "state.h"
#include "filecache.h"
#include "vfs.h"
DECLARE_EVENT_CLASS(nfsd_stateid_class,
TP_PROTO(stateid_t *stp),
TP_ARGS(stp),
TP_STRUCT__entry(
__field(u32, cl_boot)
__field(u32, cl_id)
__field(u32, si_id)
__field(u32, si_generation)
),
TP_fast_assign(
__entry->cl_boot = stp->si_opaque.so_clid.cl_boot;
__entry->cl_id = stp->si_opaque.so_clid.cl_id;
__entry->si_id = stp->si_opaque.so_id;
__entry->si_generation = stp->si_generation;
),
TP_printk("client %08x:%08x stateid %08x:%08x",
__entry->cl_boot,
__entry->cl_id,
__entry->si_id,
__entry->si_generation)
)
#define DEFINE_STATEID_EVENT(name) \
DEFINE_EVENT(nfsd_stateid_class, nfsd_##name, \
TP_PROTO(stateid_t *stp), \
TP_ARGS(stp))
DEFINE_STATEID_EVENT(layoutstate_alloc);
DEFINE_STATEID_EVENT(layoutstate_unhash);
DEFINE_STATEID_EVENT(layoutstate_free);
DEFINE_STATEID_EVENT(layout_get_lookup_fail);
DEFINE_STATEID_EVENT(layout_commit_lookup_fail);
DEFINE_STATEID_EVENT(layout_return_lookup_fail);
DEFINE_STATEID_EVENT(layout_recall);
DEFINE_STATEID_EVENT(layout_recall_done);
DEFINE_STATEID_EVENT(layout_recall_fail);
DEFINE_STATEID_EVENT(layout_recall_release);
DEFINE_STATEID_EVENT(open);
DEFINE_STATEID_EVENT(deleg_read);
DEFINE_STATEID_EVENT(deleg_recall);
DECLARE_EVENT_CLASS(nfsd_stateseqid_class,
TP_PROTO(u32 seqid, const stateid_t *stp),
TP_ARGS(seqid, stp),
TP_STRUCT__entry(
__field(u32, seqid)
__field(u32, cl_boot)
__field(u32, cl_id)
__field(u32, si_id)
__field(u32, si_generation)
),
TP_fast_assign(
__entry->seqid = seqid;
__entry->cl_boot = stp->si_opaque.so_clid.cl_boot;
__entry->cl_id = stp->si_opaque.so_clid.cl_id;
__entry->si_id = stp->si_opaque.so_id;
__entry->si_generation = stp->si_generation;
),
TP_printk("seqid=%u client %08x:%08x stateid %08x:%08x",
__entry->seqid, __entry->cl_boot, __entry->cl_id,
__entry->si_id, __entry->si_generation)
)
#define DEFINE_STATESEQID_EVENT(name) \
DEFINE_EVENT(nfsd_stateseqid_class, nfsd_##name, \
TP_PROTO(u32 seqid, const stateid_t *stp), \
TP_ARGS(seqid, stp))
DEFINE_STATESEQID_EVENT(preprocess);
DEFINE_STATESEQID_EVENT(open_confirm);
DECLARE_EVENT_CLASS(nfsd_clientid_class,
TP_PROTO(const clientid_t *clid),
TP_ARGS(clid),
TP_STRUCT__entry(
__field(u32, cl_boot)
__field(u32, cl_id)
),
TP_fast_assign(
__entry->cl_boot = clid->cl_boot;
__entry->cl_id = clid->cl_id;
),
TP_printk("client %08x:%08x", __entry->cl_boot, __entry->cl_id)
)
#define DEFINE_CLIENTID_EVENT(name) \
DEFINE_EVENT(nfsd_clientid_class, nfsd_clid_##name, \
TP_PROTO(const clientid_t *clid), \
TP_ARGS(clid))
DEFINE_CLIENTID_EVENT(expire_unconf);
DEFINE_CLIENTID_EVENT(reclaim_complete);
DEFINE_CLIENTID_EVENT(confirmed);
DEFINE_CLIENTID_EVENT(destroyed);
DEFINE_CLIENTID_EVENT(admin_expired);
DEFINE_CLIENTID_EVENT(replaced);
DEFINE_CLIENTID_EVENT(purged);
DEFINE_CLIENTID_EVENT(renew);
DEFINE_CLIENTID_EVENT(stale);
DECLARE_EVENT_CLASS(nfsd_net_class,
TP_PROTO(const struct nfsd_net *nn),
TP_ARGS(nn),
TP_STRUCT__entry(
__field(unsigned long long, boot_time)
),
TP_fast_assign(
__entry->boot_time = nn->boot_time;
),
TP_printk("boot_time=%16llx", __entry->boot_time)
)
#define DEFINE_NET_EVENT(name) \
DEFINE_EVENT(nfsd_net_class, nfsd_##name, \
TP_PROTO(const struct nfsd_net *nn), \
TP_ARGS(nn))
DEFINE_NET_EVENT(grace_start);
DEFINE_NET_EVENT(grace_complete);
TRACE_EVENT(nfsd_clid_cred_mismatch,
TP_PROTO(
const struct nfs4_client *clp,
const struct svc_rqst *rqstp
),
TP_ARGS(clp, rqstp),
TP_STRUCT__entry(
__field(u32, cl_boot)
__field(u32, cl_id)
__field(unsigned long, cl_flavor)
__field(unsigned long, new_flavor)
__array(unsigned char, addr, sizeof(struct sockaddr_in6))
),
TP_fast_assign(
__entry->cl_boot = clp->cl_clientid.cl_boot;
__entry->cl_id = clp->cl_clientid.cl_id;
__entry->cl_flavor = clp->cl_cred.cr_flavor;
__entry->new_flavor = rqstp->rq_cred.cr_flavor;
memcpy(__entry->addr, &rqstp->rq_xprt->xpt_remote,
sizeof(struct sockaddr_in6));
),
TP_printk("client %08x:%08x flavor=%s, conflict=%s from addr=%pISpc",
__entry->cl_boot, __entry->cl_id,
show_nfsd_authflavor(__entry->cl_flavor),
show_nfsd_authflavor(__entry->new_flavor), __entry->addr
)
)
TRACE_EVENT(nfsd_clid_verf_mismatch,
TP_PROTO(
const struct nfs4_client *clp,
const struct svc_rqst *rqstp,
const nfs4_verifier *verf
),
TP_ARGS(clp, rqstp, verf),
TP_STRUCT__entry(
__field(u32, cl_boot)
__field(u32, cl_id)
__array(unsigned char, cl_verifier, NFS4_VERIFIER_SIZE)
__array(unsigned char, new_verifier, NFS4_VERIFIER_SIZE)
__array(unsigned char, addr, sizeof(struct sockaddr_in6))
),
TP_fast_assign(
__entry->cl_boot = clp->cl_clientid.cl_boot;
__entry->cl_id = clp->cl_clientid.cl_id;
memcpy(__entry->cl_verifier, (void *)&clp->cl_verifier,
NFS4_VERIFIER_SIZE);
memcpy(__entry->new_verifier, (void *)verf,
NFS4_VERIFIER_SIZE);
memcpy(__entry->addr, &rqstp->rq_xprt->xpt_remote,
sizeof(struct sockaddr_in6));
),
TP_printk("client %08x:%08x verf=0x%s, updated=0x%s from addr=%pISpc",
__entry->cl_boot, __entry->cl_id,
__print_hex_str(__entry->cl_verifier, NFS4_VERIFIER_SIZE),
__print_hex_str(__entry->new_verifier, NFS4_VERIFIER_SIZE),
__entry->addr
)
);
DECLARE_EVENT_CLASS(nfsd_clid_class,
TP_PROTO(const struct nfs4_client *clp),
TP_ARGS(clp),
TP_STRUCT__entry(
__field(u32, cl_boot)
__field(u32, cl_id)
__array(unsigned char, addr, sizeof(struct sockaddr_in6))
__field(unsigned long, flavor)
__array(unsigned char, verifier, NFS4_VERIFIER_SIZE)
__dynamic_array(char, name, clp->cl_name.len + 1)
),
TP_fast_assign(
__entry->cl_boot = clp->cl_clientid.cl_boot;
__entry->cl_id = clp->cl_clientid.cl_id;
memcpy(__entry->addr, &clp->cl_addr,
sizeof(struct sockaddr_in6));
__entry->flavor = clp->cl_cred.cr_flavor;
memcpy(__entry->verifier, (void *)&clp->cl_verifier,
NFS4_VERIFIER_SIZE);
memcpy(__get_str(name), clp->cl_name.data, clp->cl_name.len);
__get_str(name)[clp->cl_name.len] = '\0';
),
TP_printk("addr=%pISpc name='%s' verifier=0x%s flavor=%s client=%08x:%08x",
__entry->addr, __get_str(name),
__print_hex_str(__entry->verifier, NFS4_VERIFIER_SIZE),
show_nfsd_authflavor(__entry->flavor),
__entry->cl_boot, __entry->cl_id)
);
#define DEFINE_CLID_EVENT(name) \
DEFINE_EVENT(nfsd_clid_class, nfsd_clid_##name, \
TP_PROTO(const struct nfs4_client *clp), \
TP_ARGS(clp))
DEFINE_CLID_EVENT(fresh);
DEFINE_CLID_EVENT(confirmed_r);
/*
* from fs/nfsd/filecache.h
*/
TRACE_DEFINE_ENUM(NFSD_FILE_HASHED);
TRACE_DEFINE_ENUM(NFSD_FILE_PENDING);
TRACE_DEFINE_ENUM(NFSD_FILE_BREAK_READ);
TRACE_DEFINE_ENUM(NFSD_FILE_BREAK_WRITE);
TRACE_DEFINE_ENUM(NFSD_FILE_REFERENCED);
#define show_nf_flags(val) \
__print_flags(val, "|", \
{ 1 << NFSD_FILE_HASHED, "HASHED" }, \
{ 1 << NFSD_FILE_PENDING, "PENDING" }, \
{ 1 << NFSD_FILE_BREAK_READ, "BREAK_READ" }, \
{ 1 << NFSD_FILE_BREAK_WRITE, "BREAK_WRITE" }, \
{ 1 << NFSD_FILE_REFERENCED, "REFERENCED"})
DECLARE_EVENT_CLASS(nfsd_file_class,
TP_PROTO(struct nfsd_file *nf),
TP_ARGS(nf),
TP_STRUCT__entry(
__field(unsigned int, nf_hashval)
__field(void *, nf_inode)
__field(int, nf_ref)
__field(unsigned long, nf_flags)
__field(unsigned char, nf_may)
__field(struct file *, nf_file)
),
TP_fast_assign(
__entry->nf_hashval = nf->nf_hashval;
__entry->nf_inode = nf->nf_inode;
__entry->nf_ref = refcount_read(&nf->nf_ref);
__entry->nf_flags = nf->nf_flags;
__entry->nf_may = nf->nf_may;
__entry->nf_file = nf->nf_file;
),
TP_printk("hash=0x%x inode=%p ref=%d flags=%s may=%s file=%p",
__entry->nf_hashval,
__entry->nf_inode,
__entry->nf_ref,
show_nf_flags(__entry->nf_flags),
show_nfsd_may_flags(__entry->nf_may),
__entry->nf_file)
)
#define DEFINE_NFSD_FILE_EVENT(name) \
DEFINE_EVENT(nfsd_file_class, name, \
TP_PROTO(struct nfsd_file *nf), \
TP_ARGS(nf))
DEFINE_NFSD_FILE_EVENT(nfsd_file_alloc);
DEFINE_NFSD_FILE_EVENT(nfsd_file_put_final);
DEFINE_NFSD_FILE_EVENT(nfsd_file_unhash);
DEFINE_NFSD_FILE_EVENT(nfsd_file_put);
DEFINE_NFSD_FILE_EVENT(nfsd_file_unhash_and_release_locked);
TRACE_EVENT(nfsd_file_acquire,
TP_PROTO(struct svc_rqst *rqstp, unsigned int hash,
struct inode *inode, unsigned int may_flags,
struct nfsd_file *nf, __be32 status),
TP_ARGS(rqstp, hash, inode, may_flags, nf, status),
TP_STRUCT__entry(
__field(u32, xid)
__field(unsigned int, hash)
__field(void *, inode)
__field(unsigned long, may_flags)
__field(int, nf_ref)
__field(unsigned long, nf_flags)
__field(unsigned long, nf_may)
__field(struct file *, nf_file)
__field(u32, status)
),
TP_fast_assign(
__entry->xid = be32_to_cpu(rqstp->rq_xid);
__entry->hash = hash;
__entry->inode = inode;
__entry->may_flags = may_flags;
__entry->nf_ref = nf ? refcount_read(&nf->nf_ref) : 0;
__entry->nf_flags = nf ? nf->nf_flags : 0;
__entry->nf_may = nf ? nf->nf_may : 0;
__entry->nf_file = nf ? nf->nf_file : NULL;
__entry->status = be32_to_cpu(status);
),
TP_printk("xid=0x%x hash=0x%x inode=%p may_flags=%s ref=%d nf_flags=%s nf_may=%s nf_file=%p status=%u",
__entry->xid, __entry->hash, __entry->inode,
show_nfsd_may_flags(__entry->may_flags),
__entry->nf_ref, show_nf_flags(__entry->nf_flags),
show_nfsd_may_flags(__entry->nf_may),
__entry->nf_file, __entry->status)
);
DECLARE_EVENT_CLASS(nfsd_file_search_class,
TP_PROTO(struct inode *inode, unsigned int hash, int found),
TP_ARGS(inode, hash, found),
TP_STRUCT__entry(
__field(struct inode *, inode)
__field(unsigned int, hash)
__field(int, found)
),
TP_fast_assign(
__entry->inode = inode;
__entry->hash = hash;
__entry->found = found;
),
TP_printk("hash=0x%x inode=%p found=%d", __entry->hash,
__entry->inode, __entry->found)
);
#define DEFINE_NFSD_FILE_SEARCH_EVENT(name) \
DEFINE_EVENT(nfsd_file_search_class, name, \
TP_PROTO(struct inode *inode, unsigned int hash, int found), \
TP_ARGS(inode, hash, found))
DEFINE_NFSD_FILE_SEARCH_EVENT(nfsd_file_close_inode_sync);
DEFINE_NFSD_FILE_SEARCH_EVENT(nfsd_file_close_inode);
DEFINE_NFSD_FILE_SEARCH_EVENT(nfsd_file_is_cached);
TRACE_EVENT(nfsd_file_fsnotify_handle_event,
TP_PROTO(struct inode *inode, u32 mask),
TP_ARGS(inode, mask),
TP_STRUCT__entry(
__field(struct inode *, inode)
__field(unsigned int, nlink)
__field(umode_t, mode)
__field(u32, mask)
),
TP_fast_assign(
__entry->inode = inode;
__entry->nlink = inode->i_nlink;
__entry->mode = inode->i_mode;
__entry->mask = mask;
),
TP_printk("inode=%p nlink=%u mode=0%ho mask=0x%x", __entry->inode,
__entry->nlink, __entry->mode, __entry->mask)
);
#include "cache.h"
TRACE_DEFINE_ENUM(RC_DROPIT);
TRACE_DEFINE_ENUM(RC_REPLY);
TRACE_DEFINE_ENUM(RC_DOIT);
#define show_drc_retval(x) \
__print_symbolic(x, \
{ RC_DROPIT, "DROPIT" }, \
{ RC_REPLY, "REPLY" }, \
{ RC_DOIT, "DOIT" })
TRACE_EVENT(nfsd_drc_found,
TP_PROTO(
const struct nfsd_net *nn,
const struct svc_rqst *rqstp,
int result
),
TP_ARGS(nn, rqstp, result),
TP_STRUCT__entry(
__field(unsigned long long, boot_time)
__field(unsigned long, result)
__field(u32, xid)
),
TP_fast_assign(
__entry->boot_time = nn->boot_time;
__entry->result = result;
__entry->xid = be32_to_cpu(rqstp->rq_xid);
),
TP_printk("boot_time=%16llx xid=0x%08x result=%s",
__entry->boot_time, __entry->xid,
show_drc_retval(__entry->result))
);
TRACE_EVENT(nfsd_drc_mismatch,
TP_PROTO(
const struct nfsd_net *nn,
const struct svc_cacherep *key,
const struct svc_cacherep *rp
),
TP_ARGS(nn, key, rp),
TP_STRUCT__entry(
__field(unsigned long long, boot_time)
__field(u32, xid)
__field(u32, cached)
__field(u32, ingress)
),
TP_fast_assign(
__entry->boot_time = nn->boot_time;
__entry->xid = be32_to_cpu(key->c_key.k_xid);
__entry->cached = (__force u32)key->c_key.k_csum;
__entry->ingress = (__force u32)rp->c_key.k_csum;
),
TP_printk("boot_time=%16llx xid=0x%08x cached-csum=0x%08x ingress-csum=0x%08x",
__entry->boot_time, __entry->xid, __entry->cached,
__entry->ingress)
);
TRACE_EVENT(nfsd_cb_args,
TP_PROTO(
const struct nfs4_client *clp,
const struct nfs4_cb_conn *conn
),
TP_ARGS(clp, conn),
TP_STRUCT__entry(
__field(u32, cl_boot)
__field(u32, cl_id)
__field(u32, prog)
__field(u32, ident)
__array(unsigned char, addr, sizeof(struct sockaddr_in6))
),
TP_fast_assign(
__entry->cl_boot = clp->cl_clientid.cl_boot;
__entry->cl_id = clp->cl_clientid.cl_id;
__entry->prog = conn->cb_prog;
__entry->ident = conn->cb_ident;
memcpy(__entry->addr, &conn->cb_addr,
sizeof(struct sockaddr_in6));
),
TP_printk("addr=%pISpc client %08x:%08x prog=%u ident=%u",
__entry->addr, __entry->cl_boot, __entry->cl_id,
__entry->prog, __entry->ident)
);
TRACE_EVENT(nfsd_cb_nodelegs,
TP_PROTO(const struct nfs4_client *clp),
TP_ARGS(clp),
TP_STRUCT__entry(
__field(u32, cl_boot)
__field(u32, cl_id)
),
TP_fast_assign(
__entry->cl_boot = clp->cl_clientid.cl_boot;
__entry->cl_id = clp->cl_clientid.cl_id;
),
TP_printk("client %08x:%08x", __entry->cl_boot, __entry->cl_id)
)
#define show_cb_state(val) \
__print_symbolic(val, \
{ NFSD4_CB_UP, "UP" }, \
{ NFSD4_CB_UNKNOWN, "UNKNOWN" }, \
{ NFSD4_CB_DOWN, "DOWN" }, \
{ NFSD4_CB_FAULT, "FAULT"})
DECLARE_EVENT_CLASS(nfsd_cb_class,
TP_PROTO(const struct nfs4_client *clp),
TP_ARGS(clp),
TP_STRUCT__entry(
__field(unsigned long, state)
__field(u32, cl_boot)
__field(u32, cl_id)
__array(unsigned char, addr, sizeof(struct sockaddr_in6))
),
TP_fast_assign(
__entry->state = clp->cl_cb_state;
__entry->cl_boot = clp->cl_clientid.cl_boot;
__entry->cl_id = clp->cl_clientid.cl_id;
memcpy(__entry->addr, &clp->cl_cb_conn.cb_addr,
sizeof(struct sockaddr_in6));
),
TP_printk("addr=%pISpc client %08x:%08x state=%s",
__entry->addr, __entry->cl_boot, __entry->cl_id,
show_cb_state(__entry->state))
);
#define DEFINE_NFSD_CB_EVENT(name) \
DEFINE_EVENT(nfsd_cb_class, nfsd_cb_##name, \
TP_PROTO(const struct nfs4_client *clp), \
TP_ARGS(clp))
DEFINE_NFSD_CB_EVENT(state);
DEFINE_NFSD_CB_EVENT(probe);
DEFINE_NFSD_CB_EVENT(lost);
DEFINE_NFSD_CB_EVENT(shutdown);
TRACE_DEFINE_ENUM(RPC_AUTH_NULL);
TRACE_DEFINE_ENUM(RPC_AUTH_UNIX);
TRACE_DEFINE_ENUM(RPC_AUTH_GSS);
TRACE_DEFINE_ENUM(RPC_AUTH_GSS_KRB5);
TRACE_DEFINE_ENUM(RPC_AUTH_GSS_KRB5I);
TRACE_DEFINE_ENUM(RPC_AUTH_GSS_KRB5P);
#define show_nfsd_authflavor(val) \
__print_symbolic(val, \
{ RPC_AUTH_NULL, "none" }, \
{ RPC_AUTH_UNIX, "sys" }, \
{ RPC_AUTH_GSS, "gss" }, \
{ RPC_AUTH_GSS_KRB5, "krb5" }, \
{ RPC_AUTH_GSS_KRB5I, "krb5i" }, \
{ RPC_AUTH_GSS_KRB5P, "krb5p" })
TRACE_EVENT(nfsd_cb_setup,
TP_PROTO(const struct nfs4_client *clp,
const char *netid,
rpc_authflavor_t authflavor
),
TP_ARGS(clp, netid, authflavor),
TP_STRUCT__entry(
__field(u32, cl_boot)
__field(u32, cl_id)
__field(unsigned long, authflavor)
__array(unsigned char, addr, sizeof(struct sockaddr_in6))
__array(unsigned char, netid, 8)
),
TP_fast_assign(
__entry->cl_boot = clp->cl_clientid.cl_boot;
__entry->cl_id = clp->cl_clientid.cl_id;
strlcpy(__entry->netid, netid, sizeof(__entry->netid));
__entry->authflavor = authflavor;
memcpy(__entry->addr, &clp->cl_cb_conn.cb_addr,
sizeof(struct sockaddr_in6));
),
TP_printk("addr=%pISpc client %08x:%08x proto=%s flavor=%s",
__entry->addr, __entry->cl_boot, __entry->cl_id,
__entry->netid, show_nfsd_authflavor(__entry->authflavor))
);
TRACE_EVENT(nfsd_cb_setup_err,
TP_PROTO(
const struct nfs4_client *clp,
long error
),
TP_ARGS(clp, error),
TP_STRUCT__entry(
__field(long, error)
__field(u32, cl_boot)
__field(u32, cl_id)
__array(unsigned char, addr, sizeof(struct sockaddr_in6))
),
TP_fast_assign(
__entry->error = error;
__entry->cl_boot = clp->cl_clientid.cl_boot;
__entry->cl_id = clp->cl_clientid.cl_id;
memcpy(__entry->addr, &clp->cl_cb_conn.cb_addr,
sizeof(struct sockaddr_in6));
),
TP_printk("addr=%pISpc client %08x:%08x error=%ld",
__entry->addr, __entry->cl_boot, __entry->cl_id, __entry->error)
);
TRACE_EVENT(nfsd_cb_recall,
TP_PROTO(
const struct nfs4_stid *stid
),
TP_ARGS(stid),
TP_STRUCT__entry(
__field(u32, cl_boot)
__field(u32, cl_id)
__field(u32, si_id)
__field(u32, si_generation)
__array(unsigned char, addr, sizeof(struct sockaddr_in6))
),
TP_fast_assign(
const stateid_t *stp = &stid->sc_stateid;
const struct nfs4_client *clp = stid->sc_client;
__entry->cl_boot = stp->si_opaque.so_clid.cl_boot;
__entry->cl_id = stp->si_opaque.so_clid.cl_id;
__entry->si_id = stp->si_opaque.so_id;
__entry->si_generation = stp->si_generation;
if (clp)
memcpy(__entry->addr, &clp->cl_cb_conn.cb_addr,
sizeof(struct sockaddr_in6));
else
memset(__entry->addr, 0, sizeof(struct sockaddr_in6));
),
TP_printk("addr=%pISpc client %08x:%08x stateid %08x:%08x",
__entry->addr, __entry->cl_boot, __entry->cl_id,
__entry->si_id, __entry->si_generation)
);
TRACE_EVENT(nfsd_cb_notify_lock,
TP_PROTO(
const struct nfs4_lockowner *lo,
const struct nfsd4_blocked_lock *nbl
),
TP_ARGS(lo, nbl),
TP_STRUCT__entry(
__field(u32, cl_boot)
__field(u32, cl_id)
__field(u32, fh_hash)
__array(unsigned char, addr, sizeof(struct sockaddr_in6))
),
TP_fast_assign(
const struct nfs4_client *clp = lo->lo_owner.so_client;
__entry->cl_boot = clp->cl_clientid.cl_boot;
__entry->cl_id = clp->cl_clientid.cl_id;
__entry->fh_hash = knfsd_fh_hash(&nbl->nbl_fh);
memcpy(__entry->addr, &clp->cl_cb_conn.cb_addr,
sizeof(struct sockaddr_in6));
),
TP_printk("addr=%pISpc client %08x:%08x fh_hash=0x%08x",
__entry->addr, __entry->cl_boot, __entry->cl_id,
__entry->fh_hash)
);
TRACE_EVENT(nfsd_cb_offload,
TP_PROTO(
const struct nfs4_client *clp,
const stateid_t *stp,
const struct knfsd_fh *fh,
u64 count,
__be32 status
),
TP_ARGS(clp, stp, fh, count, status),
TP_STRUCT__entry(
__field(u32, cl_boot)
__field(u32, cl_id)
__field(u32, si_id)
__field(u32, si_generation)
__field(u32, fh_hash)
__field(int, status)
__field(u64, count)
__array(unsigned char, addr, sizeof(struct sockaddr_in6))
),
TP_fast_assign(
__entry->cl_boot = stp->si_opaque.so_clid.cl_boot;
__entry->cl_id = stp->si_opaque.so_clid.cl_id;
__entry->si_id = stp->si_opaque.so_id;
__entry->si_generation = stp->si_generation;
__entry->fh_hash = knfsd_fh_hash(fh);
__entry->status = be32_to_cpu(status);
__entry->count = count;
memcpy(__entry->addr, &clp->cl_cb_conn.cb_addr,
sizeof(struct sockaddr_in6));
),
TP_printk("addr=%pISpc client %08x:%08x stateid %08x:%08x fh_hash=0x%08x count=%llu status=%d",
__entry->addr, __entry->cl_boot, __entry->cl_id,
__entry->si_id, __entry->si_generation,
__entry->fh_hash, __entry->count, __entry->status)
);
#endif /* _NFSD_TRACE_H */
#undef TRACE_INCLUDE_PATH
#define TRACE_INCLUDE_PATH .
#define TRACE_INCLUDE_FILE trace
#include <trace/define_trace.h>
|
7b08cf62b1239a4322427d677ea9363f0ab677c6
|
https://github.com/torvalds/linux
|
sanitizer.ts
|
typescript
|
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
// sanitize-html uses the url package, so we depend on a standalone version of
// it which acts as a polyfill for browsers.
import sanitize from 'sanitize-html';
import { ISanitizer } from './tokens';
/**
* Helper class that contains regular expressions for inline CSS style validation.
*
* Which properties (and values) to allow is largely based on the Google Caja project:
* https://github.com/google/caja
*
* The regular expressions are largly based on the syntax definition found at
* https://developer.mozilla.org/en-US/docs/Web/CSS.
*/
class CssProp {
static reg(r: string): RegExp {
return new RegExp('^' + r + '$', 'i');
}
/*
* Numeric base expressions used to help build more complex regular expressions
*/
private static readonly N = {
integer: `[+-]?[0-9]+`,
integer_pos: `[+]?[0-9]+`,
integer_zero_ff: `([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])`,
number: `[+-]?([0-9]*[.])?[0-9]+(e-?[0-9]*)?`,
number_pos: `[+]?([0-9]*[.])?[0-9]+(e-?[0-9]*)?`,
number_zero_hundred: `[+]?(([0-9]|[1-9][0-9])([.][0-9]+)?|100)`,
number_zero_one: `[+]?(1([.][0]+)?|0([.][0-9]+)?)`
};
/*
* Base expressions of common CSS syntax elements
*/
private static readonly B = {
angle: `(${CssProp.N.number}(deg|rad|grad|turn)|0)`,
frequency: `${CssProp.N.number}(Hz|kHz)`,
ident: String.raw`-?([_a-z]|[\xA0-\xFF]|\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f])([_a-z0-9-]|[\xA0-\xFF]|\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f])*`,
len_or_perc: `(0|${CssProp.N.number}(px|em|rem|ex|in|cm|mm|pt|pc|%))`,
length: `(${CssProp.N.number}(px|em|rem|ex|in|cm|mm|pt|pc)|0)`,
length_pos: `(${CssProp.N.number_pos}(px|em|rem|ex|in|cm|mm|pt|pc)|0)`,
percentage: `${CssProp.N.number}%`,
percentage_pos: `${CssProp.N.number_pos}%`,
percentage_zero_hundred: `${CssProp.N.number_zero_hundred}%`,
string: String.raw`(\"([^\n\r\f\\"]|\\\n|\r\n|\r|\f|\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f])*\")|(\'([^\n\r\f\\']|\\\n|\r\n|\r|\f|\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f])*\')`,
time: `${CssProp.N.number}(s|ms)`,
url: `url\\(.*?\\)`,
z_index: `[+-]?[0-9]{1,7}`
};
/*
* Atomic (i.e. not dependant on other regular expressions) sub RegEx segments
*/
private static readonly A = {
absolute_size: `xx-small|x-small|small|medium|large|x-large|xx-large`,
attachment: `scroll|fixed|local`,
bg_origin: `border-box|padding-box|content-box`,
border_style: `none|hidden|dotted|dashed|solid|double|groove|ridge|inset|outset`,
box: `border-box|padding-box|content-box`,
display_inside: `auto|block|table|flex|grid`,
display_outside: `block-level|inline-level|none|table-row-group|table-header-group|table-footer-group|table-row|table-cell|table-column-group|table-column|table-caption`,
ending_shape: `circle|ellipse`,
generic_family: `serif|sans-serif|cursive|fantasy|monospace`,
generic_voice: `male|female|child`,
relative_size: `smaller|larger`,
repeat_style: `repeat-x|repeat-y|((?:repeat|space|round|no-repeat)(?:\\s*(?:repeat|space|round|no-repeat))?)`,
side_or_corner: `(left|right)?\\s*(top|bottom)?`,
single_animation_direction: `normal|reverse|alternate|alternate-reverse`,
single_animation_fill_mode: `none|forwards|backwards|both`,
single_animation_play_state: `running|paused`
};
/*
* Color definition sub expressions
*/
private static readonly _COLOR = {
hex: `\\#(0x)?[0-9a-f]+`,
name: `aliceblue|antiquewhite|aqua|aquamarine|azure|beige|bisque|black|blanchedalmond|blue|blueviolet|brown|burlywood|cadetblue|chartreuse|chocolate|coral|cornflowerblue|cornsilk|crimson|cyan|darkblue|darkcyan|darkgoldenrod|darkgray|darkgreen|darkkhaki|darkmagenta|darkolivegreen|darkorange|darkorchid|darkred|darksalmon|darkseagreen|darkslateblue|darkslategray|darkturquoise|darkviolet|deeppink|deepskyblue|dimgray|dodgerblue|firebrick|floralwhite|forestgreen|fuchsia|gainsboro|ghostwhite|gold|goldenrod|gray|green|greenyellow|honeydew|hotpink|indianred|indigo|ivory|khaki|lavender|lavenderblush|lawngreen|lemonchiffon|lightblue|lightcoral|lightcyan|lightgoldenrodyellow|lightgreen|lightgrey|lightpink|lightsalmon|lightseagreen|lightskyblue|lightslategray|lightsteelblue|lightyellow|lime|limegreen|linen|magenta|maroon|mediumaquamarine|mediumblue|mediumorchid|mediumpurple|mediumseagreen|mediumslateblue|mediumspringgreen|mediumturquoise|mediumvioletred|midnightblue|mintcream|mistyrose|moccasin|navajowhite|navy|oldlace|olive|olivedrab|orange|orangered|orchid|palegoldenrod|palegreen|paleturquoise|palevioletred|papayawhip|peachpuff|peru|pink|plum|powderblue|purple|red|rosybrown|royalblue|saddlebrown|salmon|sandybrown|seagreen|seashell|sienna|silver|skyblue|slateblue|slategray|snow|springgreen|steelblue|tan|teal|thistle|tomato|turquoise|transparent|violet|wheat|white|whitesmoke|yellow|yellowgreen`,
rgb: String.raw`rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)`,
rgba: String.raw`rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(${CssProp.N.integer_zero_ff}|${CssProp.N.number_zero_one}|${CssProp.B.percentage_zero_hundred})\s*\)`
};
/*
* Compound (i.e. dependant on other (sub) regular expressions) sub RegEx segments
*/
private static readonly _C = {
alpha: `${CssProp.N.integer_zero_ff}|${CssProp.N.number_zero_one}|${CssProp.B.percentage_zero_hundred}`,
alphavalue: CssProp.N.number_zero_one,
bg_position: `((${CssProp.B.len_or_perc}|left|center|right|top|bottom)\\s*){1,4}`,
bg_size: `(${CssProp.B.length_pos}|${CssProp.B.percentage}|auto){1,2}|cover|contain`,
border_width: `thin|medium|thick|${CssProp.B.length}`,
bottom: `${CssProp.B.length}|auto`,
color: `${CssProp._COLOR.hex}|${CssProp._COLOR.rgb}|${CssProp._COLOR.rgba}|${CssProp._COLOR.name}`,
family_name: `${CssProp.B.string}|(${CssProp.B.ident}\\s*)+`,
image_decl: CssProp.B.url,
left: `${CssProp.B.length}|auto`,
loose_quotable_words: `(${CssProp.B.ident})+`,
margin_width: `${CssProp.B.len_or_perc}|auto`,
padding_width: `${CssProp.B.length_pos}|${CssProp.B.percentage_pos}`,
page_url: CssProp.B.url,
position: `((${CssProp.B.len_or_perc}|left|center|right|top|bottom)\\s*){1,4}`,
right: `${CssProp.B.length}|auto`,
shadow: '',
size: `closest-side|farthest-side|closest-corner|farthest-corner|${CssProp.B.length}|(${CssProp.B.len_or_perc})\\s+(${CssProp.B.len_or_perc})`,
top: `${CssProp.B.length}|auto`
};
private static readonly _C1 = {
image_list: `image\\(\\s*(${CssProp.B.url})*\\s*(${CssProp.B.url}|${CssProp._C.color})\\s*\\)`,
shadow: `((${CssProp._C.color})\\s+((${CssProp.B.length})\\s*){2,4}(\s+inset)?)|((inset\\s+)?((${CssProp.B.length})\\s*){2,4}\\s*(${CssProp._C.color})?)`
};
private static readonly _C2 = {
bg_image: `(${CssProp.B.url}|${CssProp._C1.image_list})|none`,
image: `${CssProp.B.url}|${CssProp._C1.image_list}`,
shape: `rect\\(\\s*(${CssProp._C.top})\\s*,\\s*(${CssProp._C.right})\\s*,\\s*(${CssProp._C.bottom})\\s*,\\s*(${CssProp._C.left})\\s*\\)`
};
private static readonly C = { ...CssProp._C, ...CssProp._C1, ...CssProp._C2 };
/*
* Property value regular expressions not dependant on other sub expressions
*/
private static readonly AP = {
border_collapse: `collapse|separate`,
box: `normal|none|contents`,
box_sizing: `content-box|padding-box|border-box`,
caption_side: `top|bottom`,
clear: `none|left|right|both`,
direction: `ltr|rtl`,
empty_cells: `show|hide`,
float: `left|right|none`,
font_stretch: `normal|wider|narrower|ultra-condensed|extra-condensed|condensed|semi-condensed|semi-expanded|expanded|extra-expanded|ultra-expanded`,
font_style: `normal|italic|oblique`,
font_variant: `normal|small-caps`,
font_weight: `normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900`,
list_style_position: `inside|outside`,
list_style_type: `disc|circle|square|decimal|decimal-leading-zero|lower-roman|upper-roman|lower-greek|lower-latin|upper-latin|armenian|georgian|lower-alpha|upper-alpha|none`,
overflow: `visible|hidden|scroll|auto`,
overflow_wrap: `normal|break-word`,
overflow_x: `visible|hidden|scroll|auto|no-display|no-content`,
page_break_after: `auto|always|avoid|left|right`,
page_break_before: `auto|always|avoid|left|right`,
page_break_inside: `avoid|auto`,
position: `static|relative|absolute`,
resize: `none|both|horizontal|vertical`,
speak: `normal|none|spell-out`,
speak_header: `once|always`,
speak_numeral: `digits|continuous`,
speak_punctuation: `code|none`,
table_layout: `auto|fixed`,
text_align: `left|right|center|justify`,
text_decoration: `none|((underline|overline|line-through|blink)\\s*)+`,
text_transform: `capitalize|uppercase|lowercase|none`,
text_wrap: `normal|unrestricted|none|suppress`,
unicode_bidi: `normal|embed|bidi-override`,
visibility: `visible|hidden|collapse`,
white_space: `normal|pre|nowrap|pre-wrap|pre-line`,
word_break: `normal|keep-all|break-all`
};
/*
* Compound propertiy value regular expressions (i.e. dependant on other sub expressions)
*/
private static readonly _CP = {
background_attachment: `${CssProp.A.attachment}(,\\s*${CssProp.A.attachment})*`,
background_color: CssProp.C.color,
background_origin: `${CssProp.A.box}(,\\s*${CssProp.A.box})*`,
background_repeat: `${CssProp.A.repeat_style}(,\\s*${CssProp.A.repeat_style})*`,
border: `((${CssProp.C.border_width}|${CssProp.A.border_style}|${CssProp.C.color})\\s*){1,3}`,
border_radius: `((${CssProp.B.len_or_perc})\\s*){1,4}(\\/\\s*((${CssProp.B.len_or_perc})\\s*){1,4})?`,
border_spacing: `${CssProp.B.length}\\s*(${CssProp.B.length})?`,
border_top_color: CssProp.C.color,
border_top_style: CssProp.A.border_style,
border_width: `((${CssProp.C.border_width})\\s*){1,4}`,
color: CssProp.C.color,
cursor: `(${CssProp.B.url}(\\s*,\\s*)?)*(auto|crosshair|default|pointer|move|e-resize|ne-resize|nw-resize|n-resize|se-resize|sw-resize|s-resize|w-resize|text|wait|help|progress|all-scroll|col-resize|hand|no-drop|not-allowed|row-resize|vertical-text)`,
display: `inline|block|list-item|run-in|inline-list-item|inline-block|table|inline-table|table-cell|table-caption|flex|inline-flex|grid|inline-grid|${CssProp.A.display_inside}|${CssProp.A.display_outside}|inherit|inline-box|inline-stack`,
display_outside: CssProp.A.display_outside,
elevation: `${CssProp.B.angle}|below|level|above|higher|lower`,
font_family: `(${CssProp.C.family_name}|${CssProp.A.generic_family})(,\\s*(${CssProp.C.family_name}|${CssProp.A.generic_family}))*`,
height: `${CssProp.B.length}|${CssProp.B.percentage}|auto`,
letter_spacing: `normal|${CssProp.B.length}`,
list_style_image: `${CssProp.C.image}|none`,
margin_right: CssProp.C.margin_width,
max_height: `${CssProp.B.length_pos}|${CssProp.B.percentage_pos}|none|auto`,
min_height: `${CssProp.B.length_pos}|${CssProp.B.percentage_pos}|auto`,
opacity: CssProp.C.alphavalue,
outline_color: `${CssProp.C.color}|invert`,
outline_width: CssProp.C.border_width,
padding: `((${CssProp.C.padding_width})\\s*){1,4}`,
padding_top: CssProp.C.padding_width,
pitch_range: CssProp.N.number,
right: `${CssProp.B.length}|${CssProp.B.percentage}|auto`,
stress: CssProp.N.number,
text_indent: `${CssProp.B.length}|${CssProp.B.percentage}`,
text_shadow: `none|${CssProp.C.shadow}(,\\s*(${CssProp.C.shadow}))*`,
volume: `${CssProp.N.number_pos}|${CssProp.B.percentage_pos}|silent|x-soft|soft|medium|loud|x-loud`,
word_wrap: CssProp.AP.overflow_wrap,
zoom: `normal|${CssProp.N.number_pos}|${CssProp.B.percentage_pos}`,
backface_visibility: CssProp.AP.visibility,
background_clip: `${CssProp.A.box}(,\\s*(${CssProp.A.box}))*`,
background_position: `${CssProp.C.bg_position}(,\\s*(${CssProp.C.bg_position}))*`,
border_bottom_color: CssProp.C.color,
border_bottom_style: CssProp.A.border_style,
border_color: `((${CssProp.C.color})\\s*){1,4}`,
border_left_color: CssProp.C.color,
border_right_color: CssProp.C.color,
border_style: `((${CssProp.A.border_style})\\s*){1,4}`,
border_top_left_radius: `(${CssProp.B.length}|${CssProp.B.percentage})(\\s*(${CssProp.B.length}|${CssProp.B.percentage}))?`,
border_top_width: CssProp.C.border_width,
box_shadow: `none|${CssProp.C.shadow}(,\\s*(${CssProp.C.shadow}))*`,
clip: `${CssProp.C.shape}|auto`,
display_inside: CssProp.A.display_inside,
font_size: `${CssProp.A.absolute_size}|${CssProp.A.relative_size}|${CssProp.B.length_pos}|${CssProp.B.percentage_pos}`,
line_height: `normal|${CssProp.N.number_pos}|${CssProp.B.length_pos}|${CssProp.B.percentage_pos}`,
margin_left: CssProp.C.margin_width,
max_width: `${CssProp.B.length_pos}|${CssProp.B.percentage_pos}|none|auto`,
outline_style: CssProp.A.border_style,
padding_bottom: CssProp.C.padding_width,
padding_right: CssProp.C.padding_width,
perspective: `none|${CssProp.B.length}`,
richness: CssProp.N.number,
text_overflow: `((clip|ellipsis|${CssProp.B.string})\\s*){1,2}`,
top: `${CssProp.B.length}|${CssProp.B.percentage}|auto`,
width: `${CssProp.B.length_pos}|${CssProp.B.percentage_pos}|auto`,
z_index: `auto|${CssProp.B.z_index}`,
// Simplified background
background: `(((${CssProp.C.bg_position}\\s*(\\/\\s*${CssProp.C.bg_size})?)|(${CssProp.A.repeat_style})|(${CssProp.A.attachment})|(${CssProp.A.bg_origin})|(${CssProp.C.bg_image})|(${CssProp.C.color}))\\s*)+`,
background_size: `${CssProp.C.bg_size}(,\\s*${CssProp.C.bg_size})*`,
border_bottom_left_radius: `(${CssProp.B.length}|${CssProp.B.percentage})(\\s*(${CssProp.B.length}|${CssProp.B.percentage}))?`,
border_bottom_width: CssProp.C.border_width,
border_left_style: CssProp.A.border_style,
border_right_style: CssProp.A.border_style,
border_top: `((${CssProp.C.border_width}|${CssProp.A.border_style}|${CssProp.C.color})\\s*){1,3}`,
bottom: `${CssProp.B.len_or_perc}|auto`,
list_style: `((${CssProp.AP.list_style_type}|${CssProp.AP.list_style_position}|${CssProp.C.image}|none})\\s*){1,3}`,
margin_top: CssProp.C.margin_width,
outline: `((${CssProp.C.color}|invert|${CssProp.A.border_style}|${CssProp.C.border_width})\\s*){1,3}`,
overflow_y: CssProp.AP.overflow_x,
pitch: `${CssProp.B.frequency}|x-low|low|medium|high|x-high`,
vertical_align: `baseline|sub|super|top|text-top|middle|bottom|text-bottom|${CssProp.B.len_or_perc}`,
word_spacing: `normal|${CssProp.B.length}`,
background_image: `${CssProp.C.bg_image}(,\\s*${CssProp.C.bg_image})*`,
border_bottom_right_radius: `(${CssProp.B.length}|${CssProp.B.percentage})(\\s*(${CssProp.B.length}|${CssProp.B.percentage}))?`,
border_left_width: CssProp.C.border_width,
border_right_width: CssProp.C.border_width,
left: `${CssProp.B.len_or_perc}|auto`,
margin_bottom: CssProp.C.margin_width,
pause_after: `${CssProp.B.time}|${CssProp.B.percentage}`,
speech_rate: `${CssProp.N.number}|x-slow|slow|medium|fast|x-fast|faster|slower`,
transition_duration: `${CssProp.B.time}(,\\s*${CssProp.B.time})*`,
border_bottom: `((${CssProp.C.border_width}|${CssProp.A.border_style}|${CssProp.C.color})\\s*){1,3}`,
border_right: `((${CssProp.C.border_width}|${CssProp.A.border_style}|${CssProp.C.color})\\s*){1,3}`,
margin: `((${CssProp.C.margin_width})\\s*){1,4}`,
padding_left: CssProp.C.padding_width,
border_left: `((${CssProp.C.border_width}|${CssProp.A.border_style}|${CssProp.C.color})\\s*){1,3}`,
quotes: `(${CssProp.B.string}\\s*${CssProp.B.string})+|none`,
border_top_right_radius: `(${CssProp.B.length}|${CssProp.B.percentage})(\\s*(${CssProp.B.length}|${CssProp.B.percentage}))?`,
min_width: `${CssProp.B.length_pos}|${CssProp.B.percentage_pos}|auto`
};
private static readonly _CP1 = {
font: `(((((${CssProp.AP.font_style}|${CssProp.AP.font_variant}|${CssProp.AP.font_weight})\\s*){1,3})?\\s*(${CssProp._CP.font_size})\\s*(\\/\\s*(${CssProp._CP.line_height}))?\\s+(${CssProp._CP.font_family}))|caption|icon|menu|message-box|small-caption|status-bar)`
};
private static readonly CP = { ...CssProp._CP, ...CssProp._CP1 };
// CSS Property value validation regular expressions for use with sanitize-html
static BORDER_COLLAPSE = CssProp.reg(CssProp.AP.border_collapse);
static BOX = CssProp.reg(CssProp.AP.box);
static BOX_SIZING = CssProp.reg(CssProp.AP.box_sizing);
static CAPTION_SIDE = CssProp.reg(CssProp.AP.caption_side);
static CLEAR = CssProp.reg(CssProp.AP.clear);
static DIRECTION = CssProp.reg(CssProp.AP.direction);
static EMPTY_CELLS = CssProp.reg(CssProp.AP.empty_cells);
static FLOAT = CssProp.reg(CssProp.AP.float);
static FONT_STRETCH = CssProp.reg(CssProp.AP.font_stretch);
static FONT_STYLE = CssProp.reg(CssProp.AP.font_style);
static FONT_VARIANT = CssProp.reg(CssProp.AP.font_variant);
static FONT_WEIGHT = CssProp.reg(CssProp.AP.font_weight);
static LIST_STYLE_POSITION = CssProp.reg(CssProp.AP.list_style_position);
static LIST_STYLE_TYPE = CssProp.reg(CssProp.AP.list_style_type);
static OVERFLOW = CssProp.reg(CssProp.AP.overflow);
static OVERFLOW_WRAP = CssProp.reg(CssProp.AP.overflow_wrap);
static OVERFLOW_X = CssProp.reg(CssProp.AP.overflow_x);
static PAGE_BREAK_AFTER = CssProp.reg(CssProp.AP.page_break_after);
static PAGE_BREAK_BEFORE = CssProp.reg(CssProp.AP.page_break_before);
static PAGE_BREAK_INSIDE = CssProp.reg(CssProp.AP.page_break_inside);
static POSITION = CssProp.reg(CssProp.AP.position);
static RESIZE = CssProp.reg(CssProp.AP.resize);
static SPEAK = CssProp.reg(CssProp.AP.speak);
static SPEAK_HEADER = CssProp.reg(CssProp.AP.speak_header);
static SPEAK_NUMERAL = CssProp.reg(CssProp.AP.speak_numeral);
static SPEAK_PUNCTUATION = CssProp.reg(CssProp.AP.speak_punctuation);
static TABLE_LAYOUT = CssProp.reg(CssProp.AP.table_layout);
static TEXT_ALIGN = CssProp.reg(CssProp.AP.text_align);
static TEXT_DECORATION = CssProp.reg(CssProp.AP.text_decoration);
static TEXT_TRANSFORM = CssProp.reg(CssProp.AP.text_transform);
static TEXT_WRAP = CssProp.reg(CssProp.AP.text_wrap);
static UNICODE_BIDI = CssProp.reg(CssProp.AP.unicode_bidi);
static VISIBILITY = CssProp.reg(CssProp.AP.visibility);
static WHITE_SPACE = CssProp.reg(CssProp.AP.white_space);
static WORD_BREAK = CssProp.reg(CssProp.AP.word_break);
static BACKGROUND_ATTACHMENT = CssProp.reg(CssProp.CP.background_attachment);
static BACKGROUND_COLOR = CssProp.reg(CssProp.CP.background_color);
static BACKGROUND_ORIGIN = CssProp.reg(CssProp.CP.background_origin);
static BACKGROUND_REPEAT = CssProp.reg(CssProp.CP.background_repeat);
static BORDER = CssProp.reg(CssProp.CP.border);
static BORDER_RADIUS = CssProp.reg(CssProp.CP.border_radius);
static BORDER_SPACING = CssProp.reg(CssProp.CP.border_spacing);
static BORDER_TOP_COLOR = CssProp.reg(CssProp.CP.border_top_color);
static BORDER_TOP_STYLE = CssProp.reg(CssProp.CP.border_top_style);
static BORDER_WIDTH = CssProp.reg(CssProp.CP.border_width);
static COLOR = CssProp.reg(CssProp.CP.color);
static CURSOR = CssProp.reg(CssProp.CP.cursor);
static DISPLAY = CssProp.reg(CssProp.CP.display);
static DISPLAY_OUTSIDE = CssProp.reg(CssProp.CP.display_outside);
static ELEVATION = CssProp.reg(CssProp.CP.elevation);
static FONT_FAMILY = CssProp.reg(CssProp.CP.font_family);
static HEIGHT = CssProp.reg(CssProp.CP.height);
static LETTER_SPACING = CssProp.reg(CssProp.CP.letter_spacing);
static LIST_STYLE_IMAGE = CssProp.reg(CssProp.CP.list_style_image);
static MARGIN_RIGHT = CssProp.reg(CssProp.CP.margin_right);
static MAX_HEIGHT = CssProp.reg(CssProp.CP.max_height);
static MIN_HEIGHT = CssProp.reg(CssProp.CP.min_height);
static OPACITY = CssProp.reg(CssProp.CP.opacity);
static OUTLINE_COLOR = CssProp.reg(CssProp.CP.outline_color);
static OUTLINE_WIDTH = CssProp.reg(CssProp.CP.outline_width);
static PADDING = CssProp.reg(CssProp.CP.padding);
static PADDING_TOP = CssProp.reg(CssProp.CP.padding_top);
static PITCH_RANGE = CssProp.reg(CssProp.CP.pitch_range);
static RIGHT = CssProp.reg(CssProp.CP.right);
static STRESS = CssProp.reg(CssProp.CP.stress);
static TEXT_INDENT = CssProp.reg(CssProp.CP.text_indent);
static TEXT_SHADOW = CssProp.reg(CssProp.CP.text_shadow);
static VOLUME = CssProp.reg(CssProp.CP.volume);
static WORD_WRAP = CssProp.reg(CssProp.CP.word_wrap);
static ZOOM = CssProp.reg(CssProp.CP.zoom);
static BACKFACE_VISIBILITY = CssProp.reg(CssProp.CP.backface_visibility);
static BACKGROUND_CLIP = CssProp.reg(CssProp.CP.background_clip);
static BACKGROUND_POSITION = CssProp.reg(CssProp.CP.background_position);
static BORDER_BOTTOM_COLOR = CssProp.reg(CssProp.CP.border_bottom_color);
static BORDER_BOTTOM_STYLE = CssProp.reg(CssProp.CP.border_bottom_style);
static BORDER_COLOR = CssProp.reg(CssProp.CP.border_color);
static BORDER_LEFT_COLOR = CssProp.reg(CssProp.CP.border_left_color);
static BORDER_RIGHT_COLOR = CssProp.reg(CssProp.CP.border_right_color);
static BORDER_STYLE = CssProp.reg(CssProp.CP.border_style);
static BORDER_TOP_LEFT_RADIUS = CssProp.reg(
CssProp.CP.border_top_left_radius
);
static BORDER_TOP_WIDTH = CssProp.reg(CssProp.CP.border_top_width);
static BOX_SHADOW = CssProp.reg(CssProp.CP.box_shadow);
static CLIP = CssProp.reg(CssProp.CP.clip);
static DISPLAY_INSIDE = CssProp.reg(CssProp.CP.display_inside);
static FONT_SIZE = CssProp.reg(CssProp.CP.font_size);
static LINE_HEIGHT = CssProp.reg(CssProp.CP.line_height);
static MARGIN_LEFT = CssProp.reg(CssProp.CP.margin_left);
static MAX_WIDTH = CssProp.reg(CssProp.CP.max_width);
static OUTLINE_STYLE = CssProp.reg(CssProp.CP.outline_style);
static PADDING_BOTTOM = CssProp.reg(CssProp.CP.padding_bottom);
static PADDING_RIGHT = CssProp.reg(CssProp.CP.padding_right);
static PERSPECTIVE = CssProp.reg(CssProp.CP.perspective);
static RICHNESS = CssProp.reg(CssProp.CP.richness);
static TEXT_OVERFLOW = CssProp.reg(CssProp.CP.text_overflow);
static TOP = CssProp.reg(CssProp.CP.top);
static WIDTH = CssProp.reg(CssProp.CP.width);
static Z_INDEX = CssProp.reg(CssProp.CP.z_index);
static BACKGROUND = CssProp.reg(CssProp.CP.background);
static BACKGROUND_SIZE = CssProp.reg(CssProp.CP.background_size);
static BORDER_BOTTOM_LEFT_RADIUS = CssProp.reg(
CssProp.CP.border_bottom_left_radius
);
static BORDER_BOTTOM_WIDTH = CssProp.reg(CssProp.CP.border_bottom_width);
static BORDER_LEFT_STYLE = CssProp.reg(CssProp.CP.border_left_style);
static BORDER_RIGHT_STYLE = CssProp.reg(CssProp.CP.border_right_style);
static BORDER_TOP = CssProp.reg(CssProp.CP.border_top);
static BOTTOM = CssProp.reg(CssProp.CP.bottom);
static LIST_STYLE = CssProp.reg(CssProp.CP.list_style);
static MARGIN_TOP = CssProp.reg(CssProp.CP.margin_top);
static OUTLINE = CssProp.reg(CssProp.CP.outline);
static OVERFLOW_Y = CssProp.reg(CssProp.CP.overflow_y);
static PITCH = CssProp.reg(CssProp.CP.pitch);
static VERTICAL_ALIGN = CssProp.reg(CssProp.CP.vertical_align);
static WORD_SPACING = CssProp.reg(CssProp.CP.word_spacing);
static BACKGROUND_IMAGE = CssProp.reg(CssProp.CP.background_image);
static BORDER_BOTTOM_RIGHT_RADIUS = CssProp.reg(
CssProp.CP.border_bottom_right_radius
);
static BORDER_LEFT_WIDTH = CssProp.reg(CssProp.CP.border_left_width);
static BORDER_RIGHT_WIDTH = CssProp.reg(CssProp.CP.border_right_width);
static LEFT = CssProp.reg(CssProp.CP.left);
static MARGIN_BOTTOM = CssProp.reg(CssProp.CP.margin_bottom);
static PAUSE_AFTER = CssProp.reg(CssProp.CP.pause_after);
static SPEECH_RATE = CssProp.reg(CssProp.CP.speech_rate);
static TRANSITION_DURATION = CssProp.reg(CssProp.CP.transition_duration);
static BORDER_BOTTOM = CssProp.reg(CssProp.CP.border_bottom);
static BORDER_RIGHT = CssProp.reg(CssProp.CP.border_right);
static MARGIN = CssProp.reg(CssProp.CP.margin);
static PADDING_LEFT = CssProp.reg(CssProp.CP.padding_left);
static BORDER_LEFT = CssProp.reg(CssProp.CP.border_left);
static FONT = CssProp.reg(CssProp.CP.font);
static QUOTES = CssProp.reg(CssProp.CP.quotes);
static BORDER_TOP_RIGHT_RADIUS = CssProp.reg(
CssProp.CP.border_top_right_radius
);
static MIN_WIDTH = CssProp.reg(CssProp.CP.min_width);
}
/**
* A class to sanitize HTML strings.
*/
export class Sanitizer implements ISanitizer {
/**
* Sanitize an HTML string.
*
* @param dirty - The dirty text.
*
* @param options - The optional sanitization options.
*
* @returns The sanitized string.
*/
sanitize(dirty: string, options?: ISanitizer.IOptions): string {
return sanitize(dirty, { ...this._options, ...(options || {}) });
}
private _options: sanitize.IOptions = {
// HTML tags that are allowed to be used. Tags were extracted from Google Caja
allowedTags: [
'a',
'abbr',
'acronym',
'address',
'area',
'article',
'aside',
'audio',
'b',
'bdi',
'bdo',
'big',
'blockquote',
'br',
'button',
'canvas',
'caption',
'center',
'cite',
'code',
'col',
'colgroup',
'colspan',
'command',
'data',
'datalist',
'dd',
'del',
'details',
'dfn',
'dir',
'div',
'dl',
'dt',
'em',
'fieldset',
'figcaption',
'figure',
'font',
'footer',
'form',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'header',
'hgroup',
'hr',
'i',
// 'iframe' is allowed by Google Caja, but disallowed by default by sanitize-html
// , 'iframe'
'img',
'input',
'ins',
'kbd',
'label',
'legend',
'li',
'map',
'mark',
'menu',
'meter',
'nav',
'nobr',
'ol',
'optgroup',
'option',
'output',
'p',
'pre',
'progress',
'q',
'rowspan',
's',
'samp',
'section',
'select',
'small',
'source',
'span',
'strike',
'strong',
'sub',
'summary',
'sup',
'table',
'tbody',
'td',
'textarea',
'tfoot',
'th',
'thead',
'time',
'tr',
'track',
'tt',
'u',
'ul',
'var',
'video',
'wbr'
],
// Attributes that HTML tags are allowed to have, extracted from Google Caja.
// See https://github.com/jupyterlab/jupyterlab/issues/1812#issuecomment-285848435
allowedAttributes: {
'*': [
'class',
'dir',
'draggable',
'hidden',
'id',
'inert',
'itemprop',
'itemref',
'itemscope',
'lang',
'spellcheck',
'style',
'title',
'translate'
],
// 'rel' and 'target' were *not* allowed by Google Caja
a: [
'accesskey',
'coords',
'href',
'hreflang',
'name',
'rel',
'shape',
'tabindex',
'target',
'type'
],
area: [
'accesskey',
'alt',
'coords',
'href',
'nohref',
'shape',
'tabindex'
],
// 'autoplay' was *not* allowed by Google Caja
audio: [
'autoplay',
'controls',
'loop',
'mediagroup',
'muted',
'preload',
'src'
],
bdo: ['dir'],
blockquote: ['cite'],
br: ['clear'],
button: [
'accesskey',
'data-commandlinker-args',
'data-commandlinker-command',
'disabled',
'name',
'tabindex',
'type',
'value'
],
canvas: ['height', 'width'],
caption: ['align'],
col: ['align', 'char', 'charoff', 'span', 'valign', 'width'],
colgroup: ['align', 'char', 'charoff', 'span', 'valign', 'width'],
command: [
'checked',
'command',
'disabled',
'icon',
'label',
'radiogroup',
'type'
],
data: ['value'],
del: ['cite', 'datetime'],
details: ['open'],
dir: ['compact'],
div: ['align'],
dl: ['compact'],
fieldset: ['disabled'],
font: ['color', 'face', 'size'],
form: [
'accept',
'action',
'autocomplete',
'enctype',
'method',
'name',
'novalidate'
],
h1: ['align'],
h2: ['align'],
h3: ['align'],
h4: ['align'],
h5: ['align'],
h6: ['align'],
hr: ['align', 'noshade', 'size', 'width'],
iframe: [
'align',
'frameborder',
'height',
'marginheight',
'marginwidth',
'width'
],
img: [
'align',
'alt',
'border',
'height',
'hspace',
'ismap',
'name',
'src',
'usemap',
'vspace',
'width'
],
input: [
'accept',
'accesskey',
'align',
'alt',
'autocomplete',
'checked',
'disabled',
'inputmode',
'ismap',
'list',
'max',
'maxlength',
'min',
'multiple',
'name',
'placeholder',
'readonly',
'required',
'size',
'src',
'step',
'tabindex',
'type',
'usemap',
'value'
],
ins: ['cite', 'datetime'],
label: ['accesskey', 'for'],
legend: ['accesskey', 'align'],
li: ['type', 'value'],
map: ['name'],
menu: ['compact', 'label', 'type'],
meter: ['high', 'low', 'max', 'min', 'value'],
ol: ['compact', 'reversed', 'start', 'type'],
optgroup: ['disabled', 'label'],
option: ['disabled', 'label', 'selected', 'value'],
output: ['for', 'name'],
p: ['align'],
pre: ['width'],
progress: ['max', 'min', 'value'],
q: ['cite'],
select: [
'autocomplete',
'disabled',
'multiple',
'name',
'required',
'size',
'tabindex'
],
source: ['type'],
table: [
'align',
'bgcolor',
'border',
'cellpadding',
'cellspacing',
'frame',
'rules',
'summary',
'width'
],
tbody: ['align', 'char', 'charoff', 'valign'],
td: [
'abbr',
'align',
'axis',
'bgcolor',
'char',
'charoff',
'colspan',
'headers',
'height',
'nowrap',
'rowspan',
'scope',
'valign',
'width'
],
textarea: [
'accesskey',
'autocomplete',
'cols',
'disabled',
'inputmode',
'name',
'placeholder',
'readonly',
'required',
'rows',
'tabindex',
'wrap'
],
tfoot: ['align', 'char', 'charoff', 'valign'],
th: [
'abbr',
'align',
'axis',
'bgcolor',
'char',
'charoff',
'colspan',
'headers',
'height',
'nowrap',
'rowspan',
'scope',
'valign',
'width'
],
thead: ['align', 'char', 'charoff', 'valign'],
tr: ['align', 'bgcolor', 'char', 'charoff', 'valign'],
track: ['default', 'kind', 'label', 'srclang'],
ul: ['compact', 'type'],
video: [
'autoplay',
'controls',
'height',
'loop',
'mediagroup',
'muted',
'poster',
'preload',
'src',
'width'
]
},
// Inline CSS styles that HTML tags may have (and their allowed values)
allowedStyles: {
// To simplify the data, all styles are allowed on all tags that allow the style attribute
'*': {
'backface-visibility': [CssProp.BACKFACE_VISIBILITY],
background: [CssProp.BACKGROUND],
'background-attachment': [CssProp.BACKGROUND_ATTACHMENT],
'background-clip': [CssProp.BACKGROUND_CLIP],
'background-color': [CssProp.BACKGROUND_COLOR],
'background-image': [CssProp.BACKGROUND_IMAGE],
'background-origin': [CssProp.BACKGROUND_ORIGIN],
'background-position': [CssProp.BACKGROUND_POSITION],
'background-repeat': [CssProp.BACKGROUND_REPEAT],
'background-size': [CssProp.BACKGROUND_SIZE],
border: [CssProp.BORDER],
'border-bottom': [CssProp.BORDER_BOTTOM],
'border-bottom-color': [CssProp.BORDER_BOTTOM_COLOR],
'border-bottom-left-radius': [CssProp.BORDER_BOTTOM_LEFT_RADIUS],
'border-bottom-right-radius': [CssProp.BORDER_BOTTOM_RIGHT_RADIUS],
'border-bottom-style': [CssProp.BORDER_BOTTOM_STYLE],
'border-bottom-width': [CssProp.BORDER_BOTTOM_WIDTH],
'border-collapse': [CssProp.BORDER_COLLAPSE],
'border-color': [CssProp.BORDER_COLOR],
'border-left': [CssProp.BORDER_LEFT],
'border-left-color': [CssProp.BORDER_LEFT_COLOR],
'border-left-style': [CssProp.BORDER_LEFT_STYLE],
'border-left-width': [CssProp.BORDER_LEFT_WIDTH],
'border-radius': [CssProp.BORDER_RADIUS],
'border-right': [CssProp.BORDER_RIGHT],
'border-right-color': [CssProp.BORDER_RIGHT_COLOR],
'border-right-style': [CssProp.BORDER_RIGHT_STYLE],
'border-right-width': [CssProp.BORDER_RIGHT_WIDTH],
'border-spacing': [CssProp.BORDER_SPACING],
'border-style': [CssProp.BORDER_STYLE],
'border-top': [CssProp.BORDER_TOP],
'border-top-color': [CssProp.BORDER_TOP_COLOR],
'border-top-left-radius': [CssProp.BORDER_TOP_LEFT_RADIUS],
'border-top-right-radius': [CssProp.BORDER_TOP_RIGHT_RADIUS],
'border-top-style': [CssProp.BORDER_TOP_STYLE],
'border-top-width': [CssProp.BORDER_TOP_WIDTH],
'border-width': [CssProp.BORDER_WIDTH],
bottom: [CssProp.BOTTOM],
box: [CssProp.BOX],
'box-shadow': [CssProp.BOX_SHADOW],
'box-sizing': [CssProp.BOX_SIZING],
'caption-side': [CssProp.CAPTION_SIDE],
clear: [CssProp.CLEAR],
clip: [CssProp.CLIP],
color: [CssProp.COLOR],
cursor: [CssProp.CURSOR],
direction: [CssProp.DIRECTION],
display: [CssProp.DISPLAY],
'display-inside': [CssProp.DISPLAY_INSIDE],
'display-outside': [CssProp.DISPLAY_OUTSIDE],
elevation: [CssProp.ELEVATION],
'empty-cells': [CssProp.EMPTY_CELLS],
float: [CssProp.FLOAT],
font: [CssProp.FONT],
'font-family': [CssProp.FONT_FAMILY],
'font-size': [CssProp.FONT_SIZE],
'font-stretch': [CssProp.FONT_STRETCH],
'font-style': [CssProp.FONT_STYLE],
'font-variant': [CssProp.FONT_VARIANT],
'font-weight': [CssProp.FONT_WEIGHT],
height: [CssProp.HEIGHT],
left: [CssProp.LEFT],
'letter-spacing': [CssProp.LETTER_SPACING],
'line-height': [CssProp.LINE_HEIGHT],
'list-style': [CssProp.LIST_STYLE],
'list-style-image': [CssProp.LIST_STYLE_IMAGE],
'list-style-position': [CssProp.LIST_STYLE_POSITION],
'list-style-type': [CssProp.LIST_STYLE_TYPE],
margin: [CssProp.MARGIN],
'margin-bottom': [CssProp.MARGIN_BOTTOM],
'margin-left': [CssProp.MARGIN_LEFT],
'margin-right': [CssProp.MARGIN_RIGHT],
'margin-top': [CssProp.MARGIN_TOP],
'max-height': [CssProp.MAX_HEIGHT],
'max-width': [CssProp.MAX_WIDTH],
'min-height': [CssProp.MIN_HEIGHT],
'min-width': [CssProp.MIN_WIDTH],
opacity: [CssProp.OPACITY],
outline: [CssProp.OUTLINE],
'outline-color': [CssProp.OUTLINE_COLOR],
'outline-style': [CssProp.OUTLINE_STYLE],
'outline-width': [CssProp.OUTLINE_WIDTH],
overflow: [CssProp.OVERFLOW],
'overflow-wrap': [CssProp.OVERFLOW_WRAP],
'overflow-x': [CssProp.OVERFLOW_X],
'overflow-y': [CssProp.OVERFLOW_Y],
padding: [CssProp.PADDING],
'padding-bottom': [CssProp.PADDING_BOTTOM],
'padding-left': [CssProp.PADDING_LEFT],
'padding-right': [CssProp.PADDING_RIGHT],
'padding-top': [CssProp.PADDING_TOP],
'page-break-after': [CssProp.PAGE_BREAK_AFTER],
'page-break-before': [CssProp.PAGE_BREAK_BEFORE],
'page-break-inside': [CssProp.PAGE_BREAK_INSIDE],
'pause-after': [CssProp.PAUSE_AFTER],
perspective: [CssProp.PERSPECTIVE],
pitch: [CssProp.PITCH],
'pitch-range': [CssProp.PITCH_RANGE],
position: [CssProp.POSITION],
quotes: [CssProp.QUOTES],
resize: [CssProp.RESIZE],
richness: [CssProp.RICHNESS],
right: [CssProp.RIGHT],
speak: [CssProp.SPEAK],
'speak-header': [CssProp.SPEAK_HEADER],
'speak-numeral': [CssProp.SPEAK_NUMERAL],
'speak-punctuation': [CssProp.SPEAK_PUNCTUATION],
'speech-rate': [CssProp.SPEECH_RATE],
stress: [CssProp.STRESS],
'table-layout': [CssProp.TABLE_LAYOUT],
'text-align': [CssProp.TEXT_ALIGN],
'text-decoration': [CssProp.TEXT_DECORATION],
'text-indent': [CssProp.TEXT_INDENT],
'text-overflow': [CssProp.TEXT_OVERFLOW],
'text-shadow': [CssProp.TEXT_SHADOW],
'text-transform': [CssProp.TEXT_TRANSFORM],
'text-wrap': [CssProp.TEXT_WRAP],
top: [CssProp.TOP],
'unicode-bidi': [CssProp.UNICODE_BIDI],
'vertical-align': [CssProp.VERTICAL_ALIGN],
visibility: [CssProp.VISIBILITY],
volume: [CssProp.VOLUME],
'white-space': [CssProp.WHITE_SPACE],
width: [CssProp.WIDTH],
'word-break': [CssProp.WORD_BREAK],
'word-spacing': [CssProp.WORD_SPACING],
'word-wrap': [CssProp.WORD_WRAP],
'z-index': [CssProp.Z_INDEX],
zoom: [CssProp.ZOOM]
}
},
transformTags: {
// Set the "rel" attribute for <a> tags to "nofollow".
a: sanitize.simpleTransform('a', { rel: 'nofollow' }),
// Set the "disabled" attribute for <input> tags.
input: sanitize.simpleTransform('input', { disabled: 'disabled' })
},
allowedSchemesByTag: {
// Allow 'attachment:' img src (used for markdown cell attachments).
img: sanitize.defaults.allowedSchemes.concat(['attachment'])
},
// Override of the default option, so we can skip 'src' attribute validation.
// 'src' Attributes are validated to be URIs, which does not allow for embedded (image) data.
// Since embedded data is no longer deemed to be a threat, validation can be skipped.
// See https://github.com/jupyterlab/jupyterlab/issues/5183
allowedSchemesAppliedToAttributes: ['href', 'cite']
};
}
/**
* The default instance of an `ISanitizer` meant for use by user code.
*/
export const defaultSanitizer: ISanitizer = new Sanitizer();
|
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
// sanitize-html uses the url package, so we depend on a standalone version of
// it which acts as a polyfill for browsers.
import sanitize from 'sanitize-html';
import { ISanitizer } from './tokens';
/**
* Helper class that contains regular expressions for inline CSS style validation.
*
* Which properties (and values) to allow is largely based on the Google Caja project:
* https://github.com/google/caja
*
* The regular expressions are largly based on the syntax definition found at
* https://developer.mozilla.org/en-US/docs/Web/CSS.
*/
class CssProp {
static reg(r: string): RegExp {
return new RegExp('^' + r + '$', 'i');
}
/*
* Numeric base expressions used to help build more complex regular expressions
*/
private static readonly N = {
integer: `[+-]?[0-9]+`,
integer_pos: `[+]?[0-9]+`,
integer_zero_ff: `([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])`,
number: `[+-]?([0-9]*[.])?[0-9]+(e-?[0-9]*)?`,
number_pos: `[+]?([0-9]*[.])?[0-9]+(e-?[0-9]*)?`,
number_zero_hundred: `[+]?(([0-9]|[1-9][0-9])([.][0-9]+)?|100)`,
number_zero_one: `[+]?(1([.][0]+)?|0([.][0-9]+)?)`
};
/*
* Base expressions of common CSS syntax elements
*/
private static readonly B = {
angle: `(${CssProp.N.number}(deg|rad|grad|turn)|0)`,
frequency: `${CssProp.N.number}(Hz|kHz)`,
ident: String.raw`-?([_a-z]|[\xA0-\xFF]|\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f])([_a-z0-9-]|[\xA0-\xFF]|\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f])*`,
len_or_perc: `(0|${CssProp.N.number}(px|em|rem|ex|in|cm|mm|pt|pc|%))`,
length: `(${CssProp.N.number}(px|em|rem|ex|in|cm|mm|pt|pc)|0)`,
length_pos: `(${CssProp.N.number_pos}(px|em|rem|ex|in|cm|mm|pt|pc)|0)`,
percentage: `${CssProp.N.number}%`,
percentage_pos: `${CssProp.N.number_pos}%`,
percentage_zero_hundred: `${CssProp.N.number_zero_hundred}%`,
string: String.raw`(\"([^\n\r\f\\"]|\\\n|\r\n|\r|\f|\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f])*\")|(\'([^\n\r\f\\']|\\\n|\r\n|\r|\f|\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f])*\')`,
time: `${CssProp.N.number}(s|ms)`,
url: `url\\(.*?\\)`,
z_index: `[+-]?[0-9]{1,7}`
};
/*
* Atomic (i.e. not dependant on other regular expressions) sub RegEx segments
*/
private static readonly A = {
absolute_size: `xx-small|x-small|small|medium|large|x-large|xx-large`,
attachment: `scroll|fixed|local`,
bg_origin: `border-box|padding-box|content-box`,
border_style: `none|hidden|dotted|dashed|solid|double|groove|ridge|inset|outset`,
box: `border-box|padding-box|content-box`,
display_inside: `auto|block|table|flex|grid`,
display_outside: `block-level|inline-level|none|table-row-group|table-header-group|table-footer-group|table-row|table-cell|table-column-group|table-column|table-caption`,
ending_shape: `circle|ellipse`,
generic_family: `serif|sans-serif|cursive|fantasy|monospace`,
generic_voice: `male|female|child`,
relative_size: `smaller|larger`,
repeat_style: `repeat-x|repeat-y|((?:repeat|space|round|no-repeat)(?:\\s*(?:repeat|space|round|no-repeat))?)`,
side_or_corner: `(left|right)?\\s*(top|bottom)?`,
single_animation_direction: `normal|reverse|alternate|alternate-reverse`,
single_animation_fill_mode: `none|forwards|backwards|both`,
single_animation_play_state: `running|paused`
};
/*
* Color definition sub expressions
*/
private static readonly _COLOR = {
hex: `\\#(0x)?[0-9a-f]+`,
name: `aliceblue|antiquewhite|aqua|aquamarine|azure|beige|bisque|black|blanchedalmond|blue|blueviolet|brown|burlywood|cadetblue|chartreuse|chocolate|coral|cornflowerblue|cornsilk|crimson|cyan|darkblue|darkcyan|darkgoldenrod|darkgray|darkgreen|darkkhaki|darkmagenta|darkolivegreen|darkorange|darkorchid|darkred|darksalmon|darkseagreen|darkslateblue|darkslategray|darkturquoise|darkviolet|deeppink|deepskyblue|dimgray|dodgerblue|firebrick|floralwhite|forestgreen|fuchsia|gainsboro|ghostwhite|gold|goldenrod|gray|green|greenyellow|honeydew|hotpink|indianred|indigo|ivory|khaki|lavender|lavenderblush|lawngreen|lemonchiffon|lightblue|lightcoral|lightcyan|lightgoldenrodyellow|lightgreen|lightgrey|lightpink|lightsalmon|lightseagreen|lightskyblue|lightslategray|lightsteelblue|lightyellow|lime|limegreen|linen|magenta|maroon|mediumaquamarine|mediumblue|mediumorchid|mediumpurple|mediumseagreen|mediumslateblue|mediumspringgreen|mediumturquoise|mediumvioletred|midnightblue|mintcream|mistyrose|moccasin|navajowhite|navy|oldlace|olive|olivedrab|orange|orangered|orchid|palegoldenrod|palegreen|paleturquoise|palevioletred|papayawhip|peachpuff|peru|pink|plum|powderblue|purple|red|rosybrown|royalblue|saddlebrown|salmon|sandybrown|seagreen|seashell|sienna|silver|skyblue|slateblue|slategray|snow|springgreen|steelblue|tan|teal|thistle|tomato|turquoise|transparent|violet|wheat|white|whitesmoke|yellow|yellowgreen`,
rgb: String.raw`rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)`,
rgba: String.raw`rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(${CssProp.N.integer_zero_ff}|${CssProp.N.number_zero_one}|${CssProp.B.percentage_zero_hundred})\s*\)`
};
/*
* Compound (i.e. dependant on other (sub) regular expressions) sub RegEx segments
*/
private static readonly _C = {
alpha: `${CssProp.N.integer_zero_ff}|${CssProp.N.number_zero_one}|${CssProp.B.percentage_zero_hundred}`,
alphavalue: CssProp.N.number_zero_one,
bg_position: `((${CssProp.B.len_or_perc}|left|center|right|top|bottom)\\s*){1,4}`,
bg_size: `(${CssProp.B.length_pos}|${CssProp.B.percentage}|auto){1,2}|cover|contain`,
border_width: `thin|medium|thick|${CssProp.B.length}`,
bottom: `${CssProp.B.length}|auto`,
color: `${CssProp._COLOR.hex}|${CssProp._COLOR.rgb}|${CssProp._COLOR.rgba}|${CssProp._COLOR.name}`,
family_name: `${CssProp.B.string}|(${CssProp.B.ident}\\s*)+`,
image_decl: CssProp.B.url,
left: `${CssProp.B.length}|auto`,
loose_quotable_words: `(${CssProp.B.ident})+`,
margin_width: `${CssProp.B.len_or_perc}|auto`,
padding_width: `${CssProp.B.length_pos}|${CssProp.B.percentage_pos}`,
page_url: CssProp.B.url,
position: `((${CssProp.B.len_or_perc}|left|center|right|top|bottom)\\s*){1,4}`,
right: `${CssProp.B.length}|auto`,
shadow: '',
size: `closest-side|farthest-side|closest-corner|farthest-corner|${CssProp.B.length}|(${CssProp.B.len_or_perc})\\s+(${CssProp.B.len_or_perc})`,
top: `${CssProp.B.length}|auto`
};
private static readonly _C1 = {
image_list: `image\\(\\s*(${CssProp.B.url})*\\s*(${CssProp.B.url}|${CssProp._C.color})\\s*\\)`,
shadow: `((${CssProp._C.color})\\s+((${CssProp.B.length})\\s*){2,4}(\s+inset)?)|((inset\\s+)?((${CssProp.B.length})\\s*){2,4}\\s*(${CssProp._C.color})?)`
};
private static readonly _C2 = {
bg_image: `(${CssProp.B.url}|${CssProp._C1.image_list})|none`,
image: `${CssProp.B.url}|${CssProp._C1.image_list}`,
shape: `rect\\(\\s*(${CssProp._C.top})\\s*,\\s*(${CssProp._C.right})\\s*,\\s*(${CssProp._C.bottom})\\s*,\\s*(${CssProp._C.left})\\s*\\)`
};
private static readonly C = { ...CssProp._C, ...CssProp._C1, ...CssProp._C2 };
/*
* Property value regular expressions not dependant on other sub expressions
*/
private static readonly AP = {
border_collapse: `collapse|separate`,
box: `normal|none|contents`,
box_sizing: `content-box|padding-box|border-box`,
caption_side: `top|bottom`,
clear: `none|left|right|both`,
direction: `ltr|rtl`,
empty_cells: `show|hide`,
float: `left|right|none`,
font_stretch: `normal|wider|narrower|ultra-condensed|extra-condensed|condensed|semi-condensed|semi-expanded|expanded|extra-expanded|ultra-expanded`,
font_style: `normal|italic|oblique`,
font_variant: `normal|small-caps`,
font_weight: `normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900`,
list_style_position: `inside|outside`,
list_style_type: `disc|circle|square|decimal|decimal-leading-zero|lower-roman|upper-roman|lower-greek|lower-latin|upper-latin|armenian|georgian|lower-alpha|upper-alpha|none`,
overflow: `visible|hidden|scroll|auto`,
overflow_wrap: `normal|break-word`,
overflow_x: `visible|hidden|scroll|auto|no-display|no-content`,
page_break_after: `auto|always|avoid|left|right`,
page_break_before: `auto|always|avoid|left|right`,
page_break_inside: `avoid|auto`,
position: `static|relative|absolute`,
resize: `none|both|horizontal|vertical`,
speak: `normal|none|spell-out`,
speak_header: `once|always`,
speak_numeral: `digits|continuous`,
speak_punctuation: `code|none`,
table_layout: `auto|fixed`,
text_align: `left|right|center|justify`,
text_decoration: `none|((underline|overline|line-through|blink)\\s*)+`,
text_transform: `capitalize|uppercase|lowercase|none`,
text_wrap: `normal|unrestricted|none|suppress`,
unicode_bidi: `normal|embed|bidi-override`,
visibility: `visible|hidden|collapse`,
white_space: `normal|pre|nowrap|pre-wrap|pre-line`,
word_break: `normal|keep-all|break-all`
};
/*
* Compound propertiy value regular expressions (i.e. dependant on other sub expressions)
*/
private static readonly _CP = {
background_attachment: `${CssProp.A.attachment}(,\\s*${CssProp.A.attachment})*`,
background_color: CssProp.C.color,
background_origin: `${CssProp.A.box}(,\\s*${CssProp.A.box})*`,
background_repeat: `${CssProp.A.repeat_style}(,\\s*${CssProp.A.repeat_style})*`,
border: `((${CssProp.C.border_width}|${CssProp.A.border_style}|${CssProp.C.color})\\s*){1,3}`,
border_radius: `((${CssProp.B.len_or_perc})\\s*){1,4}(\\/\\s*((${CssProp.B.len_or_perc})\\s*){1,4})?`,
border_spacing: `${CssProp.B.length}\\s*(${CssProp.B.length})?`,
border_top_color: CssProp.C.color,
border_top_style: CssProp.A.border_style,
border_width: `((${CssProp.C.border_width})\\s*){1,4}`,
color: CssProp.C.color,
cursor: `(${CssProp.B.url}(\\s*,\\s*)?)*(auto|crosshair|default|pointer|move|e-resize|ne-resize|nw-resize|n-resize|se-resize|sw-resize|s-resize|w-resize|text|wait|help|progress|all-scroll|col-resize|hand|no-drop|not-allowed|row-resize|vertical-text)`,
display: `inline|block|list-item|run-in|inline-list-item|inline-block|table|inline-table|table-cell|table-caption|flex|inline-flex|grid|inline-grid|${CssProp.A.display_inside}|${CssProp.A.display_outside}|inherit|inline-box|inline-stack`,
display_outside: CssProp.A.display_outside,
elevation: `${CssProp.B.angle}|below|level|above|higher|lower`,
font_family: `(${CssProp.C.family_name}|${CssProp.A.generic_family})(,\\s*(${CssProp.C.family_name}|${CssProp.A.generic_family}))*`,
height: `${CssProp.B.length}|${CssProp.B.percentage}|auto`,
letter_spacing: `normal|${CssProp.B.length}`,
list_style_image: `${CssProp.C.image}|none`,
margin_right: CssProp.C.margin_width,
max_height: `${CssProp.B.length_pos}|${CssProp.B.percentage_pos}|none|auto`,
min_height: `${CssProp.B.length_pos}|${CssProp.B.percentage_pos}|auto`,
opacity: CssProp.C.alphavalue,
outline_color: `${CssProp.C.color}|invert`,
outline_width: CssProp.C.border_width,
padding: `((${CssProp.C.padding_width})\\s*){1,4}`,
padding_top: CssProp.C.padding_width,
pitch_range: CssProp.N.number,
right: `${CssProp.B.length}|${CssProp.B.percentage}|auto`,
stress: CssProp.N.number,
text_indent: `${CssProp.B.length}|${CssProp.B.percentage}`,
text_shadow: `none|${CssProp.C.shadow}(,\\s*(${CssProp.C.shadow}))*`,
volume: `${CssProp.N.number_pos}|${CssProp.B.percentage_pos}|silent|x-soft|soft|medium|loud|x-loud`,
word_wrap: CssProp.AP.overflow_wrap,
zoom: `normal|${CssProp.N.number_pos}|${CssProp.B.percentage_pos}`,
backface_visibility: CssProp.AP.visibility,
background_clip: `${CssProp.A.box}(,\\s*(${CssProp.A.box}))*`,
background_position: `${CssProp.C.bg_position}(,\\s*(${CssProp.C.bg_position}))*`,
border_bottom_color: CssProp.C.color,
border_bottom_style: CssProp.A.border_style,
border_color: `((${CssProp.C.color})\\s*){1,4}`,
border_left_color: CssProp.C.color,
border_right_color: CssProp.C.color,
border_style: `((${CssProp.A.border_style})\\s*){1,4}`,
border_top_left_radius: `(${CssProp.B.length}|${CssProp.B.percentage})(\\s*(${CssProp.B.length}|${CssProp.B.percentage}))?`,
border_top_width: CssProp.C.border_width,
box_shadow: `none|${CssProp.C.shadow}(,\\s*(${CssProp.C.shadow}))*`,
clip: `${CssProp.C.shape}|auto`,
display_inside: CssProp.A.display_inside,
font_size: `${CssProp.A.absolute_size}|${CssProp.A.relative_size}|${CssProp.B.length_pos}|${CssProp.B.percentage_pos}`,
line_height: `normal|${CssProp.N.number_pos}|${CssProp.B.length_pos}|${CssProp.B.percentage_pos}`,
margin_left: CssProp.C.margin_width,
max_width: `${CssProp.B.length_pos}|${CssProp.B.percentage_pos}|none|auto`,
outline_style: CssProp.A.border_style,
padding_bottom: CssProp.C.padding_width,
padding_right: CssProp.C.padding_width,
perspective: `none|${CssProp.B.length}`,
richness: CssProp.N.number,
text_overflow: `((clip|ellipsis|${CssProp.B.string})\\s*){1,2}`,
top: `${CssProp.B.length}|${CssProp.B.percentage}|auto`,
width: `${CssProp.B.length_pos}|${CssProp.B.percentage_pos}|auto`,
z_index: `auto|${CssProp.B.z_index}`,
// Simplified background
background: `(((${CssProp.C.bg_position}\\s*(\\/\\s*${CssProp.C.bg_size})?)|(${CssProp.A.repeat_style})|(${CssProp.A.attachment})|(${CssProp.A.bg_origin})|(${CssProp.C.bg_image})|(${CssProp.C.color}))\\s*)+`,
background_size: `${CssProp.C.bg_size}(,\\s*${CssProp.C.bg_size})*`,
border_bottom_left_radius: `(${CssProp.B.length}|${CssProp.B.percentage})(\\s*(${CssProp.B.length}|${CssProp.B.percentage}))?`,
border_bottom_width: CssProp.C.border_width,
border_left_style: CssProp.A.border_style,
border_right_style: CssProp.A.border_style,
border_top: `((${CssProp.C.border_width}|${CssProp.A.border_style}|${CssProp.C.color})\\s*){1,3}`,
bottom: `${CssProp.B.len_or_perc}|auto`,
list_style: `((${CssProp.AP.list_style_type}|${CssProp.AP.list_style_position}|${CssProp.C.image}|none})\\s*){1,3}`,
margin_top: CssProp.C.margin_width,
outline: `((${CssProp.C.color}|invert|${CssProp.A.border_style}|${CssProp.C.border_width})\\s*){1,3}`,
overflow_y: CssProp.AP.overflow_x,
pitch: `${CssProp.B.frequency}|x-low|low|medium|high|x-high`,
vertical_align: `baseline|sub|super|top|text-top|middle|bottom|text-bottom|${CssProp.B.len_or_perc}`,
word_spacing: `normal|${CssProp.B.length}`,
background_image: `${CssProp.C.bg_image}(,\\s*${CssProp.C.bg_image})*`,
border_bottom_right_radius: `(${CssProp.B.length}|${CssProp.B.percentage})(\\s*(${CssProp.B.length}|${CssProp.B.percentage}))?`,
border_left_width: CssProp.C.border_width,
border_right_width: CssProp.C.border_width,
left: `${CssProp.B.len_or_perc}|auto`,
margin_bottom: CssProp.C.margin_width,
pause_after: `${CssProp.B.time}|${CssProp.B.percentage}`,
speech_rate: `${CssProp.N.number}|x-slow|slow|medium|fast|x-fast|faster|slower`,
transition_duration: `${CssProp.B.time}(,\\s*${CssProp.B.time})*`,
border_bottom: `((${CssProp.C.border_width}|${CssProp.A.border_style}|${CssProp.C.color})\\s*){1,3}`,
border_right: `((${CssProp.C.border_width}|${CssProp.A.border_style}|${CssProp.C.color})\\s*){1,3}`,
margin: `((${CssProp.C.margin_width})\\s*){1,4}`,
padding_left: CssProp.C.padding_width,
border_left: `((${CssProp.C.border_width}|${CssProp.A.border_style}|${CssProp.C.color})\\s*){1,3}`,
quotes: `(${CssProp.B.string}\\s*${CssProp.B.string})+|none`,
border_top_right_radius: `(${CssProp.B.length}|${CssProp.B.percentage})(\\s*(${CssProp.B.length}|${CssProp.B.percentage}))?`,
min_width: `${CssProp.B.length_pos}|${CssProp.B.percentage_pos}|auto`
};
private static readonly _CP1 = {
font: `(((((${CssProp.AP.font_style}|${CssProp.AP.font_variant}|${CssProp.AP.font_weight})\\s*){1,3})?\\s*(${CssProp._CP.font_size})\\s*(\\/\\s*(${CssProp._CP.line_height}))?\\s+(${CssProp._CP.font_family}))|caption|icon|menu|message-box|small-caption|status-bar)`
};
private static readonly CP = { ...CssProp._CP, ...CssProp._CP1 };
// CSS Property value validation regular expressions for use with sanitize-html
static BORDER_COLLAPSE = CssProp.reg(CssProp.AP.border_collapse);
static BOX = CssProp.reg(CssProp.AP.box);
static BOX_SIZING = CssProp.reg(CssProp.AP.box_sizing);
static CAPTION_SIDE = CssProp.reg(CssProp.AP.caption_side);
static CLEAR = CssProp.reg(CssProp.AP.clear);
static DIRECTION = CssProp.reg(CssProp.AP.direction);
static EMPTY_CELLS = CssProp.reg(CssProp.AP.empty_cells);
static FLOAT = CssProp.reg(CssProp.AP.float);
static FONT_STRETCH = CssProp.reg(CssProp.AP.font_stretch);
static FONT_STYLE = CssProp.reg(CssProp.AP.font_style);
static FONT_VARIANT = CssProp.reg(CssProp.AP.font_variant);
static FONT_WEIGHT = CssProp.reg(CssProp.AP.font_weight);
static LIST_STYLE_POSITION = CssProp.reg(CssProp.AP.list_style_position);
static LIST_STYLE_TYPE = CssProp.reg(CssProp.AP.list_style_type);
static OVERFLOW = CssProp.reg(CssProp.AP.overflow);
static OVERFLOW_WRAP = CssProp.reg(CssProp.AP.overflow_wrap);
static OVERFLOW_X = CssProp.reg(CssProp.AP.overflow_x);
static PAGE_BREAK_AFTER = CssProp.reg(CssProp.AP.page_break_after);
static PAGE_BREAK_BEFORE = CssProp.reg(CssProp.AP.page_break_before);
static PAGE_BREAK_INSIDE = CssProp.reg(CssProp.AP.page_break_inside);
static POSITION = CssProp.reg(CssProp.AP.position);
static RESIZE = CssProp.reg(CssProp.AP.resize);
static SPEAK = CssProp.reg(CssProp.AP.speak);
static SPEAK_HEADER = CssProp.reg(CssProp.AP.speak_header);
static SPEAK_NUMERAL = CssProp.reg(CssProp.AP.speak_numeral);
static SPEAK_PUNCTUATION = CssProp.reg(CssProp.AP.speak_punctuation);
static TABLE_LAYOUT = CssProp.reg(CssProp.AP.table_layout);
static TEXT_ALIGN = CssProp.reg(CssProp.AP.text_align);
static TEXT_DECORATION = CssProp.reg(CssProp.AP.text_decoration);
static TEXT_TRANSFORM = CssProp.reg(CssProp.AP.text_transform);
static TEXT_WRAP = CssProp.reg(CssProp.AP.text_wrap);
static UNICODE_BIDI = CssProp.reg(CssProp.AP.unicode_bidi);
static VISIBILITY = CssProp.reg(CssProp.AP.visibility);
static WHITE_SPACE = CssProp.reg(CssProp.AP.white_space);
static WORD_BREAK = CssProp.reg(CssProp.AP.word_break);
static BACKGROUND_ATTACHMENT = CssProp.reg(CssProp.CP.background_attachment);
static BACKGROUND_COLOR = CssProp.reg(CssProp.CP.background_color);
static BACKGROUND_ORIGIN = CssProp.reg(CssProp.CP.background_origin);
static BACKGROUND_REPEAT = CssProp.reg(CssProp.CP.background_repeat);
static BORDER = CssProp.reg(CssProp.CP.border);
static BORDER_RADIUS = CssProp.reg(CssProp.CP.border_radius);
static BORDER_SPACING = CssProp.reg(CssProp.CP.border_spacing);
static BORDER_TOP_COLOR = CssProp.reg(CssProp.CP.border_top_color);
static BORDER_TOP_STYLE = CssProp.reg(CssProp.CP.border_top_style);
static BORDER_WIDTH = CssProp.reg(CssProp.CP.border_width);
static COLOR = CssProp.reg(CssProp.CP.color);
static CURSOR = CssProp.reg(CssProp.CP.cursor);
static DISPLAY = CssProp.reg(CssProp.CP.display);
static DISPLAY_OUTSIDE = CssProp.reg(CssProp.CP.display_outside);
static ELEVATION = CssProp.reg(CssProp.CP.elevation);
static FONT_FAMILY = CssProp.reg(CssProp.CP.font_family);
static HEIGHT = CssProp.reg(CssProp.CP.height);
static LETTER_SPACING = CssProp.reg(CssProp.CP.letter_spacing);
static LIST_STYLE_IMAGE = CssProp.reg(CssProp.CP.list_style_image);
static MARGIN_RIGHT = CssProp.reg(CssProp.CP.margin_right);
static MAX_HEIGHT = CssProp.reg(CssProp.CP.max_height);
static MIN_HEIGHT = CssProp.reg(CssProp.CP.min_height);
static OPACITY = CssProp.reg(CssProp.CP.opacity);
static OUTLINE_COLOR = CssProp.reg(CssProp.CP.outline_color);
static OUTLINE_WIDTH = CssProp.reg(CssProp.CP.outline_width);
static PADDING = CssProp.reg(CssProp.CP.padding);
static PADDING_TOP = CssProp.reg(CssProp.CP.padding_top);
static PITCH_RANGE = CssProp.reg(CssProp.CP.pitch_range);
static RIGHT = CssProp.reg(CssProp.CP.right);
static STRESS = CssProp.reg(CssProp.CP.stress);
static TEXT_INDENT = CssProp.reg(CssProp.CP.text_indent);
static TEXT_SHADOW = CssProp.reg(CssProp.CP.text_shadow);
static VOLUME = CssProp.reg(CssProp.CP.volume);
static WORD_WRAP = CssProp.reg(CssProp.CP.word_wrap);
static ZOOM = CssProp.reg(CssProp.CP.zoom);
static BACKFACE_VISIBILITY = CssProp.reg(CssProp.CP.backface_visibility);
static BACKGROUND_CLIP = CssProp.reg(CssProp.CP.background_clip);
static BACKGROUND_POSITION = CssProp.reg(CssProp.CP.background_position);
static BORDER_BOTTOM_COLOR = CssProp.reg(CssProp.CP.border_bottom_color);
static BORDER_BOTTOM_STYLE = CssProp.reg(CssProp.CP.border_bottom_style);
static BORDER_COLOR = CssProp.reg(CssProp.CP.border_color);
static BORDER_LEFT_COLOR = CssProp.reg(CssProp.CP.border_left_color);
static BORDER_RIGHT_COLOR = CssProp.reg(CssProp.CP.border_right_color);
static BORDER_STYLE = CssProp.reg(CssProp.CP.border_style);
static BORDER_TOP_LEFT_RADIUS = CssProp.reg(
CssProp.CP.border_top_left_radius
);
static BORDER_TOP_WIDTH = CssProp.reg(CssProp.CP.border_top_width);
static BOX_SHADOW = CssProp.reg(CssProp.CP.box_shadow);
static CLIP = CssProp.reg(CssProp.CP.clip);
static DISPLAY_INSIDE = CssProp.reg(CssProp.CP.display_inside);
static FONT_SIZE = CssProp.reg(CssProp.CP.font_size);
static LINE_HEIGHT = CssProp.reg(CssProp.CP.line_height);
static MARGIN_LEFT = CssProp.reg(CssProp.CP.margin_left);
static MAX_WIDTH = CssProp.reg(CssProp.CP.max_width);
static OUTLINE_STYLE = CssProp.reg(CssProp.CP.outline_style);
static PADDING_BOTTOM = CssProp.reg(CssProp.CP.padding_bottom);
static PADDING_RIGHT = CssProp.reg(CssProp.CP.padding_right);
static PERSPECTIVE = CssProp.reg(CssProp.CP.perspective);
static RICHNESS = CssProp.reg(CssProp.CP.richness);
static TEXT_OVERFLOW = CssProp.reg(CssProp.CP.text_overflow);
static TOP = CssProp.reg(CssProp.CP.top);
static WIDTH = CssProp.reg(CssProp.CP.width);
static Z_INDEX = CssProp.reg(CssProp.CP.z_index);
static BACKGROUND = CssProp.reg(CssProp.CP.background);
static BACKGROUND_SIZE = CssProp.reg(CssProp.CP.background_size);
static BORDER_BOTTOM_LEFT_RADIUS = CssProp.reg(
CssProp.CP.border_bottom_left_radius
);
static BORDER_BOTTOM_WIDTH = CssProp.reg(CssProp.CP.border_bottom_width);
static BORDER_LEFT_STYLE = CssProp.reg(CssProp.CP.border_left_style);
static BORDER_RIGHT_STYLE = CssProp.reg(CssProp.CP.border_right_style);
static BORDER_TOP = CssProp.reg(CssProp.CP.border_top);
static BOTTOM = CssProp.reg(CssProp.CP.bottom);
static LIST_STYLE = CssProp.reg(CssProp.CP.list_style);
static MARGIN_TOP = CssProp.reg(CssProp.CP.margin_top);
static OUTLINE = CssProp.reg(CssProp.CP.outline);
static OVERFLOW_Y = CssProp.reg(CssProp.CP.overflow_y);
static PITCH = CssProp.reg(CssProp.CP.pitch);
static VERTICAL_ALIGN = CssProp.reg(CssProp.CP.vertical_align);
static WORD_SPACING = CssProp.reg(CssProp.CP.word_spacing);
static BACKGROUND_IMAGE = CssProp.reg(CssProp.CP.background_image);
static BORDER_BOTTOM_RIGHT_RADIUS = CssProp.reg(
CssProp.CP.border_bottom_right_radius
);
static BORDER_LEFT_WIDTH = CssProp.reg(CssProp.CP.border_left_width);
static BORDER_RIGHT_WIDTH = CssProp.reg(CssProp.CP.border_right_width);
static LEFT = CssProp.reg(CssProp.CP.left);
static MARGIN_BOTTOM = CssProp.reg(CssProp.CP.margin_bottom);
static PAUSE_AFTER = CssProp.reg(CssProp.CP.pause_after);
static SPEECH_RATE = CssProp.reg(CssProp.CP.speech_rate);
static TRANSITION_DURATION = CssProp.reg(CssProp.CP.transition_duration);
static BORDER_BOTTOM = CssProp.reg(CssProp.CP.border_bottom);
static BORDER_RIGHT = CssProp.reg(CssProp.CP.border_right);
static MARGIN = CssProp.reg(CssProp.CP.margin);
static PADDING_LEFT = CssProp.reg(CssProp.CP.padding_left);
static BORDER_LEFT = CssProp.reg(CssProp.CP.border_left);
static FONT = CssProp.reg(CssProp.CP.font);
static QUOTES = CssProp.reg(CssProp.CP.quotes);
static BORDER_TOP_RIGHT_RADIUS = CssProp.reg(
CssProp.CP.border_top_right_radius
);
static MIN_WIDTH = CssProp.reg(CssProp.CP.min_width);
}
/**
* A class to sanitize HTML strings.
*/
export class Sanitizer implements ISanitizer {
/**
* Sanitize an HTML string.
*
* @param dirty - The dirty text.
*
* @param options - The optional sanitization options.
*
* @returns The sanitized string.
*/
sanitize(dirty: string, options?: ISanitizer.IOptions): string {
return sanitize(dirty, { ...this._options, ...(options || {}) });
}
private _options: sanitize.IOptions = {
// HTML tags that are allowed to be used. Tags were extracted from Google Caja
allowedTags: [
'a',
'abbr',
'acronym',
'address',
'area',
'article',
'aside',
'audio',
'b',
'bdi',
'bdo',
'big',
'blockquote',
'br',
'button',
'canvas',
'caption',
'center',
'cite',
'code',
'col',
'colgroup',
'colspan',
'command',
'data',
'datalist',
'dd',
'del',
'details',
'dfn',
'dir',
'div',
'dl',
'dt',
'em',
'fieldset',
'figcaption',
'figure',
'font',
'footer',
'form',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'header',
'hgroup',
'hr',
'i',
// 'iframe' is allowed by Google Caja, but disallowed by default by sanitize-html
// , 'iframe'
'img',
'input',
'ins',
'kbd',
'label',
'legend',
'li',
'map',
'mark',
'menu',
'meter',
'nav',
'nobr',
'ol',
'optgroup',
'option',
'output',
'p',
'pre',
'progress',
'q',
'rowspan',
's',
'samp',
'section',
'select',
'small',
'source',
'span',
'strike',
'strong',
'sub',
'summary',
'sup',
'table',
'tbody',
'td',
'textarea',
'tfoot',
'th',
'thead',
'time',
'tr',
'track',
'tt',
'u',
'ul',
'var',
'video',
'wbr'
],
// Attributes that HTML tags are allowed to have, extracted from Google Caja.
// See https://github.com/jupyterlab/jupyterlab/issues/1812#issuecomment-285848435
allowedAttributes: {
'*': [
'class',
'dir',
'draggable',
'hidden',
'id',
'inert',
'itemprop',
'itemref',
'itemscope',
'lang',
'spellcheck',
'style',
'title',
'translate'
],
// 'rel' and 'target' were *not* allowed by Google Caja
a: [
'accesskey',
'coords',
'href',
'hreflang',
'name',
'rel',
'shape',
'tabindex',
'target',
'type'
],
area: [
'accesskey',
'alt',
'coords',
'href',
'nohref',
'shape',
'tabindex'
],
// 'autoplay' was *not* allowed by Google Caja
audio: [
'autoplay',
'controls',
'loop',
'mediagroup',
'muted',
'preload',
'src'
],
bdo: ['dir'],
blockquote: ['cite'],
br: ['clear'],
button: [
'accesskey',
'data-commandlinker-args',
'data-commandlinker-command',
'disabled',
'name',
'tabindex',
'type',
'value'
],
canvas: ['height', 'width'],
caption: ['align'],
col: ['align', 'char', 'charoff', 'span', 'valign', 'width'],
colgroup: ['align', 'char', 'charoff', 'span', 'valign', 'width'],
command: [
'checked',
'command',
'disabled',
'icon',
'label',
'radiogroup',
'type'
],
data: ['value'],
del: ['cite', 'datetime'],
details: ['open'],
dir: ['compact'],
div: ['align'],
dl: ['compact'],
fieldset: ['disabled'],
font: ['color', 'face', 'size'],
form: [
'accept',
'autocomplete',
'enctype',
'method',
'name',
'novalidate'
],
h1: ['align'],
h2: ['align'],
h3: ['align'],
h4: ['align'],
h5: ['align'],
h6: ['align'],
hr: ['align', 'noshade', 'size', 'width'],
iframe: [
'align',
'frameborder',
'height',
'marginheight',
'marginwidth',
'width'
],
img: [
'align',
'alt',
'border',
'height',
'hspace',
'ismap',
'name',
'src',
'usemap',
'vspace',
'width'
],
input: [
'accept',
'accesskey',
'align',
'alt',
'autocomplete',
'checked',
'disabled',
'inputmode',
'ismap',
'list',
'max',
'maxlength',
'min',
'multiple',
'name',
'placeholder',
'readonly',
'required',
'size',
'src',
'step',
'tabindex',
'type',
'usemap',
'value'
],
ins: ['cite', 'datetime'],
label: ['accesskey', 'for'],
legend: ['accesskey', 'align'],
li: ['type', 'value'],
map: ['name'],
menu: ['compact', 'label', 'type'],
meter: ['high', 'low', 'max', 'min', 'value'],
ol: ['compact', 'reversed', 'start', 'type'],
optgroup: ['disabled', 'label'],
option: ['disabled', 'label', 'selected', 'value'],
output: ['for', 'name'],
p: ['align'],
pre: ['width'],
progress: ['max', 'min', 'value'],
q: ['cite'],
select: [
'autocomplete',
'disabled',
'multiple',
'name',
'required',
'size',
'tabindex'
],
source: ['type'],
table: [
'align',
'bgcolor',
'border',
'cellpadding',
'cellspacing',
'frame',
'rules',
'summary',
'width'
],
tbody: ['align', 'char', 'charoff', 'valign'],
td: [
'abbr',
'align',
'axis',
'bgcolor',
'char',
'charoff',
'colspan',
'headers',
'height',
'nowrap',
'rowspan',
'scope',
'valign',
'width'
],
textarea: [
'accesskey',
'autocomplete',
'cols',
'disabled',
'inputmode',
'name',
'placeholder',
'readonly',
'required',
'rows',
'tabindex',
'wrap'
],
tfoot: ['align', 'char', 'charoff', 'valign'],
th: [
'abbr',
'align',
'axis',
'bgcolor',
'char',
'charoff',
'colspan',
'headers',
'height',
'nowrap',
'rowspan',
'scope',
'valign',
'width'
],
thead: ['align', 'char', 'charoff', 'valign'],
tr: ['align', 'bgcolor', 'char', 'charoff', 'valign'],
track: ['default', 'kind', 'label', 'srclang'],
ul: ['compact', 'type'],
video: [
'autoplay',
'controls',
'height',
'loop',
'mediagroup',
'muted',
'poster',
'preload',
'src',
'width'
]
},
// Inline CSS styles that HTML tags may have (and their allowed values)
allowedStyles: {
// To simplify the data, all styles are allowed on all tags that allow the style attribute
'*': {
'backface-visibility': [CssProp.BACKFACE_VISIBILITY],
background: [CssProp.BACKGROUND],
'background-attachment': [CssProp.BACKGROUND_ATTACHMENT],
'background-clip': [CssProp.BACKGROUND_CLIP],
'background-color': [CssProp.BACKGROUND_COLOR],
'background-image': [CssProp.BACKGROUND_IMAGE],
'background-origin': [CssProp.BACKGROUND_ORIGIN],
'background-position': [CssProp.BACKGROUND_POSITION],
'background-repeat': [CssProp.BACKGROUND_REPEAT],
'background-size': [CssProp.BACKGROUND_SIZE],
border: [CssProp.BORDER],
'border-bottom': [CssProp.BORDER_BOTTOM],
'border-bottom-color': [CssProp.BORDER_BOTTOM_COLOR],
'border-bottom-left-radius': [CssProp.BORDER_BOTTOM_LEFT_RADIUS],
'border-bottom-right-radius': [CssProp.BORDER_BOTTOM_RIGHT_RADIUS],
'border-bottom-style': [CssProp.BORDER_BOTTOM_STYLE],
'border-bottom-width': [CssProp.BORDER_BOTTOM_WIDTH],
'border-collapse': [CssProp.BORDER_COLLAPSE],
'border-color': [CssProp.BORDER_COLOR],
'border-left': [CssProp.BORDER_LEFT],
'border-left-color': [CssProp.BORDER_LEFT_COLOR],
'border-left-style': [CssProp.BORDER_LEFT_STYLE],
'border-left-width': [CssProp.BORDER_LEFT_WIDTH],
'border-radius': [CssProp.BORDER_RADIUS],
'border-right': [CssProp.BORDER_RIGHT],
'border-right-color': [CssProp.BORDER_RIGHT_COLOR],
'border-right-style': [CssProp.BORDER_RIGHT_STYLE],
'border-right-width': [CssProp.BORDER_RIGHT_WIDTH],
'border-spacing': [CssProp.BORDER_SPACING],
'border-style': [CssProp.BORDER_STYLE],
'border-top': [CssProp.BORDER_TOP],
'border-top-color': [CssProp.BORDER_TOP_COLOR],
'border-top-left-radius': [CssProp.BORDER_TOP_LEFT_RADIUS],
'border-top-right-radius': [CssProp.BORDER_TOP_RIGHT_RADIUS],
'border-top-style': [CssProp.BORDER_TOP_STYLE],
'border-top-width': [CssProp.BORDER_TOP_WIDTH],
'border-width': [CssProp.BORDER_WIDTH],
bottom: [CssProp.BOTTOM],
box: [CssProp.BOX],
'box-shadow': [CssProp.BOX_SHADOW],
'box-sizing': [CssProp.BOX_SIZING],
'caption-side': [CssProp.CAPTION_SIDE],
clear: [CssProp.CLEAR],
clip: [CssProp.CLIP],
color: [CssProp.COLOR],
cursor: [CssProp.CURSOR],
direction: [CssProp.DIRECTION],
display: [CssProp.DISPLAY],
'display-inside': [CssProp.DISPLAY_INSIDE],
'display-outside': [CssProp.DISPLAY_OUTSIDE],
elevation: [CssProp.ELEVATION],
'empty-cells': [CssProp.EMPTY_CELLS],
float: [CssProp.FLOAT],
font: [CssProp.FONT],
'font-family': [CssProp.FONT_FAMILY],
'font-size': [CssProp.FONT_SIZE],
'font-stretch': [CssProp.FONT_STRETCH],
'font-style': [CssProp.FONT_STYLE],
'font-variant': [CssProp.FONT_VARIANT],
'font-weight': [CssProp.FONT_WEIGHT],
height: [CssProp.HEIGHT],
left: [CssProp.LEFT],
'letter-spacing': [CssProp.LETTER_SPACING],
'line-height': [CssProp.LINE_HEIGHT],
'list-style': [CssProp.LIST_STYLE],
'list-style-image': [CssProp.LIST_STYLE_IMAGE],
'list-style-position': [CssProp.LIST_STYLE_POSITION],
'list-style-type': [CssProp.LIST_STYLE_TYPE],
margin: [CssProp.MARGIN],
'margin-bottom': [CssProp.MARGIN_BOTTOM],
'margin-left': [CssProp.MARGIN_LEFT],
'margin-right': [CssProp.MARGIN_RIGHT],
'margin-top': [CssProp.MARGIN_TOP],
'max-height': [CssProp.MAX_HEIGHT],
'max-width': [CssProp.MAX_WIDTH],
'min-height': [CssProp.MIN_HEIGHT],
'min-width': [CssProp.MIN_WIDTH],
opacity: [CssProp.OPACITY],
outline: [CssProp.OUTLINE],
'outline-color': [CssProp.OUTLINE_COLOR],
'outline-style': [CssProp.OUTLINE_STYLE],
'outline-width': [CssProp.OUTLINE_WIDTH],
overflow: [CssProp.OVERFLOW],
'overflow-wrap': [CssProp.OVERFLOW_WRAP],
'overflow-x': [CssProp.OVERFLOW_X],
'overflow-y': [CssProp.OVERFLOW_Y],
padding: [CssProp.PADDING],
'padding-bottom': [CssProp.PADDING_BOTTOM],
'padding-left': [CssProp.PADDING_LEFT],
'padding-right': [CssProp.PADDING_RIGHT],
'padding-top': [CssProp.PADDING_TOP],
'page-break-after': [CssProp.PAGE_BREAK_AFTER],
'page-break-before': [CssProp.PAGE_BREAK_BEFORE],
'page-break-inside': [CssProp.PAGE_BREAK_INSIDE],
'pause-after': [CssProp.PAUSE_AFTER],
perspective: [CssProp.PERSPECTIVE],
pitch: [CssProp.PITCH],
'pitch-range': [CssProp.PITCH_RANGE],
position: [CssProp.POSITION],
quotes: [CssProp.QUOTES],
resize: [CssProp.RESIZE],
richness: [CssProp.RICHNESS],
right: [CssProp.RIGHT],
speak: [CssProp.SPEAK],
'speak-header': [CssProp.SPEAK_HEADER],
'speak-numeral': [CssProp.SPEAK_NUMERAL],
'speak-punctuation': [CssProp.SPEAK_PUNCTUATION],
'speech-rate': [CssProp.SPEECH_RATE],
stress: [CssProp.STRESS],
'table-layout': [CssProp.TABLE_LAYOUT],
'text-align': [CssProp.TEXT_ALIGN],
'text-decoration': [CssProp.TEXT_DECORATION],
'text-indent': [CssProp.TEXT_INDENT],
'text-overflow': [CssProp.TEXT_OVERFLOW],
'text-shadow': [CssProp.TEXT_SHADOW],
'text-transform': [CssProp.TEXT_TRANSFORM],
'text-wrap': [CssProp.TEXT_WRAP],
top: [CssProp.TOP],
'unicode-bidi': [CssProp.UNICODE_BIDI],
'vertical-align': [CssProp.VERTICAL_ALIGN],
visibility: [CssProp.VISIBILITY],
volume: [CssProp.VOLUME],
'white-space': [CssProp.WHITE_SPACE],
width: [CssProp.WIDTH],
'word-break': [CssProp.WORD_BREAK],
'word-spacing': [CssProp.WORD_SPACING],
'word-wrap': [CssProp.WORD_WRAP],
'z-index': [CssProp.Z_INDEX],
zoom: [CssProp.ZOOM]
}
},
transformTags: {
// Set the "rel" attribute for <a> tags to "nofollow".
a: sanitize.simpleTransform('a', { rel: 'nofollow' }),
// Set the "disabled" attribute for <input> tags.
input: sanitize.simpleTransform('input', { disabled: 'disabled' })
},
allowedSchemesByTag: {
// Allow 'attachment:' img src (used for markdown cell attachments).
img: sanitize.defaults.allowedSchemes.concat(['attachment'])
},
// Override of the default option, so we can skip 'src' attribute validation.
// 'src' Attributes are validated to be URIs, which does not allow for embedded (image) data.
// Since embedded data is no longer deemed to be a threat, validation can be skipped.
// See https://github.com/jupyterlab/jupyterlab/issues/5183
allowedSchemesAppliedToAttributes: ['href', 'cite']
};
}
/**
* The default instance of an `ISanitizer` meant for use by user code.
*/
export const defaultSanitizer: ISanitizer = new Sanitizer();
|
504825938c0abfa2fb8ff8d529308830a5ae42ed
|
https://github.com/jupyterlab/jupyterlab
|
make_subset.php
|
php
|
<?php
/**
* @package php-font-lib
* @link https://github.com/PhenX/php-font-lib
* @author Fabien Ménager <fabien.menager@gmail.com>
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
*/
use FontLib\Font;
use FontLib\Binary_Stream;
$fontfile = null;
if (isset($_GET["fontfile"])) {
$fontfile = basename($_GET["fontfile"]);
$fontfile = "../fonts/$fontfile";
}
if (!file_exists($fontfile)) {
return;
}
$name = isset($_GET["name"]) ? $_GET["name"] : null;
if (isset($_POST["subset"])) {
$subset = $_POST["subset"];
ob_start();
require_once "../src/FontLib/Autoloader.php";
$font = Font::load($fontfile);
$font->parse();
$font->setSubset($subset);
$font->reduce();
$new_filename = basename($fontfile);
$dot = strpos($new_filename, ".");
$new_filename = substr($new_filename, 0, $dot)."-subset".substr($new_filename, $dot);
header("Content-Type: font/truetype");
header("Content-Disposition: attachment; filename=\"$new_filename\"");
$tmp = tempnam(sys_get_temp_dir(), "fnt");
$font->open($tmp, Binary_Stream::modeWrite);
$font->encode(array("OS/2"));
$font->close();
ob_end_clean();
readfile($tmp);
unlink($tmp);
return;
} ?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Subset maker</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<h1><?php echo $name; ?></h1>
<form name="make-subset" method="post" action="?fontfile=<?php echo $fontfile; ?>">
<label>
Insert the text from which you want the glyphs in the subsetted font: <br />
<textarea name="subset" cols="50" rows="20"></textarea>
</label>
<br />
<button type="submit">Make subset!</button>
</form>
</body>
</html>
|
<?php
/**
* @package php-font-lib
* @link https://github.com/PhenX/php-font-lib
* @author Fabien Ménager <fabien.menager@gmail.com>
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
*/
use FontLib\Font;
use FontLib\Binary_Stream;
$fontfile = null;
if (isset($_GET["fontfile"])) {
$fontfile = basename($_GET["fontfile"]);
$fontfile = "../fonts/$fontfile";
}
if (!file_exists($fontfile)) {
return;
}
$name = isset($_GET["name"]) ? $_GET["name"] : null;
if (isset($_POST["subset"])) {
$subset = $_POST["subset"];
ob_start();
require_once "../src/FontLib/Autoloader.php";
$font = Font::load($fontfile);
$font->parse();
$font->setSubset($subset);
$font->reduce();
$new_filename = basename($fontfile);
$dot = strpos($new_filename, ".");
$new_filename = substr($new_filename, 0, $dot)."-subset".substr($new_filename, $dot);
header("Content-Type: font/truetype");
header("Content-Disposition: attachment; filename=\"$new_filename\"");
$tmp = tempnam(sys_get_temp_dir(), "fnt");
$font->open($tmp, Binary_Stream::modeWrite);
$font->encode(array("OS/2"));
$font->close();
ob_end_clean();
readfile($tmp);
unlink($tmp);
return;
} ?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Subset maker</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<h1><?php echo htmlentities($name); ?></h1>
<form name="make-subset" method="post" action="?fontfile=<?php echo $fontfile; ?>">
<label>
Insert the text from which you want the glyphs in the subsetted font: <br />
<textarea name="subset" cols="50" rows="20"></textarea>
</label>
<br />
<button type="submit">Make subset!</button>
</form>
</body>
</html>
|
d13682b7e27d14a6323c441426f3dde1cd86c751
|
https://github.com/phenx/php-font-lib
|
call_plugin.php
|
php
|
<?php
/**
* This file gets used to access {@link Plugin} methods that are marked to be accessible this
* way. See {@link Plugin::GetHtsrvMethods()}.
*
* This file is part of the evoCore framework - {@link http://evocore.net/}
* See also {@link https://github.com/b2evolution/b2evolution}.
*
* @license GNU GPL v2 - {@link http://b2evolution.net/about/gnu-gpl-license}
*
* @copyright (c)2003-2016 by Francois Planque - {@link http://fplanque.com/}
* Parts of this file are copyright (c)2004-2006 by Daniel HAHLER - {@link http://thequod.de/contact}.
*
* @package htsrv
*/
/**
* Initialize:
* TODO: Don't do a full init!
*/
require_once dirname(__FILE__).'/../conf/_config.php';
require_once $inc_path.'_main.inc.php';
param( 'plugin_ID', 'integer', true );
// fp> it is probably unnecessary complexity to handle a method here
// instead of calling handle_htsrv_action() all the time
// and letting the plugin deal with its methods internally.
param( 'method', 'string', '' );
param( 'params', 'string', null ); // serialized
if( is_null( $params ) )
{ // Use empty array by default if params are not sent by request:
$params = array();
}
else
{ // Params given:
if( ( substr( $params, 0, 2 ) == 'a:' ) && ( ! preg_match( '/(;|{|})O:\+?[0-9]+:"/', $params ) ) )
{ // Allow to unserialize only arrays + check there is no Object in the array (We NEVER want to unserialize an object)
// (This may result in "false", but this means that unserializing failed)
$params = @unserialize( $params );
}
else
{ // Restrict all non array params to empty array:
bad_request_die( 'Invalid params! Cannot unserialize.' );
}
}
if( $plugin_ID )
{
$Plugin = & $Plugins->get_by_ID( $plugin_ID );
if( ! $Plugin )
{
bad_request_die( 'Invalid Plugin! (maybe not enabled?)' );
}
if( method_exists( $Plugin, 'get_htsrv_methods' ) )
{ // TODO: get_htsrv_methods is deprecated, but should stay here for transformation! (blueyed, 2006-04-27)
if( ! in_array( $method, $Plugin->get_htsrv_methods() ) )
{
bad_request_die( 'Call to non-htsrv Plugin method!' );
}
}
else
if( ! in_array( $method, $Plugin->GetHtsrvMethods() ) )
{
bad_request_die( 'Call to non-htsrv Plugin method!' );
}
elseif( ! method_exists( $Plugin, 'htsrv_'.$method ) )
{
bad_request_die( 'htsrv method does not exist!' );
}
// Call the method:
$Plugins->call_method( $Plugin->ID, 'htsrv_'.$method, $params );
}
?>
|
<?php
/**
* This file gets used to access {@link Plugin} methods that are marked to be accessible this
* way. See {@link Plugin::GetHtsrvMethods()}.
*
* This file is part of the evoCore framework - {@link http://evocore.net/}
* See also {@link https://github.com/b2evolution/b2evolution}.
*
* @license GNU GPL v2 - {@link http://b2evolution.net/about/gnu-gpl-license}
*
* @copyright (c)2003-2016 by Francois Planque - {@link http://fplanque.com/}
* Parts of this file are copyright (c)2004-2006 by Daniel HAHLER - {@link http://thequod.de/contact}.
*
* @package htsrv
*/
/**
* Initialize:
* TODO: Don't do a full init!
*/
require_once dirname(__FILE__).'/../conf/_config.php';
require_once $inc_path.'_main.inc.php';
param( 'plugin_ID', 'integer', true );
// fp> it is probably unnecessary complexity to handle a method here
// instead of calling handle_htsrv_action() all the time
// and letting the plugin deal with its methods internally.
param( 'method', 'string', '' );
param( 'params', 'string', null ); // serialized
if( is_null( $params ) )
{ // Use empty array by default if params are not sent by request:
$params = array();
}
else
{ // Params given:
if( ( substr( $params, 0, 2 ) == 'a:' ) && ( ! preg_match( '/(s:\d+:"[^"]*"|i:\d+)(;|{|})O:\+?[0-9]+:"/', $params ) ) )
{ // Allow to unserialize only arrays + check there is no Object in the array (We NEVER want to unserialize an object)
// (This may result in "false", but this means that unserializing failed)
$params = @unserialize( $params );
}
else
{ // Restrict all non array params to empty array:
bad_request_die( 'Invalid params! Cannot unserialize.' );
}
}
if( $plugin_ID )
{
$Plugin = & $Plugins->get_by_ID( $plugin_ID );
if( ! $Plugin )
{
bad_request_die( 'Invalid Plugin! (maybe not enabled?)' );
}
if( method_exists( $Plugin, 'get_htsrv_methods' ) )
{ // TODO: get_htsrv_methods is deprecated, but should stay here for transformation! (blueyed, 2006-04-27)
if( ! in_array( $method, $Plugin->get_htsrv_methods() ) )
{
bad_request_die( 'Call to non-htsrv Plugin method!' );
}
}
else
if( ! in_array( $method, $Plugin->GetHtsrvMethods() ) )
{
bad_request_die( 'Call to non-htsrv Plugin method!' );
}
elseif( ! method_exists( $Plugin, 'htsrv_'.$method ) )
{
bad_request_die( 'htsrv method does not exist!' );
}
// Call the method:
$Plugins->call_method( $Plugin->ID, 'htsrv_'.$method, $params );
}
?>
|
999b5ad1d59760d7e450ceb541f55432fc74cd27
|
https://github.com/b2evolution/b2evolution
|
constants.ts
|
typescript
|
import * as os from 'os'
import * as chalk from 'chalk'
// eslint-disable-next-line dot-notation
export const PLATFORMS = global['PLATFORMS'] = global['PLATFORMS'] || {}
export const enum processTypeEnum {
START = 'start',
CREATE = 'create',
COMPILE = 'compile',
CONVERT = 'convert',
COPY = 'copy',
GENERATE = 'generate',
MODIFY = 'modify',
ERROR = 'error',
WARNING = 'warning',
UNLINK = 'unlink',
REFERENCE = 'reference',
REMIND = 'remind'
}
export interface IProcessTypeMap {
[key: string]: {
name: string,
color: string | chalk.Chalk
}
}
export const processTypeMap: IProcessTypeMap = {
[processTypeEnum.CREATE]: {
name: '创建',
color: 'cyan'
},
[processTypeEnum.COMPILE]: {
name: '编译',
color: 'green'
},
[processTypeEnum.CONVERT]: {
name: '转换',
color: chalk.rgb(255, 136, 0)
},
[processTypeEnum.COPY]: {
name: '拷贝',
color: 'magenta'
},
[processTypeEnum.GENERATE]: {
name: '生成',
color: 'blue'
},
[processTypeEnum.MODIFY]: {
name: '修改',
color: 'yellow'
},
[processTypeEnum.ERROR]: {
name: '错误',
color: 'red'
},
[processTypeEnum.WARNING]: {
name: '警告',
color: 'yellowBright'
},
[processTypeEnum.UNLINK]: {
name: '删除',
color: 'magenta'
},
[processTypeEnum.START]: {
name: '启动',
color: 'green'
},
[processTypeEnum.REFERENCE]: {
name: '引用',
color: 'blue'
},
[processTypeEnum.REMIND]: {
name: '提示',
color: 'green'
}
}
export const CSS_EXT: string[] = ['.css', '.scss', '.sass', '.less', '.styl', '.stylus', '.wxss', '.acss']
export const SCSS_EXT: string[] = ['.scss']
export const JS_EXT: string[] = ['.js', '.jsx']
export const TS_EXT: string[] = ['.ts', '.tsx']
export const UX_EXT: string[] = ['.ux']
export const SCRIPT_EXT: string[] = JS_EXT.concat(TS_EXT)
export const VUE_EXT: string[] = ['.vue']
export const REG_JS = /\.js(\?.*)?$/
export const REG_SCRIPT = /\.(js|jsx)(\?.*)?$/
export const REG_TYPESCRIPT = /\.(tsx|ts)(\?.*)?$/
export const REG_SCRIPTS = /\.[tj]sx?$/i
export const REG_VUE = /\.vue$/i
export const REG_SASS = /\.(s[ac]ss)$/
export const REG_SASS_SASS = /\.sass$/
export const REG_SASS_SCSS = /\.scss$/
export const REG_LESS = /\.less$/
export const REG_STYLUS = /\.styl(us)?$/
export const REG_STYLE = /\.(css|scss|sass|less|styl|stylus|wxss|acss|ttss|jxss|qss)(\?.*)?$/
export const REG_CSS = /\.(css|wxss|acss|ttss)(\?.*)?$/
export const REG_MEDIA = /\.(mp4|webm|ogg|mp3|m4a|wav|flac|aac)(\?.*)?$/
export const REG_IMAGE = /\.(png|jpe?g|gif|bpm|svg|webp)(\?.*)?$/
export const REG_FONT = /\.(woff2?|eot|ttf|otf)(\?.*)?$/
export const REG_JSON = /\.json(\?.*)?$/
export const REG_UX = /\.ux(\?.*)?$/
export const REG_TEMPLATE = /\.(wxml|axml|ttml|qml|swan|jxml)(\?.*)?$/
export const REG_WXML_IMPORT = /<import(.*)?src=(?:(?:'([^']*)')|(?:"([^"]*)"))/gi
export const REG_URL = /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?$/i
export const CSS_IMPORT_REG = /@import (["'])(.+?)\1;/g
export const NODE_MODULES = 'node_modules'
export const NODE_MODULES_REG = /(.*)node_modules/
export const PROJECT_CONFIG = 'config/index'
export const DEVICE_RATIO = {
640: 2.34 / 2,
750: 1,
828: 1.81 / 2
}
export const FILE_PROCESSOR_MAP = {
'.js': 'babel',
'.scss': 'sass',
'.sass': 'sass',
'.less': 'less',
'.styl': 'stylus'
}
export const UPDATE_PACKAGE_LIST = [
'babel-plugin-transform-taroapi',
'babel-preset-taro',
'eslint-config-taro',
'eslint-plugin-taro',
'postcss-plugin-constparse',
'postcss-pxtransform',
'@tarojs/shared',
'@tarojs/taro',
'@tarojs/cli',
'@tarojs/components',
'@tarojs/taro-h5',
'@tarojs/helper',
'@tarojs/taro-loader',
'@tarojs/mini-runner',
'@tarojs/react',
'@tarojs/router',
'@tarojs/runner-utils',
'@tarojs/runtime',
'@tarojs/service',
'@tarojs/webpack-runner',
'@tarojs/with-weapp',
'@tarojs/taroize',
'@tarojs/plugin-platform-weapp',
'@tarojs/plugin-platform-alipay',
'@tarojs/plugin-platform-swan',
'@tarojs/plugin-platform-tt',
'@tarojs/plugin-platform-qq',
'@tarojs/plugin-platform-jd',
'nervjs',
'nerv-devtools'
]
export enum META_TYPE {
ENTRY = 'ENTRY',
PAGE = 'PAGE',
COMPONENT = 'COMPONENT',
NORMAL = 'NORMAL',
STATIC = 'STATIC',
CONFIG = 'CONFIG',
EXPORTS = 'EXPORTS'
}
export const taroJsComponents = '@tarojs/components'
export const taroJsQuickAppComponents = '@tarojs/components-qa'
export const taroJsFramework = '@tarojs/taro'
export const taroJsRedux = '@tarojs/redux'
export const taroJsMobx = '@tarojs/mobx'
export const taroJsMobxCommon = '@tarojs/mobx-common'
export const DEVICE_RATIO_NAME = 'deviceRatio'
export const isWindows = os.platform() === 'win32'
export const DEFAULT_TEMPLATE_SRC = 'github:NervJS/taro-project-templates#v3.1'
export const DEFAULT_TEMPLATE_SRC_GITEE = 'direct:https://gitee.com/o2team/taro-project-templates.git#v3.1'
export const TARO_CONFIG_FLODER = '.taro3.1'
export const TARO_BASE_CONFIG = 'index.json'
export const OUTPUT_DIR = 'dist'
export const SOURCE_DIR = 'src'
export const TEMP_DIR = '.temp'
export const NPM_DIR = 'npm'
export const ENTRY = 'app'
export enum FRAMEWORK_MAP {
VUE = 'vue',
VUE3 = 'vue3',
REACT = 'react',
NERV = 'nerv'
}
export const FRAMEWORK_EXT_MAP = {
vue: VUE_EXT,
vue3: VUE_EXT,
react: SCRIPT_EXT,
nerv: SCRIPT_EXT
}
|
import * as os from 'os'
import * as chalk from 'chalk'
// eslint-disable-next-line dot-notation
export const PLATFORMS = global['PLATFORMS'] = global['PLATFORMS'] || {}
export const enum processTypeEnum {
START = 'start',
CREATE = 'create',
COMPILE = 'compile',
CONVERT = 'convert',
COPY = 'copy',
GENERATE = 'generate',
MODIFY = 'modify',
ERROR = 'error',
WARNING = 'warning',
UNLINK = 'unlink',
REFERENCE = 'reference',
REMIND = 'remind'
}
export interface IProcessTypeMap {
[key: string]: {
name: string,
color: string | chalk.Chalk
}
}
export const processTypeMap: IProcessTypeMap = {
[processTypeEnum.CREATE]: {
name: '创建',
color: 'cyan'
},
[processTypeEnum.COMPILE]: {
name: '编译',
color: 'green'
},
[processTypeEnum.CONVERT]: {
name: '转换',
color: chalk.rgb(255, 136, 0)
},
[processTypeEnum.COPY]: {
name: '拷贝',
color: 'magenta'
},
[processTypeEnum.GENERATE]: {
name: '生成',
color: 'blue'
},
[processTypeEnum.MODIFY]: {
name: '修改',
color: 'yellow'
},
[processTypeEnum.ERROR]: {
name: '错误',
color: 'red'
},
[processTypeEnum.WARNING]: {
name: '警告',
color: 'yellowBright'
},
[processTypeEnum.UNLINK]: {
name: '删除',
color: 'magenta'
},
[processTypeEnum.START]: {
name: '启动',
color: 'green'
},
[processTypeEnum.REFERENCE]: {
name: '引用',
color: 'blue'
},
[processTypeEnum.REMIND]: {
name: '提示',
color: 'green'
}
}
export const CSS_EXT: string[] = ['.css', '.scss', '.sass', '.less', '.styl', '.stylus', '.wxss', '.acss']
export const SCSS_EXT: string[] = ['.scss']
export const JS_EXT: string[] = ['.js', '.jsx']
export const TS_EXT: string[] = ['.ts', '.tsx']
export const UX_EXT: string[] = ['.ux']
export const SCRIPT_EXT: string[] = JS_EXT.concat(TS_EXT)
export const VUE_EXT: string[] = ['.vue']
export const REG_JS = /\.js(\?.*)?$/
export const REG_SCRIPT = /\.(js|jsx)(\?.*)?$/
export const REG_TYPESCRIPT = /\.(tsx|ts)(\?.*)?$/
export const REG_SCRIPTS = /\.[tj]sx?$/i
export const REG_VUE = /\.vue$/i
export const REG_SASS = /\.(s[ac]ss)$/
export const REG_SASS_SASS = /\.sass$/
export const REG_SASS_SCSS = /\.scss$/
export const REG_LESS = /\.less$/
export const REG_STYLUS = /\.styl(us)?$/
export const REG_STYLE = /\.(css|scss|sass|less|styl|stylus|wxss|acss|ttss|jxss|qss)(\?.*)?$/
export const REG_CSS = /\.(css|wxss|acss|ttss)(\?.*)?$/
export const REG_MEDIA = /\.(mp4|webm|ogg|mp3|m4a|wav|flac|aac)(\?.*)?$/
export const REG_IMAGE = /\.(png|jpe?g|gif|bpm|svg|webp)(\?.*)?$/
export const REG_FONT = /\.(woff2?|eot|ttf|otf)(\?.*)?$/
export const REG_JSON = /\.json(\?.*)?$/
export const REG_UX = /\.ux(\?.*)?$/
export const REG_TEMPLATE = /\.(wxml|axml|ttml|qml|swan|jxml)(\?.*)?$/
export const REG_WXML_IMPORT = /<import(.*)?src=(?:(?:'([^']*)')|(?:"([^"]*)"))/gi
export const REG_URL = /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u00a1-\uffff][a-z0-9\u00a1-\uffff_-]{0,62})?[a-z0-9\u00a1-\uffff]\.)+(?:[a-z\u00a1-\uffff]{2,}\.?))(?::\d{2,5})?(?:[/?#]\S*)?$/i
export const CSS_IMPORT_REG = /@import (["'])(.+?)\1;/g
export const NODE_MODULES = 'node_modules'
export const NODE_MODULES_REG = /(.*)node_modules/
export const PROJECT_CONFIG = 'config/index'
export const DEVICE_RATIO = {
640: 2.34 / 2,
750: 1,
828: 1.81 / 2
}
export const FILE_PROCESSOR_MAP = {
'.js': 'babel',
'.scss': 'sass',
'.sass': 'sass',
'.less': 'less',
'.styl': 'stylus'
}
export const UPDATE_PACKAGE_LIST = [
'babel-plugin-transform-taroapi',
'babel-preset-taro',
'eslint-config-taro',
'eslint-plugin-taro',
'postcss-plugin-constparse',
'postcss-pxtransform',
'@tarojs/shared',
'@tarojs/taro',
'@tarojs/cli',
'@tarojs/components',
'@tarojs/taro-h5',
'@tarojs/helper',
'@tarojs/taro-loader',
'@tarojs/mini-runner',
'@tarojs/react',
'@tarojs/router',
'@tarojs/runner-utils',
'@tarojs/runtime',
'@tarojs/service',
'@tarojs/webpack-runner',
'@tarojs/with-weapp',
'@tarojs/taroize',
'@tarojs/plugin-platform-weapp',
'@tarojs/plugin-platform-alipay',
'@tarojs/plugin-platform-swan',
'@tarojs/plugin-platform-tt',
'@tarojs/plugin-platform-qq',
'@tarojs/plugin-platform-jd',
'nervjs',
'nerv-devtools'
]
export enum META_TYPE {
ENTRY = 'ENTRY',
PAGE = 'PAGE',
COMPONENT = 'COMPONENT',
NORMAL = 'NORMAL',
STATIC = 'STATIC',
CONFIG = 'CONFIG',
EXPORTS = 'EXPORTS'
}
export const taroJsComponents = '@tarojs/components'
export const taroJsQuickAppComponents = '@tarojs/components-qa'
export const taroJsFramework = '@tarojs/taro'
export const taroJsRedux = '@tarojs/redux'
export const taroJsMobx = '@tarojs/mobx'
export const taroJsMobxCommon = '@tarojs/mobx-common'
export const DEVICE_RATIO_NAME = 'deviceRatio'
export const isWindows = os.platform() === 'win32'
export const DEFAULT_TEMPLATE_SRC = 'github:NervJS/taro-project-templates#v3.1'
export const DEFAULT_TEMPLATE_SRC_GITEE = 'direct:https://gitee.com/o2team/taro-project-templates.git#v3.1'
export const TARO_CONFIG_FLODER = '.taro3.1'
export const TARO_BASE_CONFIG = 'index.json'
export const OUTPUT_DIR = 'dist'
export const SOURCE_DIR = 'src'
export const TEMP_DIR = '.temp'
export const NPM_DIR = 'npm'
export const ENTRY = 'app'
export enum FRAMEWORK_MAP {
VUE = 'vue',
VUE3 = 'vue3',
REACT = 'react',
NERV = 'nerv'
}
export const FRAMEWORK_EXT_MAP = {
vue: VUE_EXT,
vue3: VUE_EXT,
react: SCRIPT_EXT,
nerv: SCRIPT_EXT
}
|
acadb6c826ba57f2030a626f1de4f7b4608fcdb5
|
https://github.com/nervjs/taro
|
index.php
|
php
|
<?php
/**
* The main admin backend index file.
*
* 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 phpMyFAQ
* @author Thorsten Rinne <thorsten@phpmyfaq.de>
* @author Bastian Poettner <bastian@poettner.net>
* @author Meikel Katzengreis <meikel@katzengreis.com>
* @author Minoru TODA <todam@netjapan.co.jp>
* @author Matteo Scaramuccia <matteo@phpmyfaq.de>
* @copyright 2002-2022 phpMyFAQ Team
* @license http://www.mozilla.org/MPL/2.0/ Mozilla Public License Version 2.0
* @link https://www.phpmyfaq.de
* @since 2002-09-16
*/
use phpMyFAQ\Attachment\AttachmentFactory;
use phpMyFAQ\Auth\AuthLdap;
use phpMyFAQ\Auth\AuthSso;
use phpMyFAQ\Faq;
use phpMyFAQ\Filter;
use phpMyFAQ\Helper\HttpHelper;
use phpMyFAQ\Language;
use phpMyFAQ\Language\Plurals;
use phpMyFAQ\Logging;
use phpMyFAQ\Permission\MediumPermission;
use phpMyFAQ\Strings;
use phpMyFAQ\System;
use phpMyFAQ\Template;
use phpMyFAQ\User\CurrentUser;
define('PMF_ROOT_DIR', dirname(__DIR__));
//
// Define the named constant used as a check by any included PHP file
//
const IS_VALID_PHPMYFAQ = null;
//
// Bootstrapping
//
require PMF_ROOT_DIR . '/src/Bootstrap.php';
// get language (default: english)
$Language = new Language($faqConfig);
$faqLangCode = $Language->setLanguage($faqConfig->get('main.languageDetection'), $faqConfig->get('main.language'));
// Preload English strings
require PMF_ROOT_DIR . '/lang/language_en.php';
$faqConfig->setLanguage($Language);
if (isset($faqLangCode) && Language::isASupportedLanguage($faqLangCode)) {
// Overwrite English strings with the ones we have in the current language
if (!file_exists(PMF_ROOT_DIR . '/lang/language_' . $faqLangCode . '.php')) {
$faqLangCode = 'en';
}
require PMF_ROOT_DIR . '/lang/language_' . $faqLangCode . '.php';
} else {
$faqLangCode = 'en';
}
//
// Load plurals support for selected language
//
$plr = new Plurals($PMF_LANG);
//
// Initializing static string wrapper
//
Strings::init($faqLangCode);
//
// Set actual template set name
//
Template::setTplSetName($faqConfig->get('main.templateSet'));
//
// Initialize attachment factory
//
AttachmentFactory::init(
$faqConfig->get('records.attachmentsStorageType'),
$faqConfig->get('records.defaultAttachmentEncKey'),
$faqConfig->get('records.enableAttachmentEncryption')
);
//
// Create a new phpMyFAQ system object
//
$faqSystem = new System();
//
// Create a new HTTP Helper
//
$http = new HttpHelper();
//
// Create a new FAQ object
//
$faq = new Faq($faqConfig);
//
// use mbstring extension if available and when possible
//
$validMbStrings = array('ja', 'en', 'uni');
$mbLanguage = ($PMF_LANG['metaLanguage'] != 'ja') ? 'uni' : $PMF_LANG['metaLanguage'];
if (function_exists('mb_language') && in_array($mbLanguage, $validMbStrings)) {
mb_language($mbLanguage);
mb_internal_encoding('utf-8');
}
//
// Get user action
//
$action = Filter::filterInput(INPUT_GET, 'action', FILTER_UNSAFE_RAW);
if (is_null($action)) {
$action = Filter::filterInput(INPUT_POST, 'action', FILTER_UNSAFE_RAW);
}
if (!is_null($action)) {
$action = Strings::htmlentities($action);
}
//
// Get CSRF Token
//
$csrfToken = Filter::filterInput(INPUT_GET, 'csrf', FILTER_UNSAFE_RAW);
if (!isset($_SESSION['phpmyfaq_csrf_token']) || $_SESSION['phpmyfaq_csrf_token'] !== $csrfToken) {
$csrfChecked = false;
} else {
$csrfChecked = true;
}
//
// Get possible redirect action
//
$redirectAction = Filter::filterInput(INPUT_POST, 'redirect-action', FILTER_UNSAFE_RAW);
if (is_null($action) && '' !== $redirectAction && 'logout' !== $redirectAction) {
$action = $redirectAction;
}
// authenticate current user
$auth = null;
$error = '';
$faqusername = Filter::filterInput(INPUT_POST, 'faqusername', FILTER_UNSAFE_RAW);
$faqpassword = Filter::filterInput(INPUT_POST, 'faqpassword', FILTER_UNSAFE_RAW, FILTER_FLAG_NO_ENCODE_QUOTES);
$faqremember = Filter::filterInput(INPUT_POST, 'faqrememberme', FILTER_UNSAFE_RAW);
// Set username via SSO
if ($faqConfig->get('security.ssoSupport') && isset($_SERVER['REMOTE_USER'])) {
$faqusername = trim($_SERVER['REMOTE_USER']);
$faqpassword = '';
}
// Login via local DB or LDAP or SSO
if (!is_null($faqusername) && !is_null($faqpassword)) {
$user = new CurrentUser($faqConfig);
if (!is_null($faqremember) && 'rememberMe' === $faqremember) {
$user->enableRememberMe();
}
if ($faqConfig->isLdapActive() && function_exists('ldap_connect')) {
try {
$authLdap = new AuthLdap($faqConfig);
$user->addAuth($authLdap, 'ldap');
} catch (Exception $e) {
$error = $e->getMessage() . '<br>';
}
}
if ($faqConfig->get('security.ssoSupport')) {
$authSso = new AuthSso($faqConfig);
$user->addAuth($authSso, 'sso');
}
if ($user->login($faqusername, $faqpassword)) {
// login, if user account is NOT blocked
if ($user->getStatus() != 'blocked') {
$auth = true;
} else {
$error = $error . $PMF_LANG['ad_auth_fail'];
}
} else {
// error
$logging = new Logging($faqConfig);
$logging->logAdmin($user, 'Loginerror\nLogin: ' . $faqusername . '\nErrors: ' . implode(', ', $user->errors));
$error = $error . $PMF_LANG['ad_auth_fail'];
}
} else {
// Try to authenticate with cookie information
$user = CurrentUser::getFromCookie($faqConfig);
// authenticate with session information
if (!$user instanceof CurrentUser) {
$user = CurrentUser::getFromSession($faqConfig);
}
if ($user instanceof CurrentUser) {
$auth = true;
} else {
$user = new CurrentUser($faqConfig);
}
}
// logout
if ($csrfChecked && $action === 'logout' && $auth) {
$user->deleteFromSession(true);
$auth = null;
$ssoLogout = $faqConfig->get('security.ssoLogoutRedirect');
if ($faqConfig->get('security.ssoSupport') && !empty($ssoLogout)) {
$http->redirect($ssoLogout);
}
}
//
// Get current admin user and group id - default: -1
//
if (isset($user) && is_object($user)) {
$currentAdminUser = $user->getUserId();
if ($user->perm instanceof MediumPermission) {
$currentAdminGroups = $user->perm->getUserGroups($currentAdminUser);
} else {
$currentAdminGroups = [-1];
}
if (0 === count($currentAdminGroups)) {
$currentAdminGroups = [-1];
}
}
//
// Get action from _GET and _POST first
$ajax = Filter::filterInput(INPUT_GET, 'ajax', FILTER_UNSAFE_RAW);
if (is_null($ajax)) {
$ajax = Filter::filterInput(INPUT_POST, 'ajax', FILTER_UNSAFE_RAW);
}
// if performing AJAX operation, needs to branch before header.php
if (isset($auth) && (count($user->perm->getAllUserRights($user->getUserId())) > 0 || $user->isSuperAdmin())) {
if (isset($action) && isset($ajax)) {
if ('ajax' === $action) {
switch ($ajax) {
// Attachments
case 'att':
require 'ajax.attachment.php';
break;
// Dashboard
case 'dashboard':
require 'ajax.dashboard.php';
break;
// Link verification
case 'verifyURL':
require 'ajax.verifyurl.php';
break;
case 'onDemandURL':
require 'ajax.ondemandurl.php';
break;
// Categories
case 'categories':
require 'ajax.category.php';
break;
// Configuration management
case 'config_list':
require 'ajax.config_list.php';
break;
case 'config':
require 'ajax.config.php';
break;
case 'elasticsearch':
require 'ajax.elasticsearch.php';
break;
// Tags management
case 'tags':
require 'ajax.tags.php';
break;
// Comments
case 'comment':
require 'ajax.comment.php';
break;
// Records
case 'records':
require 'ajax.records.php';
break;
case 'recordSave':
require 'record.save.php';
break;
case 'recordAdd':
require 'record.add.php';
break;
case 'markdown':
require 'ajax.markdown.php';
break;
// Search
case 'search':
require 'ajax.search.php';
break;
// Users
case 'user':
require 'ajax.user.php';
break;
// Groups
case 'group':
require 'ajax.group.php';
break;
// Sections
case 'section':
require 'ajax.section.php';
break;
// Interface translation
case 'trans':
require 'ajax.trans.php';
break;
// Image upload
case 'image':
require 'ajax.image.php';
break;
}
exit();
}
}
}
// are we running a PMF export file request?
switch ($action) {
case 'exportfile':
require 'export.file.php';
exit();
break;
case 'reportexport':
require 'report.export.php';
exit();
break;
}
// Header of the admin page including the navigation
require 'header.php';
$numRights = count($user->perm->getAllUserRights($user->getUserId()));
// User is authenticated
if (isset($auth) && ($numRights > 0 || $user->isSuperAdmin())) {
if (!is_null($action)) {
// the various sections of the admin area
switch ($action) {
// functions for user administration
case 'user':
require 'user.php';
break;
case 'group':
require 'group.php';
break;
case 'section':
require 'section.php';
break;
// functions for content administration
case 'faqs-overview':
require 'faqs.overview.php';
break;
case 'viewinactive':
case 'viewactive':
case 'view':
require 'record.show.php';
break;
case 'searchfaqs':
require 'record.search.php';
break;
case 'takequestion':
case 'editentry':
case 'copyentry':
case 'editpreview':
require 'record.edit.php';
break;
case 'insertentry':
require 'record.add.php';
break;
case 'saveentry':
require 'record.save.php';
break;
case 'delatt':
require 'record.delatt.php';
break;
case 'question':
require 'record.questions.php';
break;
case 'comments':
require 'record.comments.php';
break;
// functions for tags
case 'tags':
case 'delete-tag':
require 'tags.php';
break;
// news administration
case 'news':
case 'add-news':
case 'edit-news':
case 'save-news':
case 'update-news':
case 'delete-news':
require 'news.php';
break;
// category administration
case 'content':
case 'category':
case 'savecategory':
case 'updatecategory':
case 'checkIfCategoryExists':
case 'removecategory':
case 'changecategory':
case 'pastecategory':
require 'category.main.php';
break;
case 'addcategory':
require 'category.add.php';
break;
case 'editcategory':
require 'category.edit.php';
break;
case 'translatecategory':
require 'category.translate.php';
break;
case 'deletecategory':
require 'category.delete.php';
break;
case 'cutcategory':
require 'category.cut.php';
break;
case 'movecategory':
require 'category.move.php';
break;
case 'showcategory':
require 'category.showstructure.php';
break;
// glossary
case 'glossary':
case 'saveglossary':
case 'updateglossary':
case 'deleteglossary':
require 'glossary.main.php';
break;
case 'addglossary':
require 'glossary.add.php';
break;
case 'editglossary':
require 'glossary.edit.php';
break;
// functions for password administration
case 'passwd':
require 'pwd.change.php';
break;
// functions for session administration
case 'adminlog':
case 'deleteadminlog':
require 'stat.adminlog.php';
break;
case 'viewsessions':
case 'clear-visits':
require 'stat.main.php';
break;
case 'sessionbrowse':
require 'stat.browser.php';
break;
case 'viewsession':
require 'statistics.show.php';
break;
case 'clear-statistics':
case 'statistics':
require 'stat.ratings.php';
break;
case 'truncatesearchterms':
case 'searchstats':
require 'stat.search.php';
break;
// Reports
case 'reports':
require 'report.main.php';
break;
case 'reportview':
require 'report.view.php';
break;
// Config administration
case 'config':
require 'configuration.php';
break;
case 'system':
require 'system.php';
break;
case 'updateinstance':
case 'instances':
require 'instances.php';
break;
case 'editinstance':
require 'instances.edit.php';
break;
case 'stopwordsconfig':
require 'stopwords.php';
break;
case 'elasticsearch':
require 'elasticsearch.php';
break;
case 'meta':
case 'meta.update';
require 'meta.php';
break;
case 'meta.edit':
require 'meta.edit.php';
break;
// functions for backup administration
case 'backup':
require 'backup.main.php';
break;
case 'restore':
require 'backup.import.php';
break;
// functions for FAQ export
case 'export':
require 'export.main.php';
break;
// attachment administration
case 'attachments':
require 'attachments.php';
break;
default:
echo 'Dave, this conversation can serve no purpose anymore. Goodbye.';
break;
}
} else {
require 'dashboard.php';
}
// User is authenticated, but has no rights
} elseif (isset($auth) && $numRights === 0) {
require 'noperm.php';
// User is NOT authenticated
} else {
require 'loginform.php';
}
require 'footer.php';
$faqConfig->getDb()->close();
|
<?php
/**
* The main admin backend index file.
*
* 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 phpMyFAQ
* @author Thorsten Rinne <thorsten@phpmyfaq.de>
* @author Bastian Poettner <bastian@poettner.net>
* @author Meikel Katzengreis <meikel@katzengreis.com>
* @author Minoru TODA <todam@netjapan.co.jp>
* @author Matteo Scaramuccia <matteo@phpmyfaq.de>
* @copyright 2002-2022 phpMyFAQ Team
* @license http://www.mozilla.org/MPL/2.0/ Mozilla Public License Version 2.0
* @link https://www.phpmyfaq.de
* @since 2002-09-16
*/
use phpMyFAQ\Attachment\AttachmentFactory;
use phpMyFAQ\Auth\AuthLdap;
use phpMyFAQ\Auth\AuthSso;
use phpMyFAQ\Faq;
use phpMyFAQ\Filter;
use phpMyFAQ\Helper\HttpHelper;
use phpMyFAQ\Language;
use phpMyFAQ\Language\Plurals;
use phpMyFAQ\Logging;
use phpMyFAQ\Permission\MediumPermission;
use phpMyFAQ\Strings;
use phpMyFAQ\System;
use phpMyFAQ\Template;
use phpMyFAQ\User\CurrentUser;
define('PMF_ROOT_DIR', dirname(__DIR__));
//
// Define the named constant used as a check by any included PHP file
//
const IS_VALID_PHPMYFAQ = null;
//
// Bootstrapping
//
require PMF_ROOT_DIR . '/src/Bootstrap.php';
// get language (default: english)
$Language = new Language($faqConfig);
$faqLangCode = $Language->setLanguage($faqConfig->get('main.languageDetection'), $faqConfig->get('main.language'));
// Preload English strings
require PMF_ROOT_DIR . '/lang/language_en.php';
$faqConfig->setLanguage($Language);
if (isset($faqLangCode) && Language::isASupportedLanguage($faqLangCode)) {
// Overwrite English strings with the ones we have in the current language
if (!file_exists(PMF_ROOT_DIR . '/lang/language_' . $faqLangCode . '.php')) {
$faqLangCode = 'en';
}
require PMF_ROOT_DIR . '/lang/language_' . $faqLangCode . '.php';
} else {
$faqLangCode = 'en';
}
//
// Load plurals support for selected language
//
$plr = new Plurals($PMF_LANG);
//
// Initializing static string wrapper
//
Strings::init($faqLangCode);
//
// Set actual template set name
//
Template::setTplSetName($faqConfig->get('main.templateSet'));
//
// Initialize attachment factory
//
AttachmentFactory::init(
$faqConfig->get('records.attachmentsStorageType'),
$faqConfig->get('records.defaultAttachmentEncKey'),
$faqConfig->get('records.enableAttachmentEncryption')
);
//
// Create a new phpMyFAQ system object
//
$faqSystem = new System();
//
// Create a new HTTP Helper
//
$http = new HttpHelper();
//
// Create a new FAQ object
//
$faq = new Faq($faqConfig);
//
// use mbstring extension if available and when possible
//
$validMbStrings = array('ja', 'en', 'uni');
$mbLanguage = ($PMF_LANG['metaLanguage'] != 'ja') ? 'uni' : $PMF_LANG['metaLanguage'];
if (function_exists('mb_language') && in_array($mbLanguage, $validMbStrings)) {
mb_language($mbLanguage);
mb_internal_encoding('utf-8');
}
//
// Get user action
//
$action = Filter::filterInput(INPUT_GET, 'action', FILTER_UNSAFE_RAW);
if (is_null($action)) {
$action = Filter::filterInput(INPUT_POST, 'action', FILTER_UNSAFE_RAW);
}
if (!is_null($action)) {
$action = Strings::htmlentities($action);
}
//
// Get CSRF Token
//
$csrfToken = Filter::filterInput(INPUT_GET, 'csrf', FILTER_UNSAFE_RAW);
if (!isset($_SESSION['phpmyfaq_csrf_token']) || $_SESSION['phpmyfaq_csrf_token'] !== $csrfToken) {
$csrfChecked = false;
} else {
$csrfChecked = true;
}
//
// Get possible redirect action
//
$redirectAction = Filter::filterInput(INPUT_POST, 'redirect-action', FILTER_SANITIZE_SPECIAL_CHARS);
if (is_null($action) && '' !== $redirectAction && 'logout' !== $redirectAction) {
$action = $redirectAction;
}
// authenticate current user
$auth = null;
$error = '';
$faqusername = Filter::filterInput(INPUT_POST, 'faqusername', FILTER_UNSAFE_RAW);
$faqpassword = Filter::filterInput(INPUT_POST, 'faqpassword', FILTER_UNSAFE_RAW, FILTER_FLAG_NO_ENCODE_QUOTES);
$faqremember = Filter::filterInput(INPUT_POST, 'faqrememberme', FILTER_UNSAFE_RAW);
// Set username via SSO
if ($faqConfig->get('security.ssoSupport') && isset($_SERVER['REMOTE_USER'])) {
$faqusername = trim($_SERVER['REMOTE_USER']);
$faqpassword = '';
}
// Login via local DB or LDAP or SSO
if (!is_null($faqusername) && !is_null($faqpassword)) {
$user = new CurrentUser($faqConfig);
if (!is_null($faqremember) && 'rememberMe' === $faqremember) {
$user->enableRememberMe();
}
if ($faqConfig->isLdapActive() && function_exists('ldap_connect')) {
try {
$authLdap = new AuthLdap($faqConfig);
$user->addAuth($authLdap, 'ldap');
} catch (Exception $e) {
$error = $e->getMessage() . '<br>';
}
}
if ($faqConfig->get('security.ssoSupport')) {
$authSso = new AuthSso($faqConfig);
$user->addAuth($authSso, 'sso');
}
if ($user->login($faqusername, $faqpassword)) {
// login, if user account is NOT blocked
if ($user->getStatus() != 'blocked') {
$auth = true;
} else {
$error = $error . $PMF_LANG['ad_auth_fail'];
}
} else {
// error
$logging = new Logging($faqConfig);
$logging->logAdmin($user, 'Loginerror\nLogin: ' . $faqusername . '\nErrors: ' . implode(', ', $user->errors));
$error = $error . $PMF_LANG['ad_auth_fail'];
}
} else {
// Try to authenticate with cookie information
$user = CurrentUser::getFromCookie($faqConfig);
// authenticate with session information
if (!$user instanceof CurrentUser) {
$user = CurrentUser::getFromSession($faqConfig);
}
if ($user instanceof CurrentUser) {
$auth = true;
} else {
$user = new CurrentUser($faqConfig);
}
}
// logout
if ($csrfChecked && $action === 'logout' && $auth) {
$user->deleteFromSession(true);
$auth = null;
$ssoLogout = $faqConfig->get('security.ssoLogoutRedirect');
if ($faqConfig->get('security.ssoSupport') && !empty($ssoLogout)) {
$http->redirect($ssoLogout);
}
}
//
// Get current admin user and group id - default: -1
//
if (isset($user) && is_object($user)) {
$currentAdminUser = $user->getUserId();
if ($user->perm instanceof MediumPermission) {
$currentAdminGroups = $user->perm->getUserGroups($currentAdminUser);
} else {
$currentAdminGroups = [-1];
}
if (0 === count($currentAdminGroups)) {
$currentAdminGroups = [-1];
}
}
//
// Get action from _GET and _POST first
$ajax = Filter::filterInput(INPUT_GET, 'ajax', FILTER_UNSAFE_RAW);
if (is_null($ajax)) {
$ajax = Filter::filterInput(INPUT_POST, 'ajax', FILTER_UNSAFE_RAW);
}
// if performing AJAX operation, needs to branch before header.php
if (isset($auth) && (count($user->perm->getAllUserRights($user->getUserId())) > 0 || $user->isSuperAdmin())) {
if (isset($action) && isset($ajax)) {
if ('ajax' === $action) {
switch ($ajax) {
// Attachments
case 'att':
require 'ajax.attachment.php';
break;
// Dashboard
case 'dashboard':
require 'ajax.dashboard.php';
break;
// Link verification
case 'verifyURL':
require 'ajax.verifyurl.php';
break;
case 'onDemandURL':
require 'ajax.ondemandurl.php';
break;
// Categories
case 'categories':
require 'ajax.category.php';
break;
// Configuration management
case 'config_list':
require 'ajax.config_list.php';
break;
case 'config':
require 'ajax.config.php';
break;
case 'elasticsearch':
require 'ajax.elasticsearch.php';
break;
// Tags management
case 'tags':
require 'ajax.tags.php';
break;
// Comments
case 'comment':
require 'ajax.comment.php';
break;
// Records
case 'records':
require 'ajax.records.php';
break;
case 'recordSave':
require 'record.save.php';
break;
case 'recordAdd':
require 'record.add.php';
break;
case 'markdown':
require 'ajax.markdown.php';
break;
// Search
case 'search':
require 'ajax.search.php';
break;
// Users
case 'user':
require 'ajax.user.php';
break;
// Groups
case 'group':
require 'ajax.group.php';
break;
// Sections
case 'section':
require 'ajax.section.php';
break;
// Interface translation
case 'trans':
require 'ajax.trans.php';
break;
// Image upload
case 'image':
require 'ajax.image.php';
break;
}
exit();
}
}
}
// are we running a PMF export file request?
switch ($action) {
case 'exportfile':
require 'export.file.php';
exit();
break;
case 'reportexport':
require 'report.export.php';
exit();
break;
}
// Header of the admin page including the navigation
require 'header.php';
$numRights = count($user->perm->getAllUserRights($user->getUserId()));
// User is authenticated
if (isset($auth) && ($numRights > 0 || $user->isSuperAdmin())) {
if (!is_null($action)) {
// the various sections of the admin area
switch ($action) {
// functions for user administration
case 'user':
require 'user.php';
break;
case 'group':
require 'group.php';
break;
case 'section':
require 'section.php';
break;
// functions for content administration
case 'faqs-overview':
require 'faqs.overview.php';
break;
case 'viewinactive':
case 'viewactive':
case 'view':
require 'record.show.php';
break;
case 'searchfaqs':
require 'record.search.php';
break;
case 'takequestion':
case 'editentry':
case 'copyentry':
case 'editpreview':
require 'record.edit.php';
break;
case 'insertentry':
require 'record.add.php';
break;
case 'saveentry':
require 'record.save.php';
break;
case 'delatt':
require 'record.delatt.php';
break;
case 'question':
require 'record.questions.php';
break;
case 'comments':
require 'record.comments.php';
break;
// functions for tags
case 'tags':
case 'delete-tag':
require 'tags.php';
break;
// news administration
case 'news':
case 'add-news':
case 'edit-news':
case 'save-news':
case 'update-news':
case 'delete-news':
require 'news.php';
break;
// category administration
case 'content':
case 'category':
case 'savecategory':
case 'updatecategory':
case 'checkIfCategoryExists':
case 'removecategory':
case 'changecategory':
case 'pastecategory':
require 'category.main.php';
break;
case 'addcategory':
require 'category.add.php';
break;
case 'editcategory':
require 'category.edit.php';
break;
case 'translatecategory':
require 'category.translate.php';
break;
case 'deletecategory':
require 'category.delete.php';
break;
case 'cutcategory':
require 'category.cut.php';
break;
case 'movecategory':
require 'category.move.php';
break;
case 'showcategory':
require 'category.showstructure.php';
break;
// glossary
case 'glossary':
case 'saveglossary':
case 'updateglossary':
case 'deleteglossary':
require 'glossary.main.php';
break;
case 'addglossary':
require 'glossary.add.php';
break;
case 'editglossary':
require 'glossary.edit.php';
break;
// functions for password administration
case 'passwd':
require 'pwd.change.php';
break;
// functions for session administration
case 'adminlog':
case 'deleteadminlog':
require 'stat.adminlog.php';
break;
case 'viewsessions':
case 'clear-visits':
require 'stat.main.php';
break;
case 'sessionbrowse':
require 'stat.browser.php';
break;
case 'viewsession':
require 'statistics.show.php';
break;
case 'clear-statistics':
case 'statistics':
require 'stat.ratings.php';
break;
case 'truncatesearchterms':
case 'searchstats':
require 'stat.search.php';
break;
// Reports
case 'reports':
require 'report.main.php';
break;
case 'reportview':
require 'report.view.php';
break;
// Config administration
case 'config':
require 'configuration.php';
break;
case 'system':
require 'system.php';
break;
case 'updateinstance':
case 'instances':
require 'instances.php';
break;
case 'editinstance':
require 'instances.edit.php';
break;
case 'stopwordsconfig':
require 'stopwords.php';
break;
case 'elasticsearch':
require 'elasticsearch.php';
break;
case 'meta':
case 'meta.update';
require 'meta.php';
break;
case 'meta.edit':
require 'meta.edit.php';
break;
// functions for backup administration
case 'backup':
require 'backup.main.php';
break;
case 'restore':
require 'backup.import.php';
break;
// functions for FAQ export
case 'export':
require 'export.main.php';
break;
// attachment administration
case 'attachments':
require 'attachments.php';
break;
default:
echo 'Dave, this conversation can serve no purpose anymore. Goodbye.';
break;
}
} else {
require 'dashboard.php';
}
// User is authenticated, but has no rights
} elseif (isset($auth) && $numRights === 0) {
require 'noperm.php';
// User is NOT authenticated
} else {
require 'loginform.php';
}
require 'footer.php';
$faqConfig->getDb()->close();
|
3872e7eac2ddeac182fc1335cc312d1392d56f98
|
https://github.com/thorsten/phpmyfaq
|
part.choosecalendar.rowfields.php
|
php
|
<?php
echo '<td width="20px"><input id="active_' . $_['calendar']['id'] . '" type="checkbox" onClick="Calendar.UI.Calendar.activation(this,' . $_['calendar']['id'] . ')"' . ($_['calendar']['active'] ? ' checked="checked"' : '') . '></td>';
echo '<td id="' . OCP\USER::getUser() . '_' . $_['calendar']['id'] . '"><label for="active_' . $_['calendar']['id'] . '">' . htmlspecialchars($_['calendar']['displayname']) . '</label></td>';
echo '<td width="20px"><a href="#" onclick="Calendar.UI.Share.dropdown(\'' . OCP\USER::getUser() . '\', \'' . $_['calendar']['id'] . '\');" title="' . $l->t("Share Calendar") . '" class="action"><img class="svg action" src="' . ((!$_['shared']) ? OCP\Util::imagePath('core', 'actions/share.svg') : OCP\Util::imagePath('core', 'actions/shared.svg')) . '"></a></td>';
echo '<td width="20px"><a href="#" onclick="Calendar.UI.showCalDAVUrl(\'' . OCP\USER::getUser() . '\', \'' . $_['calendar']['uri'] . '\');" title="' . $l->t("CalDav Link") . '" class="action"><img class="svg action" src="'.OCP\Util::imagePath('core', 'actions/public.svg').'"></a></td>';
echo '<td width="20px"><a href="?app=calendar&getfile=export.php?calid=' . $_['calendar']['id'] . '" title="' . $l->t('Download') . '" class="action"><img class="svg action" src="'.OCP\Util::imagePath('core', 'actions/download.svg').'"></a></td>';
echo '<td width="20px"><a href="#" title="' . $l->t('Edit') . '" class="action" onclick="Calendar.UI.Calendar.edit(this, ' . $_['calendar']['id'] . ');"><img class="svg action" src="'.OCP\Util::imagePath('core', 'actions/rename.svg').'"></a></td>';
echo '<td width="20px"><a href="#" onclick="Calendar.UI.Calendar.deleteCalendar(\'' . $_['calendar']['id'] . '\');" title="' . $l->t('Delete') . '" class="action"><img class="svg action" src="'.OCP\Util::imagePath('core', 'actions/delete.svg').'"></a></td>';
|
<?php
echo '<td width="20px"><input id="active_' . $_['calendar']['id'] . '" type="checkbox" onClick="Calendar.UI.Calendar.activation(this,' . $_['calendar']['id'] . ')"' . ($_['calendar']['active'] ? ' checked="checked"' : '') . '></td>';
echo '<td id="' . OCP\USER::getUser() . '_' . $_['calendar']['id'] . '"><label for="active_' . $_['calendar']['id'] . '">' . htmlspecialchars($_['calendar']['displayname']) . '</label></td>';
echo '<td width="20px"><a href="#" onclick="Calendar.UI.Share.dropdown(\'' . OCP\USER::getUser() . '\', \'' . $_['calendar']['id'] . '\');" title="' . $l->t("Share Calendar") . '" class="action"><img class="svg action" src="' . ((!$_['shared']) ? OCP\Util::imagePath('core', 'actions/share.svg') : OCP\Util::imagePath('core', 'actions/shared.svg')) . '"></a></td>';
echo '<td width="20px"><a href="#" onclick="Calendar.UI.showCalDAVUrl(\'' . OCP\USER::getUser() . '\', \'' . htmlentities($_['calendar']['uri']) . '\');" title="' . $l->t("CalDav Link") . '" class="action"><img class="svg action" src="'.OCP\Util::imagePath('core', 'actions/public.svg').'"></a></td>';
echo '<td width="20px"><a href="?app=calendar&getfile=export.php?calid=' . $_['calendar']['id'] . '" title="' . $l->t('Download') . '" class="action"><img class="svg action" src="'.OCP\Util::imagePath('core', 'actions/download.svg').'"></a></td>';
echo '<td width="20px"><a href="#" title="' . $l->t('Edit') . '" class="action" onclick="Calendar.UI.Calendar.edit(this, ' . $_['calendar']['id'] . ');"><img class="svg action" src="'.OCP\Util::imagePath('core', 'actions/rename.svg').'"></a></td>';
echo '<td width="20px"><a href="#" onclick="Calendar.UI.Calendar.deleteCalendar(\'' . $_['calendar']['id'] . '\');" title="' . $l->t('Delete') . '" class="action"><img class="svg action" src="'.OCP\Util::imagePath('core', 'actions/delete.svg').'"></a></td>';
|
f955f6a6857754826af8903475688ba54f72c1bb
|
https://github.com/owncloud/core
|
iTermAdvancedSettingsModel.m
|
objective-c
|
//
// iTermAdvancedSettingsModel.m
// iTerm
//
// Created by George Nachman on 3/18/14.
//
//
#import "iTermAdvancedSettingsModel.h"
#import "iTermAdvancedSettingsViewController.h"
#import "NSStringITerm.h"
@implementation iTermAdvancedSettingsModel
#define DEFINE_BOOL(name, theDefault, theDescription) \
+ (BOOL)name { \
NSString *theIdentifier = [@#name stringByCapitalizingFirstLetter]; \
return [iTermAdvancedSettingsViewController boolForIdentifier:theIdentifier \
defaultValue:theDefault \
description:theDescription]; \
} \
+ (NSString *)name##UserDefaultsKey { \
NSString *theIdentifier = [@#name stringByCapitalizingFirstLetter]; \
return theIdentifier; \
}
#define DEFINE_SETTABLE_BOOL(name, capitalizedName, theDefault, theDescription) \
DEFINE_BOOL(name, theDefault, theDescription) \
+ (void)set##capitalizedName :(BOOL)newValue { \
[[NSUserDefaults standardUserDefaults] setBool:newValue forKey:@#capitalizedName]; \
[[NSNotificationCenter defaultCenter] postNotificationName:iTermAdvancedSettingsDidChange \
object:nil]; \
}
#define DEFINE_OPTIONAL_BOOL(name, theDefault, theDescription) \
+ (BOOL *)name { \
NSString *theIdentifier = [@#name stringByCapitalizingFirstLetter]; \
return [iTermAdvancedSettingsViewController optionalBoolForIdentifier:theIdentifier \
defaultValue:theDefault \
description:theDescription]; \
} \
+ (NSString *)name##UserDefaultsKey { \
NSString *theIdentifier = [@#name stringByCapitalizingFirstLetter]; \
return theIdentifier; \
}
#define DEFINE_INT(name, theDefault, theDescription) \
+ (int)name { \
NSString *theIdentifier = [@#name stringByCapitalizingFirstLetter]; \
return [iTermAdvancedSettingsViewController intForIdentifier:theIdentifier \
defaultValue:theDefault \
description:theDescription]; \
}
#define DEFINE_FLOAT(name, theDefault, theDescription) \
+ (double)name { \
NSString *theIdentifier = [@#name stringByCapitalizingFirstLetter]; \
return [iTermAdvancedSettingsViewController floatForIdentifier:theIdentifier \
defaultValue:theDefault \
description:theDescription]; \
}
#define DEFINE_SETTABLE_FLOAT(name, capitalizedName, theDefault, theDescription) \
DEFINE_FLOAT(name, theDefault, theDescription) \
+ (void)set##capitalizedName :(double)newValue { \
[[NSUserDefaults standardUserDefaults] setDouble:newValue forKey:@#capitalizedName]; \
[[NSNotificationCenter defaultCenter] postNotificationName:iTermAdvancedSettingsDidChange \
object:nil]; \
}
#define DEFINE_STRING(name, theDefault, theDescription) \
+ (NSString *)name { \
NSString *theIdentifier = [@#name stringByCapitalizingFirstLetter]; \
return [iTermAdvancedSettingsViewController stringForIdentifier:theIdentifier \
defaultValue:theDefault \
description:theDescription]; \
}
#pragma mark Tabs
DEFINE_BOOL(useUnevenTabs, NO, @"Tabs: Uneven tab widths allowed.");
DEFINE_INT(minTabWidth, 75, @"Tabs: Minimum tab width when using uneven tab widths.");
DEFINE_INT(minCompactTabWidth, 60, @"Tabs: Minimum tab width when using uneven tab widths for compact tabs.");
DEFINE_INT(optimumTabWidth, 175, @"Tabs: Preferred tab width when tabs are equally sized.");
DEFINE_BOOL(addNewTabAtEndOfTabs, YES, @"Tabs: Add new tabs at the end of the tab bar, not next to current tab.");
DEFINE_BOOL(navigatePanesInReadingOrder, YES, @"Tabs: Next Pane and Previous Pane commands use reading order, not the time of last use.");
DEFINE_BOOL(eliminateCloseButtons, NO, @"Tabs: Eliminate close buttons from tabs, even on mouse-over.");
DEFINE_FLOAT(tabAutoShowHoldTime, 1.0, @"Tabs: How long in seconds to show tabs in fullscreen.\nThe tab bar appears briefly in fullscreen when the number of tabs changes or you switch tabs. This setting gives the time in seconds for it to remain visible.");
DEFINE_FLOAT(tabFlashAnimationDuration, 0.25, @"Tabs: Animation duration for fade in/out animation of tabs in full screen, in seconds.")
DEFINE_BOOL(allowDragOfTabIntoNewWindow, YES, @"Tabs: Allow a tab to be dragged and dropped outside any existing tab bar to create a new window.");
DEFINE_INT(minimumTabDragDistance, 10, @"Tabs: How far must the mouse move before a tab drag is initiated?\nYou must restart iTerm2 after changing this setting for it to take effect.");
#pragma mark Mouse
DEFINE_STRING(alternateMouseScrollStringForUp, @"",
@"Mouse: Scroll wheel up sends the specified text when in alternate screen mode.\n"
@"The value should use Vim syntax, such as \\e for escape.");
DEFINE_STRING(alternateMouseScrollStringForDown, @"",
@"Mouse: Scroll wheel down sends the specified text when in alternate screen mode.\n"
@"The value should use Vim syntax, such as \\e for escape.");
DEFINE_BOOL(alternateMouseScroll, NO, @"Mouse: Scroll wheel sends arrow keys when in alternate screen mode.");
DEFINE_BOOL(pinchToChangeFontSizeDisabled, NO, @"Mouse: Disable changing font size in response to a pinch gesture.");
DEFINE_BOOL(useSystemCursorWhenPossible, NO, @"Mouse: Use system cursor icons when possible.");
DEFINE_BOOL(alwaysAcceptFirstMouse, NO, @"Mouse: Always accept first mouse event on terminal windows.\nThis means clicks will work the same when iTerm2 is active as when it’s inactive.");
DEFINE_BOOL(doubleReportScrollWheel, NO, @"Mouse: Double-report scroll wheel events to work around tmux scrolling bug.");
DEFINE_BOOL(stealKeyFocus, NO, @"Mouse: When Focus Follows Mouse is enabled, steal key focus even when inactive.");
DEFINE_BOOL(cmdClickWhenInactiveInvokesSemanticHistory, NO, @"Mouse: ⌘-click in an active pane while iTerm2 isn't the active app invokes Semantic History.\nBy default, iTerm2 respects the OS standard that ⌘-click in an app that doesn't have keyboard focus behaves like a non-⌘ click that does not raise the window.");
#pragma mark Terminal
DEFINE_BOOL(traditionalVisualBell, NO, @"Terminal: Visual bell flashes the whole screen, not just a bell icon.");
DEFINE_FLOAT(timeBetweenBlinks, 0.5, @"Terminal: Cursor blink speed (seconds).");
DEFINE_BOOL(doNotSetCtype, NO, @"Terminal: Never set the CTYPE environment variable.");
// For these, 1 is more aggressive and 0 turns the feature off:
DEFINE_FLOAT(smartCursorColorBgThreshold, 0.5, @"Terminal: Threshold for Smart Cursor Color for background color (0 to 1).\n0 means the cursor’s background color will always be the cell’s text color, while 1 means it will always be black or white.");
DEFINE_FLOAT(smartCursorColorFgThreshold, 0.75, @"Terminal: Threshold for Smart Cursor Color for text color (0 to 1).\n0 means the cursor’s text color will always be the cell’s background color, while 1 means it will always be black or white.");
DEFINE_STRING(findUrlsRegex,
@"https?://([a-z0-9A-Z]+(:[a-zA-Z0-9]+)?@)?[a-z0-9A-Z\\-]+(\\.[a-z0-9A-Z\\-]+)*"
@"((:[0-9]+)?)(/[a-zA-Z0-9;:/\\.\\-_+%~?&@=#\\(\\)]*)?",
@"Terminal: Regular expression for “Find URLs” command.");
DEFINE_FLOAT(echoProbeDuration, 0.5, @"Terminal: Amount of time to wait while testing if echo is on (seconds).\nThis is used by the password manager to ensure you're at a password prompt.");
DEFINE_BOOL(disablePasswordManagerAnimations, NO, @"Terminal: Disable animations for showing/hiding password manager.");
DEFINE_BOOL(optionIsMetaForSpecialChars, YES, @"Terminal: When you press an arrow key or other function key that transmits the modifiers, should Option be translated to Meta?\nIf this is set to No then it will be translated to Alt.");
DEFINE_BOOL(noSyncSilenceAnnoyingBellAutomatically, NO, @"Terminal: Automatically silence bell when it rings too much.");
DEFINE_BOOL(restoreWindowContents, YES, @"Terminal: Restore window contents at startup.\nThis requires “System Prefs>General>Close windows when quitting an app” to be off.");
DEFINE_INT(numberOfLinesForAccessibility, 1000, @"Terminal: Maximum number of lines of history to expose to Accessibility.\nAccessibility APIs can make iTerm2 slow. In order to limit the effect, you can restrict the number of lines in each session that are visible to accessibility. The last lines of each session will be made accessible.");
DEFINE_INT(triggerRadius, 3, @"Terminal: Number of screen lines to match against trigger regular expressions.\nTrigger regular expressions are matched against the last logical line of text when a newline is received. A search is performed to find the start of the line. Since very long lines would cause performance problems, the search (and consequently the regular expression match, highlighting, and so on) is limited to this many screen lines.");
DEFINE_BOOL(requireCmdForDraggingText, NO, @"Terminal: To drag images or selected text, you must hold ⌘. This prevents accidental drags.");
DEFINE_BOOL(focusReportingEnabled, YES, @"Terminal: Apps may turn on Focus Reporting.\nFocus reporting causes iTerm2 to send an escape sequence when a session gains or loses focus. It can cause problems when an ssh session dies unexpectedly because it gets left on, so some users prefer to disable it.");
DEFINE_BOOL(useColorfgbgFallback, YES, @"Terminal: Use fallback for COLORFGBG if no exact match found?\nThe COLORFGBG variable indicates the ANSI colors that match the foreground and background colors. If no colors match and this setting is enabled, then the variable will be set to 15;0 to indicate a dark background or 0;15 to indicate a light background.");
DEFINE_BOOL(zeroWidthSpaceAdvancesCursor, YES, @"Terminal: Zero-Width Space (U+200B) advances cursor?\nWhile a zero-width space should not advance the cursor per the Unicode spec, both Terminal.app and Konsole do this, and Weechat depends on it. You must restart iTerm2 after changing this setting.");
DEFINE_BOOL(fullHeightCursor, NO, @"Terminal: Cursor occupies line spacing area.\nIf lines have more than 100% vertical spacing and this setting is enabled the bottom of the cursor will be aligned to the bottom of the spacing area.");
DEFINE_FLOAT(underlineCursorOffset, 0, @"Terminal: Vertical offset for underline cursor.\nPositive values move it up, negative values move it down.");
DEFINE_BOOL(preventEscapeSequenceFromClearingHistory, NO, @"Terminal: Prevent CSI 3 J from clearing scrollback history?\nThis is also known as thethe terminfo E3 capability.");
DEFINE_FLOAT(verticalBarCursorWidth, 1, @"Terminal: Width of vertical bar cursor.");
#pragma mark Hotkey
DEFINE_FLOAT(hotkeyTermAnimationDuration, 0.25, @"Hotkey: Duration in seconds of the hotkey window animation.\nWarning: reducing this value may cause problems if you have multiple displays.");
DEFINE_BOOL(dockIconTogglesWindow, NO, @"Hotkey: If the only window is a hotkey window, then clicking the dock icon shows or hides it.");
DEFINE_BOOL(hotkeyWindowFloatsAboveOtherWindows, NO, @"Hotkey: The hotkey window floats above other windows even when another application is active.\nYou must disable “Prefs > Keys > Hotkey window hides when focus is lost” for this setting to be effective.");
DEFINE_FLOAT(hotKeyDoubleTapMaxDelay, 0.3, @"Hotkey: The maximum amount of time allowed between presses of a modifier key when performing a modifier double-tap.");
#pragma mark General
DEFINE_STRING(searchCommand, @"https://google.com/search?q=%@", @"General: Template for URL of search engine.\niTerm2 replaces the string “%@” with the text to search for. Query parameter percent escaping is used.");
DEFINE_INT(autocompleteMaxOptions, 20, @"General: Number of autocomplete options to present.\nA value less than 100 is recommended.");
DEFINE_FLOAT(minRunningTime, 10, @"General: Grace period for automatic quitting after the last window is closed.\nIf iTerm2 is configured to quit automatically when the last window is closed, this setting gives a grace period (in seconds) after startup where that feature is disabled. Set to 0 to have no grace period.");
DEFINE_FLOAT(updateScreenParamsDelay, 1, @"General: Delay after changing number of screens/resolution until refresh (seconds).\nThis works around OS bugs where it takes some time after a screen change before it is safe to resize windows.");
DEFINE_BOOL(disableAppNap, NO, @"General: Disable App Nap.\nChange effective after restarting iTerm2.");
DEFINE_FLOAT(idleTimeSeconds, 2, @"General: Time in seconds before a session is considered idle.\nUsed for updating icons and activity indicator in tabs.");
DEFINE_FLOAT(findDelaySeconds, 1, @"General: Time to wait before performing Find action on 1- or 2- character queries.");
DEFINE_INT(maximumBytesToProvideToServices, 100000, @"General: Maximum number of bytes of selection to provide to Services.\nA large value here can cause performance issues when you have a big selection.");
DEFINE_BOOL(useOpenDirectory, YES, @"General: Use Open Directory to determine the user shell");
DEFINE_BOOL(disablePotentiallyInsecureEscapeSequences, NO, @"General: Disable potentially insecure escape sequences.\nSome features of iTerm2 expand the surface area for security issues. Consider turning this on when viewing untrusted content. The following custom escape sequences will be disabled: RemoteHost, StealFocus, CurrentDir, SetProfile, CopyToClipboard, EndCopy, File, SetBackgroundImageFile. The following DEC sequences are disabled: DECRQCRA. The following xterm extensions are disabled: Window Title Reporting, Icon Title Reporting. This will break displaying inline images, file download, some shell integration features, and other features.");
DEFINE_BOOL(performDictionaryLookupOnQuickLook, YES, @"General: Perform dictionary lookups on force press.\nIf this is NO, force press will still preview the Semantic History action; only dictionary lookups can be disabled.");
DEFINE_BOOL(jiggleTTYSizeOnClearBuffer, NO, @"General: Redraw the screen after the Clear Buffer menu item is selected.\nWhen enabled, the TTY size is briefly changed after clearing the buffer to cause the shell or current app to redraw.");
DEFINE_BOOL(indicateBellsInDockBadgeLabel, YES, @"General: Indicate the number of bells rung while the app is inactive in the dock icon’s badge label");
DEFINE_STRING(downloadsDirectory, @"", @"General: Downloads folder.\nIf set, downloaded files go to this location instead of the user’s $HOME/Downloads folder.");
DEFINE_FLOAT(pointSizeOfTimeStamp, 10, @"General: Point size for timestamps");
DEFINE_INT(terminalMargin, 5, @"General: Width of left and right margins in terminal panes\nHow much space to leave between the left and right edges of the terminal.\nYou must restart iTerm2 after modifying this property. Saved window arrangements should be re-created.");
DEFINE_INT(terminalVMargin, 2, @"General: Height of top and bottom margins in terminal panes\nHow much space to leave between the top and bottom edges of the terminal.\nYou must restart iTerm2 after modifying this property. Saved window arrangements should be re-created.");
DEFINE_BOOL(zippyTextDrawing, YES, @"General: Use zippy text drawing algorithm?\nThis draws non-ASCII text more quickly but with lower fidelity. This setting is ignored if ligatures are enabled in Prefs > Profiles > Text.");
DEFINE_BOOL(lowFiCombiningMarks, NO, @"General: Prefer speed to accuracy for characters with combining marks?");
DEFINE_BOOL(useVirtualKeyCodesForDetectingDigits, YES, @"General: On keyboards that require a modifier to press a digit, do not require that modifier for switching between windows, tabs, and panes by number.\nFor example, AZERTY requires you to hold down Shift to enter a number. To switch tabs with Cmd+Number on an AZERTY keyboard, you must enable this setting. Then, for example, Cmd-& switches to tab 1. When this setting is enabled, some user-defined shortcuts may become unavailable because the tab/window/pane switching behavior takes precedence.");
DEFINE_STRING(viewManPageCommand, @"man %@ || sleep 3", @"General: Command to view man pages.\nUsed when you press the man page button on the touch bar. %@ is replaced with the command. End the command with & to avoid opening an iTerm2 window (e.g., if you're launching an external viewer).");
#pragma mark - Semantic History
DEFINE_BOOL(ignoreHardNewlinesInURLs, NO, @"Semantic History: Ignore hard newlines for the purposes of locating URLs and file names for Semantic History.\nIf a hard newline occurs at the end of a line then cmd-click will not see it all unless this setting is turned on. This is useful for some interactive applications. Turning this on will remove newlines from the \\3 and \\4 substitutions.");
// Note: square brackets are included for ipv6 addresses like http://[2600:3c03::f03c:91ff:fe96:6a7a]/
DEFINE_STRING(URLCharacterSet, @".?\\/:;%=&_-,+~#@!*'(())|[]", @"Semantic History: Non-alphanumeric characters considered part of a URL for Semantic History.\nLetters and numbers are always considered part of the URL. These non-alphanumeric characters are used in addition for the purposes of figuring out where a URL begins and ends.");
DEFINE_INT(maxSemanticHistoryPrefixOrSuffix, 2000, @"Semantic History: Maximum number of bytes of text before and after click location to take into account.\nThis also limits the size of the \\3 and \\4 substitutions.");
DEFINE_STRING(pathsToIgnore, @"", @"Semantic History: Paths to ignore for Semantic History.\nSeparate paths with a comma. Any file under one of these paths will not be openable with Semantic History.");
DEFINE_BOOL(performDNSLookups, YES, @"Semantic History: Perform DNS lookups to check if URLs are valid?\nWhen enabled, the name under the mouse will be resolved with DNS to determine if it is a clickable link.");
#pragma mark - Debugging
DEFINE_BOOL(startDebugLoggingAutomatically, NO, @"Debugging: Start debug logging automatically when iTerm2 is launched.");
DEFINE_BOOL(logDrawingPerformance, NO, @"Debugging: Log stats about text drawing performance to console.\nUsed for performance testing.");
DEFINE_BOOL(logRestorableStateSize, NO, @"Debugging: Log restorable state size info to /tmp/statesize.*.txt.");
#pragma mark - Session
DEFINE_BOOL(runJobsInServers, YES, @"Session: Enable session restoration.\nSession restoration runs jobs in separate processes. They will survive crashes, force quits, and upgrades.\nYou must restart iTerm2 for this change to take effect.");
DEFINE_BOOL(killJobsInServersOnQuit, YES, @"Session: User-initiated Quit (⌘Q) of iTerm2 will kill all running jobs.\nApplies only when session restoration is on.");
DEFINE_SETTABLE_BOOL(suppressRestartAnnouncement, SuppressRestartAnnouncement, NO, @"Session: Suppress the Restart Session offer.\nWhen a sessions terminates, it will offer to restart itself. Turn this on to suppress the offer permanently.");
DEFINE_BOOL(showSessionRestoredBanner, YES, @"Session: When restoring a session without restoring a running job, draw a banner saying “Session Restored” below the restored contents.");
DEFINE_STRING(autoLogFormat,
@"\\(session.creationTimeString).\\(session.name).\\(session.termid).\\(iterm2.pid).\\(session.autoLogId).log",
@"Session: Format for automatic session log filenames.\nSee the Badges documentation for supported substitutions.");
DEFINE_BOOL(focusNewSplitPaneWithFocusFollowsMouse, YES, @"Session: When focus follows mouse is enabled, should new split panes automatically be focused?");
#pragma mark - Window
DEFINE_BOOL(openFileInNewWindows, NO, @"Windows: Open files in new windows, not new tabs.\nThis affects shell scripts opened from Finder, for example.");
DEFINE_BOOL(rememberWindowPositions, YES, @"Windows: Remember window locations even after the windows are closed.\nWhen a new window is opened, one of the recorded locations is used.");
DEFINE_BOOL(disableWindowSizeSnap, NO, @"Windows: Terminal windows resize smoothly.\nDisables snapping to character grid. Holding Control will temporarily disable snap-to-grid.");
DEFINE_BOOL(profilesWindowJoinsActiveSpace, NO, @"Windows: If the Profiles window is open, it always moves to join the active Space.\nYou must restart iTerm2 for a change in this setting to take effect.");
DEFINE_BOOL(darkThemeHasBlackTitlebar, YES, @"Windows: Dark themes give terminal windows black title bars by default.");
DEFINE_BOOL(fontChangeAffectsBroadcastingSessions, NO, @"Windows: Should growing or shrinking the font in a session that's broadcasting input affect all session that broadcast input?\nThis only applies to changing the font size with Make Text Bigger, Make Text Normal Size, and Make Text Smaller");
#pragma mark tmux
DEFINE_BOOL(noSyncNewWindowOrTabFromTmuxOpensTmux, NO, @"Tmux Integration: Suppress alert asking what kind of tab/window to open in tmux integration.");
DEFINE_BOOL(tmuxUsesDedicatedProfile, YES, @"Tmux Integration: Tmux always uses the “tmux” profile.\nIf disabled, tmux sessions use the profile of the session you ran tmux -CC in.");
#pragma mark Warnings
DEFINE_BOOL(neverWarnAboutMeta, NO, @"Warnings: Suppress a warning when Option Key Acts as Meta is enabled in Prefs>Profiles>Keys.");
DEFINE_BOOL(neverWarnAboutSpaces, NO, @"Warnings: Suppress a warning about how to configure Spaces when setting a window's Space.");
DEFINE_BOOL(neverWarnAboutOverrides, NO, @"Warnings: Suppress a warning about a change to a Profile key setting that overrides a global setting.");
DEFINE_BOOL(neverWarnAboutPossibleOverrides, NO, @"Warnings: Suppress a warning about a change to a global key that's overridden by a Profile.");
DEFINE_BOOL(noSyncNeverRemindPrefsChangesLostForUrl, NO, @"Warnings: Suppress changed-setting warning when prefs are loaded from a URL.");
DEFINE_BOOL(noSyncNeverRemindPrefsChangesLostForFile, NO, @"Warnings: Suppress changed-setting warning when prefs are loaded from a custom folder.");
DEFINE_BOOL(noSyncSuppressAnnyoingBellOffer, NO, @"Warnings: Suppress offer to silence bell when it rings too much.");
DEFINE_BOOL(suppressMultilinePasteWarningWhenPastingOneLineWithTerminalNewline, NO, @"Warnings: Suppress warning about multi-line paste when pasting a single line ending with a newline.\nThis supresses all multi-line paste warnings when a single line is being pasted.");
DEFINE_BOOL(suppressMultilinePasteWarningWhenNotAtShellPrompt, NO, @"Warnings: Suppress warning about multi-line paste when not at prompt.\nRequires Shell Integration to be installed.");
DEFINE_BOOL(noSyncSuppressBroadcastInputWarning, NO, @"Warnings: Suppress warning about broadcasting input.");
DEFINE_BOOL(noSyncSuppressCaptureOutputRequiresShellIntegrationWarning, NO,
@"Warnings: Suppress warning “Shell Integration is required for Capture Output.”");
DEFINE_BOOL(noSyncSuppressCaptureOutputToolNotVisibleWarning, NO,
@"Warnings: Suppress warning that the Captured Output tool is not visible.");
DEFINE_BOOL(closingTmuxWindowKillsTmuxWindows, NO, @"Warnings: Suppress kill/hide dialog when closing a tmux window.");
DEFINE_BOOL(closingTmuxTabKillsTmuxWindows, NO, @"Warnings: Suppress kill/hide dialog when closing a tmux tab.");
DEFINE_BOOL(aboutToPasteTabs, NO, @"Warnings: Suppress warning about pasting tabs with offer to convert them to spaces.");
DEFINE_FLOAT(shortLivedSessionDuration, 3, @"Warnings: Warn about short-lived sessions that live less than this many seconds.");
DEFINE_SETTABLE_BOOL(noSyncDoNotWarnBeforeMultilinePaste, NoSyncDoNotWarnBeforeMultilinePaste, NO, @"Warnings: Suppress warning about multi-line pastes (or a single line ending in a newline).\nThis applies whether you are at the shell prompt or not, provided two or more lines are being pasted.");
DEFINE_SETTABLE_BOOL(noSyncDoNotWarnBeforePastingOneLineEndingInNewlineAtShellPrompt, NoSyncDoNotWarnBeforePastingOneLineEndingInNewlineAtShellPrompt, NO, @"Warnings: Suppress warning about pasting a single line ending in a newline when at the shell prompt.\nThis requires Shell Integration to be installed.");
DEFINE_BOOL(noSyncReplaceProfileWarning, NO, @"Warnings: Suppress warning about copying a session's settings over a Profile");
DEFINE_OPTIONAL_BOOL(noSyncTurnOffFocusReportingOnHostChange, nil, @"Warnings: Always turn off focus reporting when host changes?");
DEFINE_OPTIONAL_BOOL(noSyncTurnOffMouseReportingOnHostChange, nil, @"Warnings: Always turn off mouse reporting when host changes?");
DEFINE_OPTIONAL_BOOL(noSyncTurnOffBracketedPasteOnHostChange, nil, @"Warnings: Always turn off paste bracketing when host changes?");
#pragma mark Pasteboard
DEFINE_BOOL(trimWhitespaceOnCopy, YES, @"Pasteboard: Trim whitespace when copying to pasteboard.");
DEFINE_INT(quickPasteBytesPerCall, 667, @"Pasteboard: Number of bytes to paste in each chunk when pasting normally.");
DEFINE_FLOAT(quickPasteDelayBetweenCalls, 0.01530456, @"Pasteboard: Delay in seconds between chunks when pasting normally.")
DEFINE_INT(slowPasteBytesPerCall, 16, @"Pasteboard: Number of bytes to paste in each chunk when pasting slowly.");
DEFINE_FLOAT(slowPasteDelayBetweenCalls, 0.125, @"Pasteboard: Delay in seconds between chunks when pasting slowly");
DEFINE_BOOL(copyWithStylesByDefault, NO, @"Pasteboard: Copy to pasteboard on selection includes color and font style.");
DEFINE_INT(pasteHistoryMaxOptions, 20, @"Pasteboard: Number of entires to save in Paste History.\n.");
DEFINE_BOOL(disallowCopyEmptyString, NO, @"Pasteboard: Disallow copying empty string to pasteboard.\nIf enabled, selecting an empty string (or all whitespace if trimming is enabled) will not erase the contents of the pasteboard.");
DEFINE_BOOL(typingClearsSelection, YES, @"Pasteboard: Pressing a key will remove the selection.");
DEFINE_SETTABLE_BOOL(promptForPasteWhenNotAtPrompt, PromptForPasteWhenNotAtPrompt, NO, @"Pasteboard: Warn before pasting when not at shell prompt?");
DEFINE_SETTABLE_BOOL(noSyncSuppressClipboardAccessDeniedWarning, NoSyncSuppressClipboardAccessDeniedWarning, NO, @"Session: Suppress the notification that the terminal attempted to access the clipboard but it was denied?");
DEFINE_SETTABLE_BOOL(noSyncSuppressMissingProfileInArrangementWarning, NoSyncSuppressMissingProfileInArrangementWarning, NO, @"Session: Suppress the notification that a restored session’s profile no longer exists?");
DEFINE_BOOL(excludeBackgroundColorsFromCopiedStyle, NO, @"Pasteboard: Exclude background colors when text is copied with color and font style?");
#pragma mark - Tip of the day
DEFINE_BOOL(noSyncTipsDisabled, NO, @"Tip of the Day: Disable the Tip of the Day?");
DEFINE_SETTABLE_FLOAT(timeBetweenTips, TimeBetweenTips, 24 * 60 * 60, @"Tip of the Day: Time between tips (in seconds)");
#pragma mark - Badge
DEFINE_STRING(badgeFont, @"Helvetica", @"Badge: Font to use for the badge.");
DEFINE_BOOL(badgeFontIsBold, YES, @"Badge: Should the badge render in bold type?");
DEFINE_FLOAT(badgeMaxWidthFraction, 0.5, @"Badge: Maximum width of the badge\nAs a fraction of the width of the terminal, between 0 and 1.0.");
DEFINE_FLOAT(badgeMaxHeightFraction, 0.2, @"Badge: Maximum height of the badge\nAs a fraction of the height of the terminal, between 0 and 1.0.");
DEFINE_INT(badgeRightMargin, 10, @"Badge: Right Margin for the badge\nHow much space to leave between the right edge of the badge and the right edge of the terminal.");
DEFINE_INT(badgeTopMargin, 10, @"Badge: Top Margin for the badge\nHow much space to leave between the top edge of the badge and the top edge of the terminal.");
#pragma mark - Experimental Features
DEFINE_BOOL(includePasteHistoryInAdvancedPaste, YES, @"Experimental Features: Include paste history in the advanced paste menu.");
// This used to be on by default. Experiment with setting to to NO: it'll make ssh nicer.
DEFINE_BOOL(tolerateUnrecognizedTmuxCommands, NO, @"Experimental Features: Tolerate unrecognized commands from server.\nNormally, an unknown command from tmux will not end the session. Turning this off helps detect dead ssh sessions.");
DEFINE_BOOL(serializeOpeningMultipleFullScreenWindows, YES, @"Experimental Features: When opening multiple fullscreen windows, enter fullscreen one window at a time.");
DEFINE_BOOL(useAdaptiveFrameRate, YES, @"Experimental Features: Use adaptive framerate.\nWhen throughput is low, the screen will update at 60 frames per second. When throughput is higher, it will update at 30 frames per second.");
DEFINE_FLOAT(slowFrameRate, 15.0, @"Experimental Features: When adaptive framerate is enabled, refresh at this rate during high throughput conditions (FPS).");
DEFINE_INT(adaptiveFrameRateThroughputThreshold, 10000, @"Experimental Features: Throughput threshold for adaptive frame rate.\nIf more than this many bytes per second are received, use the lower frame rate of 30 fps.");
DEFINE_BOOL(tabTitlesUseSmartTruncation, YES, @"Experimental Features: Use “smart truncation” for tab titles.\nIf a tab‘s title is too long to fit, ellipsize the start of the title if more tabs have unique suffixes than prefixes in a given window.");
DEFINE_BOOL(experimentalKeyHandling, YES, @"Experimental Features: Improved support for input method editors like AquaSKK.");
DEFINE_BOOL(hideStuckTooltips, YES, @"Experimental Features: Hide stuck tooltips.\nWhen you hide iTerm2 using a hotkey while a tooltip is fading out it gets stuck because of an OS bug. Work around it with a nasty hack by enabling this feature.")
DEFINE_BOOL(showYellowMarkForJobStoppedBySignal, YES, @"Experimental Features: Use a yellow for a Shell Integration prompt mark when the job is stopped by a signal.");
DEFINE_BOOL(openFileOverridesSendText, YES, @"Experimental Features: Should opening a script with iTerm2 disable the default profile's “Send Text at Start” setting?\nIf you use “open iTerm2 file.command” or drag a script onto iTerm2's icon and this setting is enabled then the script will be executed inl lieu of the profile's “Send Text at Start” setting. If this setting is off then both will be executed.");
// This is half implemented and should not be turned on by default.
DEFINE_BOOL(useLayers, NO, @"Experimental Features: Use Core Animation layers for opaque terminal views");
DEFINE_BOOL(acceptOSC7, YES, @"Experimental Features: Accept OSC 7 to set username, hostname, and path.");
DEFINE_BOOL(trackingRunloopForLiveResize, YES, @"Experimental Features: Use a tracking runloop for live resizing.");
DEFINE_BOOL(enableAPIServer, NO, @"Experimental Features: Enable websocket API server.\nYou must restart iTerm2 for this change to take effect.");
DEFINE_BOOL(useGCDUpdateTimer, YES, @"Experimental Features: Use GCD-based update timer instead of NSTimer.\nThis should cause more regular screen updates. Restart iTerm2 after changing this setting.");
DEFINE_BOOL(drawOutlineAroundCursor, NO, @"Experimental Features: Draw outline around underline and vertical bar cursors using background color.");
DEFINE_BOOL(killSessionsOnLogout, NO, @"Experimental Features: Kill sessions on logout.\nA possible fix for issue 4147.");
DEFINE_BOOL(detectPasswordInput, NO, @"Experimental Features: Show key at cursor at password prompt?");
DEFINE_BOOL(dwcLineCache, NO, @"Experimental Features: Enable cache of double-width character locations?\nThis should improve performance. It is always on in nightly builds. You must restart iTerm2 for this setting to take effect.");
@end
|
//
// iTermAdvancedSettingsModel.m
// iTerm
//
// Created by George Nachman on 3/18/14.
//
//
#import "iTermAdvancedSettingsModel.h"
#import "iTermAdvancedSettingsViewController.h"
#import "NSStringITerm.h"
@implementation iTermAdvancedSettingsModel
#define DEFINE_BOOL(name, theDefault, theDescription) \
+ (BOOL)name { \
NSString *theIdentifier = [@#name stringByCapitalizingFirstLetter]; \
return [iTermAdvancedSettingsViewController boolForIdentifier:theIdentifier \
defaultValue:theDefault \
description:theDescription]; \
} \
+ (NSString *)name##UserDefaultsKey { \
NSString *theIdentifier = [@#name stringByCapitalizingFirstLetter]; \
return theIdentifier; \
}
#define DEFINE_SETTABLE_BOOL(name, capitalizedName, theDefault, theDescription) \
DEFINE_BOOL(name, theDefault, theDescription) \
+ (void)set##capitalizedName :(BOOL)newValue { \
[[NSUserDefaults standardUserDefaults] setBool:newValue forKey:@#capitalizedName]; \
[[NSNotificationCenter defaultCenter] postNotificationName:iTermAdvancedSettingsDidChange \
object:nil]; \
}
#define DEFINE_OPTIONAL_BOOL(name, theDefault, theDescription) \
+ (BOOL *)name { \
NSString *theIdentifier = [@#name stringByCapitalizingFirstLetter]; \
return [iTermAdvancedSettingsViewController optionalBoolForIdentifier:theIdentifier \
defaultValue:theDefault \
description:theDescription]; \
} \
+ (NSString *)name##UserDefaultsKey { \
NSString *theIdentifier = [@#name stringByCapitalizingFirstLetter]; \
return theIdentifier; \
}
#define DEFINE_INT(name, theDefault, theDescription) \
+ (int)name { \
NSString *theIdentifier = [@#name stringByCapitalizingFirstLetter]; \
return [iTermAdvancedSettingsViewController intForIdentifier:theIdentifier \
defaultValue:theDefault \
description:theDescription]; \
}
#define DEFINE_FLOAT(name, theDefault, theDescription) \
+ (double)name { \
NSString *theIdentifier = [@#name stringByCapitalizingFirstLetter]; \
return [iTermAdvancedSettingsViewController floatForIdentifier:theIdentifier \
defaultValue:theDefault \
description:theDescription]; \
}
#define DEFINE_SETTABLE_FLOAT(name, capitalizedName, theDefault, theDescription) \
DEFINE_FLOAT(name, theDefault, theDescription) \
+ (void)set##capitalizedName :(double)newValue { \
[[NSUserDefaults standardUserDefaults] setDouble:newValue forKey:@#capitalizedName]; \
[[NSNotificationCenter defaultCenter] postNotificationName:iTermAdvancedSettingsDidChange \
object:nil]; \
}
#define DEFINE_STRING(name, theDefault, theDescription) \
+ (NSString *)name { \
NSString *theIdentifier = [@#name stringByCapitalizingFirstLetter]; \
return [iTermAdvancedSettingsViewController stringForIdentifier:theIdentifier \
defaultValue:theDefault \
description:theDescription]; \
}
#pragma mark Tabs
DEFINE_BOOL(useUnevenTabs, NO, @"Tabs: Uneven tab widths allowed.");
DEFINE_INT(minTabWidth, 75, @"Tabs: Minimum tab width when using uneven tab widths.");
DEFINE_INT(minCompactTabWidth, 60, @"Tabs: Minimum tab width when using uneven tab widths for compact tabs.");
DEFINE_INT(optimumTabWidth, 175, @"Tabs: Preferred tab width when tabs are equally sized.");
DEFINE_BOOL(addNewTabAtEndOfTabs, YES, @"Tabs: Add new tabs at the end of the tab bar, not next to current tab.");
DEFINE_BOOL(navigatePanesInReadingOrder, YES, @"Tabs: Next Pane and Previous Pane commands use reading order, not the time of last use.");
DEFINE_BOOL(eliminateCloseButtons, NO, @"Tabs: Eliminate close buttons from tabs, even on mouse-over.");
DEFINE_FLOAT(tabAutoShowHoldTime, 1.0, @"Tabs: How long in seconds to show tabs in fullscreen.\nThe tab bar appears briefly in fullscreen when the number of tabs changes or you switch tabs. This setting gives the time in seconds for it to remain visible.");
DEFINE_FLOAT(tabFlashAnimationDuration, 0.25, @"Tabs: Animation duration for fade in/out animation of tabs in full screen, in seconds.")
DEFINE_BOOL(allowDragOfTabIntoNewWindow, YES, @"Tabs: Allow a tab to be dragged and dropped outside any existing tab bar to create a new window.");
DEFINE_INT(minimumTabDragDistance, 10, @"Tabs: How far must the mouse move before a tab drag is initiated?\nYou must restart iTerm2 after changing this setting for it to take effect.");
#pragma mark Mouse
DEFINE_STRING(alternateMouseScrollStringForUp, @"",
@"Mouse: Scroll wheel up sends the specified text when in alternate screen mode.\n"
@"The value should use Vim syntax, such as \\e for escape.");
DEFINE_STRING(alternateMouseScrollStringForDown, @"",
@"Mouse: Scroll wheel down sends the specified text when in alternate screen mode.\n"
@"The value should use Vim syntax, such as \\e for escape.");
DEFINE_BOOL(alternateMouseScroll, NO, @"Mouse: Scroll wheel sends arrow keys when in alternate screen mode.");
DEFINE_BOOL(pinchToChangeFontSizeDisabled, NO, @"Mouse: Disable changing font size in response to a pinch gesture.");
DEFINE_BOOL(useSystemCursorWhenPossible, NO, @"Mouse: Use system cursor icons when possible.");
DEFINE_BOOL(alwaysAcceptFirstMouse, NO, @"Mouse: Always accept first mouse event on terminal windows.\nThis means clicks will work the same when iTerm2 is active as when it’s inactive.");
DEFINE_BOOL(doubleReportScrollWheel, NO, @"Mouse: Double-report scroll wheel events to work around tmux scrolling bug.");
DEFINE_BOOL(stealKeyFocus, NO, @"Mouse: When Focus Follows Mouse is enabled, steal key focus even when inactive.");
DEFINE_BOOL(cmdClickWhenInactiveInvokesSemanticHistory, NO, @"Mouse: ⌘-click in an active pane while iTerm2 isn't the active app invokes Semantic History.\nBy default, iTerm2 respects the OS standard that ⌘-click in an app that doesn't have keyboard focus behaves like a non-⌘ click that does not raise the window.");
#pragma mark Terminal
DEFINE_BOOL(traditionalVisualBell, NO, @"Terminal: Visual bell flashes the whole screen, not just a bell icon.");
DEFINE_FLOAT(timeBetweenBlinks, 0.5, @"Terminal: Cursor blink speed (seconds).");
DEFINE_BOOL(doNotSetCtype, NO, @"Terminal: Never set the CTYPE environment variable.");
// For these, 1 is more aggressive and 0 turns the feature off:
DEFINE_FLOAT(smartCursorColorBgThreshold, 0.5, @"Terminal: Threshold for Smart Cursor Color for background color (0 to 1).\n0 means the cursor’s background color will always be the cell’s text color, while 1 means it will always be black or white.");
DEFINE_FLOAT(smartCursorColorFgThreshold, 0.75, @"Terminal: Threshold for Smart Cursor Color for text color (0 to 1).\n0 means the cursor’s text color will always be the cell’s background color, while 1 means it will always be black or white.");
DEFINE_STRING(findUrlsRegex,
@"https?://([a-z0-9A-Z]+(:[a-zA-Z0-9]+)?@)?[a-z0-9A-Z\\-]+(\\.[a-z0-9A-Z\\-]+)*"
@"((:[0-9]+)?)(/[a-zA-Z0-9;:/\\.\\-_+%~?&@=#\\(\\)]*)?",
@"Terminal: Regular expression for “Find URLs” command.");
DEFINE_FLOAT(echoProbeDuration, 0.5, @"Terminal: Amount of time to wait while testing if echo is on (seconds).\nThis is used by the password manager to ensure you're at a password prompt.");
DEFINE_BOOL(disablePasswordManagerAnimations, NO, @"Terminal: Disable animations for showing/hiding password manager.");
DEFINE_BOOL(optionIsMetaForSpecialChars, YES, @"Terminal: When you press an arrow key or other function key that transmits the modifiers, should Option be translated to Meta?\nIf this is set to No then it will be translated to Alt.");
DEFINE_BOOL(noSyncSilenceAnnoyingBellAutomatically, NO, @"Terminal: Automatically silence bell when it rings too much.");
DEFINE_BOOL(restoreWindowContents, YES, @"Terminal: Restore window contents at startup.\nThis requires “System Prefs>General>Close windows when quitting an app” to be off.");
DEFINE_INT(numberOfLinesForAccessibility, 1000, @"Terminal: Maximum number of lines of history to expose to Accessibility.\nAccessibility APIs can make iTerm2 slow. In order to limit the effect, you can restrict the number of lines in each session that are visible to accessibility. The last lines of each session will be made accessible.");
DEFINE_INT(triggerRadius, 3, @"Terminal: Number of screen lines to match against trigger regular expressions.\nTrigger regular expressions are matched against the last logical line of text when a newline is received. A search is performed to find the start of the line. Since very long lines would cause performance problems, the search (and consequently the regular expression match, highlighting, and so on) is limited to this many screen lines.");
DEFINE_BOOL(requireCmdForDraggingText, NO, @"Terminal: To drag images or selected text, you must hold ⌘. This prevents accidental drags.");
DEFINE_BOOL(focusReportingEnabled, YES, @"Terminal: Apps may turn on Focus Reporting.\nFocus reporting causes iTerm2 to send an escape sequence when a session gains or loses focus. It can cause problems when an ssh session dies unexpectedly because it gets left on, so some users prefer to disable it.");
DEFINE_BOOL(useColorfgbgFallback, YES, @"Terminal: Use fallback for COLORFGBG if no exact match found?\nThe COLORFGBG variable indicates the ANSI colors that match the foreground and background colors. If no colors match and this setting is enabled, then the variable will be set to 15;0 to indicate a dark background or 0;15 to indicate a light background.");
DEFINE_BOOL(zeroWidthSpaceAdvancesCursor, YES, @"Terminal: Zero-Width Space (U+200B) advances cursor?\nWhile a zero-width space should not advance the cursor per the Unicode spec, both Terminal.app and Konsole do this, and Weechat depends on it. You must restart iTerm2 after changing this setting.");
DEFINE_BOOL(fullHeightCursor, NO, @"Terminal: Cursor occupies line spacing area.\nIf lines have more than 100% vertical spacing and this setting is enabled the bottom of the cursor will be aligned to the bottom of the spacing area.");
DEFINE_FLOAT(underlineCursorOffset, 0, @"Terminal: Vertical offset for underline cursor.\nPositive values move it up, negative values move it down.");
DEFINE_BOOL(preventEscapeSequenceFromClearingHistory, NO, @"Terminal: Prevent CSI 3 J from clearing scrollback history?\nThis is also known as thethe terminfo E3 capability.");
DEFINE_FLOAT(verticalBarCursorWidth, 1, @"Terminal: Width of vertical bar cursor.");
#pragma mark Hotkey
DEFINE_FLOAT(hotkeyTermAnimationDuration, 0.25, @"Hotkey: Duration in seconds of the hotkey window animation.\nWarning: reducing this value may cause problems if you have multiple displays.");
DEFINE_BOOL(dockIconTogglesWindow, NO, @"Hotkey: If the only window is a hotkey window, then clicking the dock icon shows or hides it.");
DEFINE_BOOL(hotkeyWindowFloatsAboveOtherWindows, NO, @"Hotkey: The hotkey window floats above other windows even when another application is active.\nYou must disable “Prefs > Keys > Hotkey window hides when focus is lost” for this setting to be effective.");
DEFINE_FLOAT(hotKeyDoubleTapMaxDelay, 0.3, @"Hotkey: The maximum amount of time allowed between presses of a modifier key when performing a modifier double-tap.");
#pragma mark General
DEFINE_STRING(searchCommand, @"https://google.com/search?q=%@", @"General: Template for URL of search engine.\niTerm2 replaces the string “%@” with the text to search for. Query parameter percent escaping is used.");
DEFINE_INT(autocompleteMaxOptions, 20, @"General: Number of autocomplete options to present.\nA value less than 100 is recommended.");
DEFINE_FLOAT(minRunningTime, 10, @"General: Grace period for automatic quitting after the last window is closed.\nIf iTerm2 is configured to quit automatically when the last window is closed, this setting gives a grace period (in seconds) after startup where that feature is disabled. Set to 0 to have no grace period.");
DEFINE_FLOAT(updateScreenParamsDelay, 1, @"General: Delay after changing number of screens/resolution until refresh (seconds).\nThis works around OS bugs where it takes some time after a screen change before it is safe to resize windows.");
DEFINE_BOOL(disableAppNap, NO, @"General: Disable App Nap.\nChange effective after restarting iTerm2.");
DEFINE_FLOAT(idleTimeSeconds, 2, @"General: Time in seconds before a session is considered idle.\nUsed for updating icons and activity indicator in tabs.");
DEFINE_FLOAT(findDelaySeconds, 1, @"General: Time to wait before performing Find action on 1- or 2- character queries.");
DEFINE_INT(maximumBytesToProvideToServices, 100000, @"General: Maximum number of bytes of selection to provide to Services.\nA large value here can cause performance issues when you have a big selection.");
DEFINE_BOOL(useOpenDirectory, YES, @"General: Use Open Directory to determine the user shell");
DEFINE_BOOL(disablePotentiallyInsecureEscapeSequences, NO, @"General: Disable potentially insecure escape sequences.\nSome features of iTerm2 expand the surface area for security issues. Consider turning this on when viewing untrusted content. The following custom escape sequences will be disabled: RemoteHost, StealFocus, CurrentDir, SetProfile, CopyToClipboard, EndCopy, File, SetBackgroundImageFile. The following DEC sequences are disabled: DECRQCRA. The following xterm extensions are disabled: Window Title Reporting, Icon Title Reporting. This will break displaying inline images, file download, some shell integration features, and other features.");
DEFINE_BOOL(performDictionaryLookupOnQuickLook, YES, @"General: Perform dictionary lookups on force press.\nIf this is NO, force press will still preview the Semantic History action; only dictionary lookups can be disabled.");
DEFINE_BOOL(jiggleTTYSizeOnClearBuffer, NO, @"General: Redraw the screen after the Clear Buffer menu item is selected.\nWhen enabled, the TTY size is briefly changed after clearing the buffer to cause the shell or current app to redraw.");
DEFINE_BOOL(indicateBellsInDockBadgeLabel, YES, @"General: Indicate the number of bells rung while the app is inactive in the dock icon’s badge label");
DEFINE_STRING(downloadsDirectory, @"", @"General: Downloads folder.\nIf set, downloaded files go to this location instead of the user’s $HOME/Downloads folder.");
DEFINE_FLOAT(pointSizeOfTimeStamp, 10, @"General: Point size for timestamps");
DEFINE_INT(terminalMargin, 5, @"General: Width of left and right margins in terminal panes\nHow much space to leave between the left and right edges of the terminal.\nYou must restart iTerm2 after modifying this property. Saved window arrangements should be re-created.");
DEFINE_INT(terminalVMargin, 2, @"General: Height of top and bottom margins in terminal panes\nHow much space to leave between the top and bottom edges of the terminal.\nYou must restart iTerm2 after modifying this property. Saved window arrangements should be re-created.");
DEFINE_BOOL(zippyTextDrawing, YES, @"General: Use zippy text drawing algorithm?\nThis draws non-ASCII text more quickly but with lower fidelity. This setting is ignored if ligatures are enabled in Prefs > Profiles > Text.");
DEFINE_BOOL(lowFiCombiningMarks, NO, @"General: Prefer speed to accuracy for characters with combining marks?");
DEFINE_BOOL(useVirtualKeyCodesForDetectingDigits, YES, @"General: On keyboards that require a modifier to press a digit, do not require that modifier for switching between windows, tabs, and panes by number.\nFor example, AZERTY requires you to hold down Shift to enter a number. To switch tabs with Cmd+Number on an AZERTY keyboard, you must enable this setting. Then, for example, Cmd-& switches to tab 1. When this setting is enabled, some user-defined shortcuts may become unavailable because the tab/window/pane switching behavior takes precedence.");
DEFINE_STRING(viewManPageCommand, @"man %@ || sleep 3", @"General: Command to view man pages.\nUsed when you press the man page button on the touch bar. %@ is replaced with the command. End the command with & to avoid opening an iTerm2 window (e.g., if you're launching an external viewer).");
#pragma mark - Semantic History
DEFINE_BOOL(ignoreHardNewlinesInURLs, NO, @"Semantic History: Ignore hard newlines for the purposes of locating URLs and file names for Semantic History.\nIf a hard newline occurs at the end of a line then cmd-click will not see it all unless this setting is turned on. This is useful for some interactive applications. Turning this on will remove newlines from the \\3 and \\4 substitutions.");
// Note: square brackets are included for ipv6 addresses like http://[2600:3c03::f03c:91ff:fe96:6a7a]/
DEFINE_STRING(URLCharacterSet, @".?\\/:;%=&_-,+~#@!*'(())|[]", @"Semantic History: Non-alphanumeric characters considered part of a URL for Semantic History.\nLetters and numbers are always considered part of the URL. These non-alphanumeric characters are used in addition for the purposes of figuring out where a URL begins and ends.");
DEFINE_INT(maxSemanticHistoryPrefixOrSuffix, 2000, @"Semantic History: Maximum number of bytes of text before and after click location to take into account.\nThis also limits the size of the \\3 and \\4 substitutions.");
DEFINE_STRING(pathsToIgnore, @"", @"Semantic History: Paths to ignore for Semantic History.\nSeparate paths with a comma. Any file under one of these paths will not be openable with Semantic History.");
DEFINE_BOOL(performDNSLookups, NO, @"Semantic History: Perform DNS lookups to check if URLs are valid?\nWhen enabled, the name under the mouse will be resolved with DNS to determine if it is a clickable link.");
#pragma mark - Debugging
DEFINE_BOOL(startDebugLoggingAutomatically, NO, @"Debugging: Start debug logging automatically when iTerm2 is launched.");
DEFINE_BOOL(logDrawingPerformance, NO, @"Debugging: Log stats about text drawing performance to console.\nUsed for performance testing.");
DEFINE_BOOL(logRestorableStateSize, NO, @"Debugging: Log restorable state size info to /tmp/statesize.*.txt.");
#pragma mark - Session
DEFINE_BOOL(runJobsInServers, YES, @"Session: Enable session restoration.\nSession restoration runs jobs in separate processes. They will survive crashes, force quits, and upgrades.\nYou must restart iTerm2 for this change to take effect.");
DEFINE_BOOL(killJobsInServersOnQuit, YES, @"Session: User-initiated Quit (⌘Q) of iTerm2 will kill all running jobs.\nApplies only when session restoration is on.");
DEFINE_SETTABLE_BOOL(suppressRestartAnnouncement, SuppressRestartAnnouncement, NO, @"Session: Suppress the Restart Session offer.\nWhen a sessions terminates, it will offer to restart itself. Turn this on to suppress the offer permanently.");
DEFINE_BOOL(showSessionRestoredBanner, YES, @"Session: When restoring a session without restoring a running job, draw a banner saying “Session Restored” below the restored contents.");
DEFINE_STRING(autoLogFormat,
@"\\(session.creationTimeString).\\(session.name).\\(session.termid).\\(iterm2.pid).\\(session.autoLogId).log",
@"Session: Format for automatic session log filenames.\nSee the Badges documentation for supported substitutions.");
DEFINE_BOOL(focusNewSplitPaneWithFocusFollowsMouse, YES, @"Session: When focus follows mouse is enabled, should new split panes automatically be focused?");
#pragma mark - Window
DEFINE_BOOL(openFileInNewWindows, NO, @"Windows: Open files in new windows, not new tabs.\nThis affects shell scripts opened from Finder, for example.");
DEFINE_BOOL(rememberWindowPositions, YES, @"Windows: Remember window locations even after the windows are closed.\nWhen a new window is opened, one of the recorded locations is used.");
DEFINE_BOOL(disableWindowSizeSnap, NO, @"Windows: Terminal windows resize smoothly.\nDisables snapping to character grid. Holding Control will temporarily disable snap-to-grid.");
DEFINE_BOOL(profilesWindowJoinsActiveSpace, NO, @"Windows: If the Profiles window is open, it always moves to join the active Space.\nYou must restart iTerm2 for a change in this setting to take effect.");
DEFINE_BOOL(darkThemeHasBlackTitlebar, YES, @"Windows: Dark themes give terminal windows black title bars by default.");
DEFINE_BOOL(fontChangeAffectsBroadcastingSessions, NO, @"Windows: Should growing or shrinking the font in a session that's broadcasting input affect all session that broadcast input?\nThis only applies to changing the font size with Make Text Bigger, Make Text Normal Size, and Make Text Smaller");
#pragma mark tmux
DEFINE_BOOL(noSyncNewWindowOrTabFromTmuxOpensTmux, NO, @"Tmux Integration: Suppress alert asking what kind of tab/window to open in tmux integration.");
DEFINE_BOOL(tmuxUsesDedicatedProfile, YES, @"Tmux Integration: Tmux always uses the “tmux” profile.\nIf disabled, tmux sessions use the profile of the session you ran tmux -CC in.");
#pragma mark Warnings
DEFINE_BOOL(neverWarnAboutMeta, NO, @"Warnings: Suppress a warning when Option Key Acts as Meta is enabled in Prefs>Profiles>Keys.");
DEFINE_BOOL(neverWarnAboutSpaces, NO, @"Warnings: Suppress a warning about how to configure Spaces when setting a window's Space.");
DEFINE_BOOL(neverWarnAboutOverrides, NO, @"Warnings: Suppress a warning about a change to a Profile key setting that overrides a global setting.");
DEFINE_BOOL(neverWarnAboutPossibleOverrides, NO, @"Warnings: Suppress a warning about a change to a global key that's overridden by a Profile.");
DEFINE_BOOL(noSyncNeverRemindPrefsChangesLostForUrl, NO, @"Warnings: Suppress changed-setting warning when prefs are loaded from a URL.");
DEFINE_BOOL(noSyncNeverRemindPrefsChangesLostForFile, NO, @"Warnings: Suppress changed-setting warning when prefs are loaded from a custom folder.");
DEFINE_BOOL(noSyncSuppressAnnyoingBellOffer, NO, @"Warnings: Suppress offer to silence bell when it rings too much.");
DEFINE_BOOL(suppressMultilinePasteWarningWhenPastingOneLineWithTerminalNewline, NO, @"Warnings: Suppress warning about multi-line paste when pasting a single line ending with a newline.\nThis supresses all multi-line paste warnings when a single line is being pasted.");
DEFINE_BOOL(suppressMultilinePasteWarningWhenNotAtShellPrompt, NO, @"Warnings: Suppress warning about multi-line paste when not at prompt.\nRequires Shell Integration to be installed.");
DEFINE_BOOL(noSyncSuppressBroadcastInputWarning, NO, @"Warnings: Suppress warning about broadcasting input.");
DEFINE_BOOL(noSyncSuppressCaptureOutputRequiresShellIntegrationWarning, NO,
@"Warnings: Suppress warning “Shell Integration is required for Capture Output.”");
DEFINE_BOOL(noSyncSuppressCaptureOutputToolNotVisibleWarning, NO,
@"Warnings: Suppress warning that the Captured Output tool is not visible.");
DEFINE_BOOL(closingTmuxWindowKillsTmuxWindows, NO, @"Warnings: Suppress kill/hide dialog when closing a tmux window.");
DEFINE_BOOL(closingTmuxTabKillsTmuxWindows, NO, @"Warnings: Suppress kill/hide dialog when closing a tmux tab.");
DEFINE_BOOL(aboutToPasteTabs, NO, @"Warnings: Suppress warning about pasting tabs with offer to convert them to spaces.");
DEFINE_FLOAT(shortLivedSessionDuration, 3, @"Warnings: Warn about short-lived sessions that live less than this many seconds.");
DEFINE_SETTABLE_BOOL(noSyncDoNotWarnBeforeMultilinePaste, NoSyncDoNotWarnBeforeMultilinePaste, NO, @"Warnings: Suppress warning about multi-line pastes (or a single line ending in a newline).\nThis applies whether you are at the shell prompt or not, provided two or more lines are being pasted.");
DEFINE_SETTABLE_BOOL(noSyncDoNotWarnBeforePastingOneLineEndingInNewlineAtShellPrompt, NoSyncDoNotWarnBeforePastingOneLineEndingInNewlineAtShellPrompt, NO, @"Warnings: Suppress warning about pasting a single line ending in a newline when at the shell prompt.\nThis requires Shell Integration to be installed.");
DEFINE_BOOL(noSyncReplaceProfileWarning, NO, @"Warnings: Suppress warning about copying a session's settings over a Profile");
DEFINE_OPTIONAL_BOOL(noSyncTurnOffFocusReportingOnHostChange, nil, @"Warnings: Always turn off focus reporting when host changes?");
DEFINE_OPTIONAL_BOOL(noSyncTurnOffMouseReportingOnHostChange, nil, @"Warnings: Always turn off mouse reporting when host changes?");
DEFINE_OPTIONAL_BOOL(noSyncTurnOffBracketedPasteOnHostChange, nil, @"Warnings: Always turn off paste bracketing when host changes?");
#pragma mark Pasteboard
DEFINE_BOOL(trimWhitespaceOnCopy, YES, @"Pasteboard: Trim whitespace when copying to pasteboard.");
DEFINE_INT(quickPasteBytesPerCall, 667, @"Pasteboard: Number of bytes to paste in each chunk when pasting normally.");
DEFINE_FLOAT(quickPasteDelayBetweenCalls, 0.01530456, @"Pasteboard: Delay in seconds between chunks when pasting normally.")
DEFINE_INT(slowPasteBytesPerCall, 16, @"Pasteboard: Number of bytes to paste in each chunk when pasting slowly.");
DEFINE_FLOAT(slowPasteDelayBetweenCalls, 0.125, @"Pasteboard: Delay in seconds between chunks when pasting slowly");
DEFINE_BOOL(copyWithStylesByDefault, NO, @"Pasteboard: Copy to pasteboard on selection includes color and font style.");
DEFINE_INT(pasteHistoryMaxOptions, 20, @"Pasteboard: Number of entires to save in Paste History.\n.");
DEFINE_BOOL(disallowCopyEmptyString, NO, @"Pasteboard: Disallow copying empty string to pasteboard.\nIf enabled, selecting an empty string (or all whitespace if trimming is enabled) will not erase the contents of the pasteboard.");
DEFINE_BOOL(typingClearsSelection, YES, @"Pasteboard: Pressing a key will remove the selection.");
DEFINE_SETTABLE_BOOL(promptForPasteWhenNotAtPrompt, PromptForPasteWhenNotAtPrompt, NO, @"Pasteboard: Warn before pasting when not at shell prompt?");
DEFINE_SETTABLE_BOOL(noSyncSuppressClipboardAccessDeniedWarning, NoSyncSuppressClipboardAccessDeniedWarning, NO, @"Session: Suppress the notification that the terminal attempted to access the clipboard but it was denied?");
DEFINE_SETTABLE_BOOL(noSyncSuppressMissingProfileInArrangementWarning, NoSyncSuppressMissingProfileInArrangementWarning, NO, @"Session: Suppress the notification that a restored session’s profile no longer exists?");
DEFINE_BOOL(excludeBackgroundColorsFromCopiedStyle, NO, @"Pasteboard: Exclude background colors when text is copied with color and font style?");
#pragma mark - Tip of the day
DEFINE_BOOL(noSyncTipsDisabled, NO, @"Tip of the Day: Disable the Tip of the Day?");
DEFINE_SETTABLE_FLOAT(timeBetweenTips, TimeBetweenTips, 24 * 60 * 60, @"Tip of the Day: Time between tips (in seconds)");
#pragma mark - Badge
DEFINE_STRING(badgeFont, @"Helvetica", @"Badge: Font to use for the badge.");
DEFINE_BOOL(badgeFontIsBold, YES, @"Badge: Should the badge render in bold type?");
DEFINE_FLOAT(badgeMaxWidthFraction, 0.5, @"Badge: Maximum width of the badge\nAs a fraction of the width of the terminal, between 0 and 1.0.");
DEFINE_FLOAT(badgeMaxHeightFraction, 0.2, @"Badge: Maximum height of the badge\nAs a fraction of the height of the terminal, between 0 and 1.0.");
DEFINE_INT(badgeRightMargin, 10, @"Badge: Right Margin for the badge\nHow much space to leave between the right edge of the badge and the right edge of the terminal.");
DEFINE_INT(badgeTopMargin, 10, @"Badge: Top Margin for the badge\nHow much space to leave between the top edge of the badge and the top edge of the terminal.");
#pragma mark - Experimental Features
DEFINE_BOOL(includePasteHistoryInAdvancedPaste, YES, @"Experimental Features: Include paste history in the advanced paste menu.");
// This used to be on by default. Experiment with setting to to NO: it'll make ssh nicer.
DEFINE_BOOL(tolerateUnrecognizedTmuxCommands, NO, @"Experimental Features: Tolerate unrecognized commands from server.\nNormally, an unknown command from tmux will not end the session. Turning this off helps detect dead ssh sessions.");
DEFINE_BOOL(serializeOpeningMultipleFullScreenWindows, YES, @"Experimental Features: When opening multiple fullscreen windows, enter fullscreen one window at a time.");
DEFINE_BOOL(useAdaptiveFrameRate, YES, @"Experimental Features: Use adaptive framerate.\nWhen throughput is low, the screen will update at 60 frames per second. When throughput is higher, it will update at 30 frames per second.");
DEFINE_FLOAT(slowFrameRate, 15.0, @"Experimental Features: When adaptive framerate is enabled, refresh at this rate during high throughput conditions (FPS).");
DEFINE_INT(adaptiveFrameRateThroughputThreshold, 10000, @"Experimental Features: Throughput threshold for adaptive frame rate.\nIf more than this many bytes per second are received, use the lower frame rate of 30 fps.");
DEFINE_BOOL(tabTitlesUseSmartTruncation, YES, @"Experimental Features: Use “smart truncation” for tab titles.\nIf a tab‘s title is too long to fit, ellipsize the start of the title if more tabs have unique suffixes than prefixes in a given window.");
DEFINE_BOOL(experimentalKeyHandling, YES, @"Experimental Features: Improved support for input method editors like AquaSKK.");
DEFINE_BOOL(hideStuckTooltips, YES, @"Experimental Features: Hide stuck tooltips.\nWhen you hide iTerm2 using a hotkey while a tooltip is fading out it gets stuck because of an OS bug. Work around it with a nasty hack by enabling this feature.")
DEFINE_BOOL(showYellowMarkForJobStoppedBySignal, YES, @"Experimental Features: Use a yellow for a Shell Integration prompt mark when the job is stopped by a signal.");
DEFINE_BOOL(openFileOverridesSendText, YES, @"Experimental Features: Should opening a script with iTerm2 disable the default profile's “Send Text at Start” setting?\nIf you use “open iTerm2 file.command” or drag a script onto iTerm2's icon and this setting is enabled then the script will be executed inl lieu of the profile's “Send Text at Start” setting. If this setting is off then both will be executed.");
// This is half implemented and should not be turned on by default.
DEFINE_BOOL(useLayers, NO, @"Experimental Features: Use Core Animation layers for opaque terminal views");
DEFINE_BOOL(acceptOSC7, YES, @"Experimental Features: Accept OSC 7 to set username, hostname, and path.");
DEFINE_BOOL(trackingRunloopForLiveResize, YES, @"Experimental Features: Use a tracking runloop for live resizing.");
DEFINE_BOOL(enableAPIServer, NO, @"Experimental Features: Enable websocket API server.\nYou must restart iTerm2 for this change to take effect.");
DEFINE_BOOL(useGCDUpdateTimer, YES, @"Experimental Features: Use GCD-based update timer instead of NSTimer.\nThis should cause more regular screen updates. Restart iTerm2 after changing this setting.");
DEFINE_BOOL(drawOutlineAroundCursor, NO, @"Experimental Features: Draw outline around underline and vertical bar cursors using background color.");
DEFINE_BOOL(killSessionsOnLogout, NO, @"Experimental Features: Kill sessions on logout.\nA possible fix for issue 4147.");
DEFINE_BOOL(detectPasswordInput, NO, @"Experimental Features: Show key at cursor at password prompt?");
DEFINE_BOOL(dwcLineCache, NO, @"Experimental Features: Enable cache of double-width character locations?\nThis should improve performance. It is always on in nightly builds. You must restart iTerm2 for this setting to take effect.");
@end
|
e4eb1063529deb575b75b396138d41554428d522
|
https://github.com/gnachman/iterm2
|
kohana_error_page.php
|
php
|
<?php defined('SYSPATH') OR die('No direct access allowed.'); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php if(isset ( $_SERVER['REQUEST_URI'])):?>
<meta http-equiv="refresh" content="60; url=<?php echo $_SERVER['REQUEST_URI'] ?>">
<?php endif ?>
<title><?php echo $error ?></title>
<?php echo html::stylesheet('media/css/common.css') ?>
<?php echo html::stylesheet('media/css/ui-'.Kohana::config('core.theme').'/jquery-ui.css') ?>
<?php echo html::link('media/images/favicon.ico','icon','image/ico') ?>
<?php echo html::script('media/js/jquery-min.js')?>
<?php echo html::script('media/js/jquery-ui.min.js')?>
<style type="text/css">
<?php #include Kohana::find_file('views', 'kohana_errors', FALSE, 'css') ?>
</style>
</head>
<body>
<div class="pagebody">
<table class="body">
<tr valign="top"><td>
<div class="left ui-widget">
<div class="p2 ui-widget-header ui-corner-top">
<?php echo "PNP4Nagios Version ".PNP_VERSION ?>
</div>
<div class="p4 ui-widget-content ui-corner-bottom" style="width: 640px">
<div style="padding: 0pt 0.7em;" class="ui-state-error ui-corner-all">
<h3>Please check the documentation for information about the following error.</h3>
<p><?php echo html::specialchars($message) ?></p>
<?php if ( ! empty($line) AND ! empty($file)): ?>
<h3>file [line]:</h3>
<p><?php echo Kohana::lang('core.error_file_line', $file, $line) ?></p>
<?php endif ?>
<?php if ( ! empty($trace)): ?>
<h3><?php echo Kohana::lang('core.stack_trace') ?></h3>
<?php echo $trace ?>
<?php endif ?>
<p>
<a href="javascript:history.back()"><?php echo Kohana::lang('common.back') ?></a>
</div>
</div>
</td><td>
<div class="right">
<div class="ui-widget">
<div class="p2 ui-widget-header ui-corner-top">
<?php echo Kohana::lang('common.icon-box-header') ?>
</div>
<div class="p4 ui-widget-content ui-corner-bottom" >
<?php
echo "<a title=\"".Kohana::lang('common.back')."\" href=\"javascript:history.back()\"><img class=\"icon\" src=\"".url::base()."media/images/back.png\"></a>\n";
echo "<a title=\"".Kohana::lang('common.title-home-link')."\" href=\"".url::base(TRUE)."graph\"><img class=\"icon\" src=\"".url::base()."media/images/home.png\"></a>\n";
echo "<a title=\"".Kohana::lang('common.title-docs-link')."\" href=\"".url::base(TRUE)."docs\"><img class=\"icon\" src=\"".url::base()."media/images/docs.png\"></a>\n";
?>
</div>
</div>
</div>
</td></tr>
<tr valign="top"><td colspan="2">
<div class="left">
<div class="cb p4 ui-widget-content ui-corner-all">
<?php echo pnp::print_version(); ?>
</div>
</div>
</div>
</td></tr></table>
</div>
</body>
</html>
|
<?php defined('SYSPATH') OR die('No direct access allowed.'); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php if(isset ( $_SERVER['REQUEST_URI'])):?>
<meta http-equiv="refresh" content="60">
<?php endif ?>
<title><?php echo $error ?></title>
<?php echo html::stylesheet('media/css/common.css') ?>
<?php echo html::stylesheet('media/css/ui-'.Kohana::config('core.theme').'/jquery-ui.css') ?>
<?php echo html::link('media/images/favicon.ico','icon','image/ico') ?>
<?php echo html::script('media/js/jquery-min.js')?>
<?php echo html::script('media/js/jquery-ui.min.js')?>
<style type="text/css">
<?php #include Kohana::find_file('views', 'kohana_errors', FALSE, 'css') ?>
</style>
</head>
<body>
<div class="pagebody">
<table class="body">
<tr valign="top"><td>
<div class="left ui-widget">
<div class="p2 ui-widget-header ui-corner-top">
<?php echo "PNP4Nagios Version ".PNP_VERSION ?>
</div>
<div class="p4 ui-widget-content ui-corner-bottom" style="width: 640px">
<div style="padding: 0pt 0.7em;" class="ui-state-error ui-corner-all">
<h3>Please check the documentation for information about the following error.</h3>
<p><?php echo html::specialchars($message) ?></p>
<?php if ( ! empty($line) AND ! empty($file)): ?>
<h3>file [line]:</h3>
<p><?php echo Kohana::lang('core.error_file_line', $file, $line) ?></p>
<?php endif ?>
<?php if ( ! empty($trace)): ?>
<h3><?php echo Kohana::lang('core.stack_trace') ?></h3>
<?php echo $trace ?>
<?php endif ?>
<p>
<a href="javascript:history.back()"><?php echo Kohana::lang('common.back') ?></a>
</div>
</div>
</td><td>
<div class="right">
<div class="ui-widget">
<div class="p2 ui-widget-header ui-corner-top">
<?php echo Kohana::lang('common.icon-box-header') ?>
</div>
<div class="p4 ui-widget-content ui-corner-bottom" >
<?php
echo "<a title=\"".Kohana::lang('common.back')."\" href=\"javascript:history.back()\"><img class=\"icon\" src=\"".url::base()."media/images/back.png\"></a>\n";
echo "<a title=\"".Kohana::lang('common.title-home-link')."\" href=\"".url::base(TRUE)."graph\"><img class=\"icon\" src=\"".url::base()."media/images/home.png\"></a>\n";
echo "<a title=\"".Kohana::lang('common.title-docs-link')."\" href=\"".url::base(TRUE)."docs\"><img class=\"icon\" src=\"".url::base()."media/images/docs.png\"></a>\n";
?>
</div>
</div>
</div>
</td></tr>
<tr valign="top"><td colspan="2">
<div class="left">
<div class="cb p4 ui-widget-content ui-corner-all">
<?php echo pnp::print_version(); ?>
</div>
</div>
</div>
</td></tr></table>
</div>
</body>
</html>
|
e4a19768a5c5e5b1276caf3dd5bb721a540ec014
|
https://github.com/lingej/pnp4nagios
|
view.php
|
php
|
<?php
if (!defined('FLUX_ROOT')) exit;
$this->loginRequired();
?>
<?php if($ticketlist): ?>
<h2><?php echo Flux::message('SDHeaderID') ?><?php echo htmlspecialchars($trow->ticket_id) ?> - <?php echo htmlspecialchars($trow->subject) ?></h2>
<table class="vertical-table" width="100%">
<tbody>
<tr>
<th>Account</th>
<td><?php echo $this->linkToAccount($trow->account_id,$session->account->userid . ' ('.$session->account->account_id.')') ?></td>
<th>Characters Affected</th>
<?php if($trow->char_id=='0'):?>
<td><i>All Characters</i></td>
<?php elseif($trow->char_id=='-1'):?>
<td><i>None on account</i></td>
<?php else:?>
<td><?php echo $this->linkToCharacter($trow->char_id,$char->name) ?></td>
<?php endif ?>
</tr>
<tr>
<th>Category</th>
<td><?php echo $catname ?></td>
<th>Current Status</th>
<td><?php echo htmlspecialchars($trow->status) ?></td>
</tr>
<tr>
<th>Date/Time Submitted</th>
<td><?php echo htmlspecialchars($trow->timestamp) ?></td>
<th>Team</th>
<td><?php if($trow->team=='1'): ?><?php echo Flux::message('SDGroup1') ?>
<?php elseif($trow->team=='2'): ?><?php echo Flux::message('SDGroup2') ?>
<?php elseif($trow->team=='3'): ?><?php echo Flux::message('SDGroup3') ?>
<?php endif ?></td>
</tr>
<tr>
<th>Subject</th>
<td colspan="3"><?php echo htmlspecialchars($trow->subject) ?></td>
</tr>
<?php if($trow->chatlink!='0'): ?>
<tr>
<th>Chat Logs</th>
<td colspan="3"><a href="<?php echo htmlspecialchars($trow->chatlink) ?>" target="_blank"><?php echo htmlspecialchars($trow->chatlink) ?></a></td></tr>
</tr>
<?php endif ?>
<?php if($trow->sslink!='0'): ?>
<tr>
<th>Screenshots</th>
<td colspan="3"><a href="<?php echo $trow->sslink ?>" target="_blank"><img src="<?php echo $trow->sslink ?>" width="100px" height="100"></a></td></tr>
</tr>
<?php endif ?>
<?php if($trow->videolink!='0'): ?>
<tr>
<th>Video Capture</th>
<td colspan="3"><?php echo htmlspecialchars($trow->videolink) ?></td></tr>
</tr>
<?php endif ?>
<tr>
<th>Body<br /> <br /> <br /> </th>
<td colspan="3"><?php echo nl2br($trow->text) ?></td></tr>
</tr>
</tbody>
</table>
<br />
<?php if($replylist): ?>
<?php foreach($replylist as $rrow): ?>
<table class="vertical-table" width="100%">
<tbody>
<tr>
<th width="100">Reply By</th>
<td>
<?php if($rrow->isstaff==1): ?>
<font color="<?php echo Flux::config('StaffReplyColour') ?>"><?php echo $rrow->author ?></font>
<?php elseif($rrow->isstaff==0): ?>
<?php echo $rrow->author ?>
<?php endif ?>
</td>
</tr>
<?php if($rrow->text!='0'): ?>
<tr>
<th>Response</th>
<td><?php echo nl2br(stripslashes($rrow->text)) ?></td>
</tr>
<?php endif ?>
<?php if($rrow->action!='0'): ?>
<tr>
<th>Action</th>
<td><?php echo $rrow->action ?></td>
</tr>
<?php endif ?>
<tr>
<th>Timestamp</th>
<td><?php echo $rrow->timestamp ?></td>
</tr>
</tbody>
</table><br />
<?php endforeach ?>
<?php else: ?>
<table class="vertical-table" width="100%">
<tbody>
<tr>
<th>There are no replies to this ticket.</th>
</tr>
</tbody>
</table>
<?php endif ?>
<br />
<?php if($trow->status!='Resolved' || $trow->status!='Closed'): ?>
<form action="<?php echo $this->urlWithQs ?>" method="post">
<table class="vertical-table" width="100%">
<tbody>
<tr>
<th width="100">Response</th>
<td><textarea cols="30" rows="10" name="response" placeholder="Click here to enter a response."></textarea></td>
</tr>
<tr>
<th>Actions</th>
<td><table class="generic-form-table">
<?php if($trow->status=="Resolved" || $trow->status=="Closed"): ?>
<tr><td><?php echo Flux::message('SDRespTable6') ?>:</td><td><input type="radio" name="secact" value="6" checked="checked" /></td></tr>
<?php else: ?>
<tr><td><?php echo Flux::message('SDRespTable2') ?>:</td><td><input type="radio" name="secact" value="2" checked="checked" /></td></tr>
<tr><td><?php echo Flux::message('SDRespTable3') ?>:</td><td><input type="radio" name="secact" value="3" /></td></tr>
<?php endif ?>
</table></td>
</tr>
<tr>
<td colspan="2">
<input type="hidden" name="postreply" value="gogolol" />
<input type="submit" name="submit" value="Add Reply" /></td>
</tr>
</tbody>
</table>
</form>
<?php endif ?>
<?php else: ?>
<p>
<?php echo htmlspecialchars(Flux::message('SDHuh')) ?>
</p>
<?php endif ?>
|
<?php
if (!defined('FLUX_ROOT')) exit;
$this->loginRequired();
?>
<?php if($ticketlist): ?>
<h2><?php echo Flux::message('SDHeaderID') ?><?php echo htmlspecialchars($trow->ticket_id) ?> - <?php echo htmlspecialchars($trow->subject) ?></h2>
<table class="vertical-table" width="100%">
<tbody>
<tr>
<th>Account</th>
<td><?php echo $this->linkToAccount($trow->account_id,$session->account->userid . ' ('.$session->account->account_id.')') ?></td>
<th>Characters Affected</th>
<?php if($trow->char_id=='0'):?>
<td><i>All Characters</i></td>
<?php elseif($trow->char_id=='-1'):?>
<td><i>None on account</i></td>
<?php else:?>
<td><?php echo $this->linkToCharacter($trow->char_id,$char->name) ?></td>
<?php endif ?>
</tr>
<tr>
<th>Category</th>
<td><?php echo $catname ?></td>
<th>Current Status</th>
<td><?php echo htmlspecialchars($trow->status) ?></td>
</tr>
<tr>
<th>Date/Time Submitted</th>
<td><?php echo htmlspecialchars($trow->timestamp) ?></td>
<th>Team</th>
<td><?php if($trow->team=='1'): ?><?php echo Flux::message('SDGroup1') ?>
<?php elseif($trow->team=='2'): ?><?php echo Flux::message('SDGroup2') ?>
<?php elseif($trow->team=='3'): ?><?php echo Flux::message('SDGroup3') ?>
<?php endif ?></td>
</tr>
<tr>
<th>Subject</th>
<td colspan="3"><?php echo htmlspecialchars($trow->subject) ?></td>
</tr>
<?php if($trow->chatlink!='0'): ?>
<tr>
<th>Chat Logs</th>
<td colspan="3"><a href="<?php echo htmlspecialchars($trow->chatlink) ?>" target="_blank"><?php echo htmlspecialchars($trow->chatlink) ?></a></td></tr>
</tr>
<?php endif ?>
<?php if($trow->sslink!='0'): ?>
<tr>
<th>Screenshots</th>
<td colspan="3"><a href="<?php echo htmlspecialchars($trow->sslink) ?>" target="_blank"><img src="<?php echo htmlspecialchars($trow->sslink) ?>" width="100px" height="100"></a></td></tr>
</tr>
<?php endif ?>
<?php if($trow->videolink!='0'): ?>
<tr>
<th>Video Capture</th>
<td colspan="3"><?php echo htmlspecialchars($trow->videolink) ?></td></tr>
</tr>
<?php endif ?>
<tr>
<th>Body<br /> <br /> <br /> </th>
<td colspan="3"><?php echo nl2br($trow->text) ?></td></tr>
</tr>
</tbody>
</table>
<br />
<?php if($replylist): ?>
<?php foreach($replylist as $rrow): ?>
<table class="vertical-table" width="100%">
<tbody>
<tr>
<th width="100">Reply By</th>
<td>
<?php if($rrow->isstaff==1): ?>
<font color="<?php echo Flux::config('StaffReplyColour') ?>"><?php echo $rrow->author ?></font>
<?php elseif($rrow->isstaff==0): ?>
<?php echo $rrow->author ?>
<?php endif ?>
</td>
</tr>
<?php if($rrow->text!='0'): ?>
<tr>
<th>Response</th>
<td><?php echo nl2br(stripslashes($rrow->text)) ?></td>
</tr>
<?php endif ?>
<?php if($rrow->action!='0'): ?>
<tr>
<th>Action</th>
<td><?php echo $rrow->action ?></td>
</tr>
<?php endif ?>
<tr>
<th>Timestamp</th>
<td><?php echo $rrow->timestamp ?></td>
</tr>
</tbody>
</table><br />
<?php endforeach ?>
<?php else: ?>
<table class="vertical-table" width="100%">
<tbody>
<tr>
<th>There are no replies to this ticket.</th>
</tr>
</tbody>
</table>
<?php endif ?>
<br />
<?php if($trow->status!='Resolved' || $trow->status!='Closed'): ?>
<form action="<?php echo $this->urlWithQs ?>" method="post">
<table class="vertical-table" width="100%">
<tbody>
<tr>
<th width="100">Response</th>
<td><textarea cols="30" rows="10" name="response" placeholder="Click here to enter a response."></textarea></td>
</tr>
<tr>
<th>Actions</th>
<td><table class="generic-form-table">
<?php if($trow->status=="Resolved" || $trow->status=="Closed"): ?>
<tr><td><?php echo Flux::message('SDRespTable6') ?>:</td><td><input type="radio" name="secact" value="6" checked="checked" /></td></tr>
<?php else: ?>
<tr><td><?php echo Flux::message('SDRespTable2') ?>:</td><td><input type="radio" name="secact" value="2" checked="checked" /></td></tr>
<tr><td><?php echo Flux::message('SDRespTable3') ?>:</td><td><input type="radio" name="secact" value="3" /></td></tr>
<?php endif ?>
</table></td>
</tr>
<tr>
<td colspan="2">
<input type="hidden" name="postreply" value="gogolol" />
<input type="submit" name="submit" value="Add Reply" /></td>
</tr>
</tbody>
</table>
</form>
<?php endif ?>
<?php else: ?>
<p>
<?php echo htmlspecialchars(Flux::message('SDHuh')) ?>
</p>
<?php endif ?>
|
8a39b2b2bf28353b3503ff1421862393db15aa7e
|
https://github.com/rathena/fluxcp
|
fee_sheet_options_ajax.php
|
php
|
<?php
/**
* Controller for getting information about fee sheet options
*
* @package OpenEMR
* @link http://www.open-emr.org
* @author Kevin Yeh <kevin.y@integralemr.com>
* @copyright Copyright (c) 2013 Kevin Yeh <kevin.y@integralemr.com> and OEMR <www.oemr.org>
* @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3
*/
require_once("../../../globals.php");
require_once("fee_sheet_options_queries.php");
use OpenEMR\Common\Acl\AclMain;
if (!AclMain::aclCheckCore('acct', 'bill')) {
header("HTTP/1.0 403 Forbidden");
echo "Not authorized for billing";
return false;
}
if (isset($_REQUEST['pricelevel'])) {
$pricelevel = $_REQUEST['pricelevel'];
} else {
$pricelevel = 'standard';
}
$fso = load_fee_sheet_options($pricelevel);
$retval = array();
$retval['fee_sheet_options'] = $fso;
$retval['pricelevel'] = $pricelevel;
echo json_encode($retval);
|
<?php
/**
* Controller for getting information about fee sheet options
*
* @package OpenEMR
* @link http://www.open-emr.org
* @author Kevin Yeh <kevin.y@integralemr.com>
* @copyright Copyright (c) 2013 Kevin Yeh <kevin.y@integralemr.com> and OEMR <www.oemr.org>
* @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3
*/
require_once("../../../globals.php");
require_once("fee_sheet_options_queries.php");
use OpenEMR\Common\Acl\AclMain;
if (!AclMain::aclCheckCore('acct', 'bill')) {
header("HTTP/1.0 403 Forbidden");
echo "Not authorized for billing";
return false;
}
if (isset($_REQUEST['pricelevel'])) {
$pricelevel = $_REQUEST['pricelevel'];
} else {
$pricelevel = 'standard';
}
$fso = load_fee_sheet_options($pricelevel);
$retval = array();
$retval['fee_sheet_options'] = $fso;
$retval['pricelevel'] = $pricelevel;
echo text(json_encode($retval));
|
59458bc15ab0cb556c521de9d5187167d6f88945
|
https://github.com/openemr/openemr
|
consumer.php
|
php
|
<?php
$this->data['header'] = 'OpenID Login';
$this->data['autofocus'] = 'openid-identifier';
$this->includeAtTemplateBase('includes/header.php');
?>
<style>
input.openid-identifier {
background: url(http://stat.livejournal.com/img/openid-inputicon.gif) no-repeat;
/* background-color: #fff; */
border-left: 1px solid #ccc;
border-right: 1px solid #aaa;
border-top: 1px solid #aaa;
border-bottom: 1px solid #ccc;
color: #555;
background-position: 0 50%;
padding-left: 18px;
}
fieldset {
border-left: 1px solid #aaa;
border-right: 1px solid #ccc;
border-top: 1px solid #ccc;
border-bottom: 1px solid #aaa;
padding: 1em;
}
legend {
padding-left: .3em;
padding-right: .3em;
color: #555;
}
div.error {
padding: 1em; margin: 1em;
background: red;
color: white;
border: 1px solid #600;
}
</style>
<?php if (isset($this->data['error'])) { print "<div class=\"error\">" . $this->data['error'] . "</div>"; } ?>
<form method="get" action="consumer.php">
<fieldset>
<legend>OpenID Login</legend>
Identity URL:
<input type="hidden" name="action" value="verify" />
<input id="openid-identifier" class="openid-identifier" type="text" name="openid_url" value="http://" />
<input type="hidden" name="AuthState" value="<?php echo $this->data['AuthState']; ?>" />
<input type="submit" value="Login with OpenID" />
</fieldset>
</form>
<p style="margin-top: 2em">
OpenID is a free and easy way to use a single digital identity across the Internet. Enter your OpenID identity URL in the box above to authenticate.
</p>
<?php
$this->includeAtTemplateBase('includes/footer.php');
?>
|
<?php
$this->data['header'] = 'OpenID Login';
$this->data['autofocus'] = 'openid-identifier';
$this->includeAtTemplateBase('includes/header.php');
?>
<style>
input.openid-identifier {
background: url(http://stat.livejournal.com/img/openid-inputicon.gif) no-repeat;
/* background-color: #fff; */
border-left: 1px solid #ccc;
border-right: 1px solid #aaa;
border-top: 1px solid #aaa;
border-bottom: 1px solid #ccc;
color: #555;
background-position: 0 50%;
padding-left: 18px;
}
fieldset {
border-left: 1px solid #aaa;
border-right: 1px solid #ccc;
border-top: 1px solid #ccc;
border-bottom: 1px solid #aaa;
padding: 1em;
}
legend {
padding-left: .3em;
padding-right: .3em;
color: #555;
}
div.error {
padding: 1em; margin: 1em;
background: red;
color: white;
border: 1px solid #600;
}
</style>
<?php if (isset($this->data['error'])) { print "<div class=\"error\">" . $this->data['error'] . "</div>"; } ?>
<form method="get" action="consumer.php">
<fieldset>
<legend>OpenID Login</legend>
Identity URL:
<input type="hidden" name="action" value="verify" />
<input id="openid-identifier" class="openid-identifier" type="text" name="openid_url" value="http://" />
<input type="hidden" name="AuthState" value="<?php echo htmlspecialchars($this->data['AuthState']); ?>" />
<input type="submit" value="Login with OpenID" />
</fieldset>
</form>
<p style="margin-top: 2em">
OpenID is a free and easy way to use a single digital identity across the Internet. Enter your OpenID identity URL in the box above to authenticate.
</p>
<?php
$this->includeAtTemplateBase('includes/footer.php');
?>
|
d652d41ccaf8c45d5707e741c0c5d82a2365a9a3
|
https://github.com/simplesamlphp/simplesamlphp-module-openid
|
fdb.inc.php
|
php
|
<div class="panel panel-default panel-condensed">
<div class="panel-heading">
<strong>FDB Entries</strong>
</div>
<table id="fdb-search" class="table table-hover table-condensed table-striped">
<thead>
<tr>
<th data-column-id="device">Device</th>
<th data-column-id="mac_address" data-width="150px" data-formatter="tooltip">MAC Address</th>
<th data-column-id="mac_oui" data-sortable="false" data-width="150px" data-visible="<?php echo \LibreNMS\Config::get('mac_oui.enabled') ? 'true' : 'false' ?>" data-formatter="tooltip">Vendor</th>
<th data-column-id="ipv4_address" data-sortable="false" data-formatter="tooltip">IPv4 Address</th>
<th data-column-id="interface">Port</th>
<th data-column-id="vlan" data-width="60px">Vlan</th>
<th data-column-id="description" data-formatter="tooltip">Description</th>
<th data-column-id="dnsname" data-sortable="false" data-visible="false" data-formatter="tooltip">DNS Name</th>
<th data-column-id="first_seen" data-width="165px">First seen</th>
<th data-column-id="last_seen" data-width="165px">Last seen</th>
</tr>
</thead>
</table>
</div>
<script>
var grid = $("#fdb-search").bootgrid({
ajax: true,
rowCount: [50, 100, 250, -1],
templates: {
header: "<div id=\"{{ctx.id}}\" class=\"{{css.header}}\"><div class=\"row\">"+
"<div class=\"col-sm-9 actionBar\"><span class=\"pull-left\">"+
"<form method=\"post\" action=\"\" class=\"form-inline\" role=\"form\">"+
"<?php echo addslashes(csrf_field()) ?>"+
"<div class=\"form-group\">"+
"<select name=\"device_id\" id=\"device_id\" class=\"form-control input-sm\">"+
"<option value=\"\">All Devices</option>"+
<?php
// Select the devices only with FDB tables
$sql = 'SELECT D.device_id AS device_id, `hostname`, `sysName`, `display` FROM `ports_fdb` AS F, `ports` AS P, `devices` AS D';
$param = [];
if (! Auth::user()->hasGlobalRead()) {
$device_ids = Permissions::devicesForUser()->toArray() ?: [0];
$where .= ' AND `D`.`device_id` IN ' . dbGenPlaceholders(count($device_ids));
$param = array_merge($param, $device_ids);
}
$sql .= " WHERE F.port_id = P.port_id AND P.device_id = D.device_id $where GROUP BY `D`.`device_id`, `D`.`hostname` ORDER BY `hostname`";
foreach (dbFetchRows($sql, $param) as $data) {
echo '"<option value=\"' . $data['device_id'] . '\""+';
if ($data['device_id'] == $vars['device_id']) {
echo '" selected "+';
}
echo '">' . format_hostname($data) . '</option>"+';
}
?>
"</select>"+
"</div>"+
"<div class=\"form-group\">"+
"<select name=\"searchby\" id=\"searchby\" class=\"form-control input-sm\">"+
"<option value=\"mac\" "+
<?php
if ($vars['searchby'] == 'mac') {
echo '" selected "+';
}
?>
">MAC Address</option>"+
"<option value=\"ip\" "+
<?php
if ($vars['searchby'] == 'ip') {
echo '" selected "+';
}
?>
">IP Address</option>"+
"<option value=\"dnsname\" "+
<?php
if ($vars['searchby'] == 'dnsname') {
echo '" selected "+';
}
?>
">DNS Name</option>"+
"<option value=\"description\" "+
<?php
if ($vars['searchby'] == 'description') {
echo '" selected "+';
}
?>
">Description</option>"+
"<option value=\"vendor\" "+
<?php
if ($vars['searchby'] == 'vendor') {
echo '" selected "+';
}
?>
">Vendor</option>"+
"<option value=\"vlan\" "+
<?php
if ($vars['searchby'] == 'vlan') {
echo '" selected "+';
}
?>
">Vlan</option>"+
"</select>"+
"</div>"+
"<div class=\"form-group\">"+
"<input type=\"text\" name=\"searchPhrase\" id=\"address\" value=\""+
<?php
echo '"' . $vars['searchPhrase'] . '"+';
?>
"\" class=\"form-control input-sm\" placeholder=\"Value\" />"+
"</div>"+
"<button type=\"submit\" class=\"btn btn-default input-sm\">Search</button>"+
"</form></span></div>"+
"<div class=\"col-sm-3 actionBar\"><p class=\"{{css.actions}}\"></p></div></div></div>"
},
post: function ()
{
return {
device_id: '<?php echo htmlspecialchars($vars['device_id']); ?>',
searchby: '<?php echo htmlspecialchars($vars['searchby']); ?>',
searchPhrase: '<?php echo htmlspecialchars($vars['searchPhrase']); ?>',
dns: $("#fdb-search").bootgrid("getColumnSettings").find(col => col.id === "dnsname").visible,
};
},
url: "<?php echo url('/ajax/table/fdb-tables'); ?>",
formatters: {
"tooltip": function (column, row) {
var value = row[column.id];
var vendor = '';
if (column.id == 'mac_address' && ((vendor = row['mac_oui']) != '' )) {
return "<span title=\'" + value + " (" + vendor + ")\' data-toggle=\'tooltip\'>" + value + "</span>";
}
return "<span title=\'" + value + "\' data-toggle=\'tooltip\'>" + value + "</span>";
},
},
});
</script>
|
<div class="panel panel-default panel-condensed">
<div class="panel-heading">
<strong>FDB Entries</strong>
</div>
<table id="fdb-search" class="table table-hover table-condensed table-striped">
<thead>
<tr>
<th data-column-id="device">Device</th>
<th data-column-id="mac_address" data-width="150px" data-formatter="tooltip">MAC Address</th>
<th data-column-id="mac_oui" data-sortable="false" data-width="150px" data-visible="<?php echo \LibreNMS\Config::get('mac_oui.enabled') ? 'true' : 'false' ?>" data-formatter="tooltip">Vendor</th>
<th data-column-id="ipv4_address" data-sortable="false" data-formatter="tooltip">IPv4 Address</th>
<th data-column-id="interface">Port</th>
<th data-column-id="vlan" data-width="60px">Vlan</th>
<th data-column-id="description" data-formatter="tooltip">Description</th>
<th data-column-id="dnsname" data-sortable="false" data-visible="false" data-formatter="tooltip">DNS Name</th>
<th data-column-id="first_seen" data-width="165px">First seen</th>
<th data-column-id="last_seen" data-width="165px">Last seen</th>
</tr>
</thead>
</table>
</div>
<script>
var grid = $("#fdb-search").bootgrid({
ajax: true,
rowCount: [50, 100, 250, -1],
templates: {
header: "<div id=\"{{ctx.id}}\" class=\"{{css.header}}\"><div class=\"row\">"+
"<div class=\"col-sm-9 actionBar\"><span class=\"pull-left\">"+
"<form method=\"post\" action=\"\" class=\"form-inline\" role=\"form\">"+
"<?php echo addslashes(csrf_field()) ?>"+
"<div class=\"form-group\">"+
"<select name=\"device_id\" id=\"device_id\" class=\"form-control input-sm\">"+
"<option value=\"\">All Devices</option>"+
<?php
// Select the devices only with FDB tables
$sql = 'SELECT D.device_id AS device_id, `hostname`, `sysName`, `display` FROM `ports_fdb` AS F, `ports` AS P, `devices` AS D';
$param = [];
if (! Auth::user()->hasGlobalRead()) {
$device_ids = Permissions::devicesForUser()->toArray() ?: [0];
$where .= ' AND `D`.`device_id` IN ' . dbGenPlaceholders(count($device_ids));
$param = array_merge($param, $device_ids);
}
$sql .= " WHERE F.port_id = P.port_id AND P.device_id = D.device_id $where GROUP BY `D`.`device_id`, `D`.`hostname` ORDER BY `hostname`";
foreach (dbFetchRows($sql, $param) as $data) {
echo '"<option value=\"' . $data['device_id'] . '\""+';
if ($data['device_id'] == $vars['device_id']) {
echo '" selected "+';
}
echo '">' . format_hostname($data) . '</option>"+';
}
?>
"</select>"+
"</div>"+
"<div class=\"form-group\">"+
"<select name=\"searchby\" id=\"searchby\" class=\"form-control input-sm\">"+
"<option value=\"mac\" "+
<?php
if ($vars['searchby'] == 'mac') {
echo '" selected "+';
}
?>
">MAC Address</option>"+
"<option value=\"ip\" "+
<?php
if ($vars['searchby'] == 'ip') {
echo '" selected "+';
}
?>
">IP Address</option>"+
"<option value=\"dnsname\" "+
<?php
if ($vars['searchby'] == 'dnsname') {
echo '" selected "+';
}
?>
">DNS Name</option>"+
"<option value=\"description\" "+
<?php
if ($vars['searchby'] == 'description') {
echo '" selected "+';
}
?>
">Description</option>"+
"<option value=\"vendor\" "+
<?php
if ($vars['searchby'] == 'vendor') {
echo '" selected "+';
}
?>
">Vendor</option>"+
"<option value=\"vlan\" "+
<?php
if ($vars['searchby'] == 'vlan') {
echo '" selected "+';
}
?>
">Vlan</option>"+
"</select>"+
"</div>"+
"<div class=\"form-group\">"+
"<input type=\"text\" name=\"searchPhrase\" id=\"address\" value=\""+
<?php
echo '"' . htmlspecialchars($vars['searchPhrase']) . '"+';
?>
"\" class=\"form-control input-sm\" placeholder=\"Value\" />"+
"</div>"+
"<button type=\"submit\" class=\"btn btn-default input-sm\">Search</button>"+
"</form></span></div>"+
"<div class=\"col-sm-3 actionBar\"><p class=\"{{css.actions}}\"></p></div></div></div>"
},
post: function ()
{
return {
device_id: '<?php echo htmlspecialchars($vars['device_id']); ?>',
searchby: '<?php echo htmlspecialchars($vars['searchby']); ?>',
searchPhrase: '<?php echo htmlspecialchars($vars['searchPhrase']); ?>',
dns: $("#fdb-search").bootgrid("getColumnSettings").find(col => col.id === "dnsname").visible,
};
},
url: "<?php echo url('/ajax/table/fdb-tables'); ?>",
formatters: {
"tooltip": function (column, row) {
var value = row[column.id];
var vendor = '';
if (column.id == 'mac_address' && ((vendor = row['mac_oui']) != '' )) {
return "<span title=\'" + value + " (" + vendor + ")\' data-toggle=\'tooltip\'>" + value + "</span>";
}
return "<span title=\'" + value + "\' data-toggle=\'tooltip\'>" + value + "</span>";
},
},
});
</script>
|
2c5960631c49f7414f61b6d4dcd305b07da05769
|
https://github.com/librenms/librenms
|
include.cdn.php
|
php
|
<?php
//always make sure we have a scriptNest variable (can be used to change default path for non-pathed modules
if(!isset($scriptNest)) {
$scriptNest = '';
}
?>
<script>
if (typeof console === "undefined") {
console = {};
if(typeof console.log === "undefined") {
console.log = function() {};
}
}
window.AS_APP = '<?php echo AS_APP; ?>';
function getFullURL() {
return '<?php echo trim( getFullURL(), '/'); ?>';
}
function getBaseURL() {
return '<?php echo getBaseURL(); ?>';
}
function getThemeURL() {
return '<?php echo getThemeURL(); ?>';
}
function getCdnURL() {
return '<?php echo $_SESSION[AS_APP]['environment']['cdn']; ?>';
}
<?php if($_SESSION[AS_APP]['localtesting']) { ?>
$_SESSION = <?php echo json_encode($_SESSION); ?>;
<?php } ?>
</script>
<script src="<?php echo $_SESSION[AS_APP]['environment']['cdn']; ?>/require.js"></script>
<script>
//configure require js
requirejs.config({
<?php //By default load any module IDs from js/lib ?>
baseUrl: getBaseURL()+'/script<?php echo $scriptNest; ?>',
paths: {
async: getCdnURL()+'/requirejs/async',
goog: getCdnURL()+'/requirejs/goog',
domReady: getCdnURL()+'/requirejs/domReady',
jquery: getCdnURL()+'/node_modules/jquery/dist/jquery.min',
jQuery: getCdnURL()+'/node_modules/jquery/dist/jquery.min',
moment: getCdnURL()+'/node_modules/moment/min/moment.min',
'es6-promise': getCdnURL()+'/node_modules/es6-promise/dist/es6-promise.min',
axios: getCdnURL()+'/node_modules/axios/dist/axios.min',
<?php if($_SESSION[AS_APP]['localtesting']) { ?>
vue: getCdnURL()+'/node_modules/vue/dist/vue',
<?php } else { ?>
vue: getCdnURL()+'/node_modules/vue/dist/vue.min',
<?php } ?>
semanticui: getBaseURL()+"/dcfront/script/rlibs/plugins/sa/semanticui/semantic.min",
script: getBaseURL()+'/script',
cdn: getCdnURL()
}
});
<?php foreach($requireJSModules as $module) { ?>
requirejs(['<?php echo $module; ?>'], function( a ) {
if(typeof(a)=='function') {
a();
}
});
<?php } ?>
</script>
|
<?php
//always make sure we have a scriptNest variable (can be used to change default path for non-pathed modules
if(!isset($scriptNest)) {
$scriptNest = '';
}
?>
<script>
if (typeof console === "undefined") {
console = {};
if(typeof console.log === "undefined") {
console.log = function() {};
}
}
window.AS_APP = '<?php echo AS_APP; ?>';
function getFullURL() {
return '<?php echo trim( htmlspecialchars( getFullURL(), ENT_QUOTES ), '/'); ?>';
}
function getBaseURL() {
return '<?php echo getBaseURL(); ?>';
}
function getThemeURL() {
return '<?php echo getThemeURL(); ?>';
}
function getCdnURL() {
return '<?php echo $_SESSION[AS_APP]['environment']['cdn']; ?>';
}
<?php if($_SESSION[AS_APP]['localtesting']) { ?>
$_SESSION = <?php echo json_encode($_SESSION); ?>;
<?php } ?>
</script>
<script src="<?php echo $_SESSION[AS_APP]['environment']['cdn']; ?>/require.js"></script>
<script>
//configure require js
requirejs.config({
<?php //By default load any module IDs from js/lib ?>
baseUrl: getBaseURL()+'/script<?php echo $scriptNest; ?>',
paths: {
async: getCdnURL()+'/requirejs/async',
goog: getCdnURL()+'/requirejs/goog',
domReady: getCdnURL()+'/requirejs/domReady',
jquery: getCdnURL()+'/node_modules/jquery/dist/jquery.min',
jQuery: getCdnURL()+'/node_modules/jquery/dist/jquery.min',
moment: getCdnURL()+'/node_modules/moment/min/moment.min',
'es6-promise': getCdnURL()+'/node_modules/es6-promise/dist/es6-promise.min',
axios: getCdnURL()+'/node_modules/axios/dist/axios.min',
<?php if($_SESSION[AS_APP]['localtesting']) { ?>
vue: getCdnURL()+'/node_modules/vue/dist/vue',
<?php } else { ?>
vue: getCdnURL()+'/node_modules/vue/dist/vue.min',
<?php } ?>
semanticui: getBaseURL()+"/dcfront/script/rlibs/plugins/sa/semanticui/semantic.min",
script: getBaseURL()+'/script',
cdn: getCdnURL()
}
});
<?php foreach($requireJSModules as $module) { ?>
requirejs(['<?php echo $module; ?>'], function( a ) {
if(typeof(a)=='function') {
a();
}
});
<?php } ?>
</script>
|
4acad1e3d2c34c017473ceea442fb3e3e078b2bd
|
https://github.com/andrewsauder/as
|
proxy.php
|
php
|
<?php
require_once '../../videos/configuration.php';
session_write_close();
try {
$global['mysqli']->close();
} catch (Exception $exc) {
//echo $exc->getTraceAsString();
}
/*
* this file is to handle HTTP URLs into HTTPS
*/
if (!filter_var($_GET['livelink'], FILTER_VALIDATE_URL) && preg_match("/^http.*/i", $_GET['livelink'])) {
echo "Invalid Link";
exit;
}
header("Content-Type: video/vnd.mpegurl");
header("Content-Disposition: attachment;filename=playlist.m3u");
$content = url_get_contents($_GET['livelink']);
$pathinfo = pathinfo($_GET['livelink']);
foreach (preg_split("/((\r?\n)|(\r\n?))/", $content) as $line) {
$line = trim($line);
if (!empty($line) && $line[0] !== "#") {
if (!filter_var($line, FILTER_VALIDATE_URL)) {
if(!empty($pathinfo["extension"])){
$_GET['livelink'] = str_replace($pathinfo["basename"], "", $_GET['livelink']);
}
$line = $_GET['livelink'].$line;
}
}
echo $line.PHP_EOL;
}
|
<?php
require_once '../../videos/configuration.php';
session_write_close();
try {
$global['mysqli']->close();
} catch (Exception $exc) {
//echo $exc->getTraceAsString();
}
/*
* this file is to handle HTTP URLs into HTTPS
*/
if (!filter_var($_GET['livelink'], FILTER_VALIDATE_URL) || !preg_match("/^http.*/i", $_GET['livelink'])) {
echo "Invalid Link";
exit;
}
header("Content-Type: video/vnd.mpegurl");
header("Content-Disposition: attachment;filename=playlist.m3u");
$content = url_get_contents($_GET['livelink']);
$pathinfo = pathinfo($_GET['livelink']);
foreach (preg_split("/((\r?\n)|(\r\n?))/", $content) as $line) {
$line = trim($line);
if (!empty($line) && $line[0] !== "#") {
if (!filter_var($line, FILTER_VALIDATE_URL)) {
if(!empty($pathinfo["extension"])){
$_GET['livelink'] = str_replace($pathinfo["basename"], "", $_GET['livelink']);
}
$line = $_GET['livelink'].$line;
}
}
echo $line.PHP_EOL;
}
|
218c98cbd4a4a2c15745852bcd0f29faf101bd8c
|
https://github.com/wwbn/avideo
|
index.php
|
php
|
<?php
/**
* The main admin backend index file.
*
* 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 phpMyFAQ
* @author Thorsten Rinne <thorsten@phpmyfaq.de>
* @author Bastian Poettner <bastian@poettner.net>
* @author Meikel Katzengreis <meikel@katzengreis.com>
* @author Minoru TODA <todam@netjapan.co.jp>
* @author Matteo Scaramuccia <matteo@phpmyfaq.de>
* @copyright 2002-2022 phpMyFAQ Team
* @license http://www.mozilla.org/MPL/2.0/ Mozilla Public License Version 2.0
* @link https://www.phpmyfaq.de
* @since 2002-09-16
*/
use phpMyFAQ\Attachment\AttachmentFactory;
use phpMyFAQ\Auth\AuthLdap;
use phpMyFAQ\Auth\AuthSso;
use phpMyFAQ\Faq;
use phpMyFAQ\Filter;
use phpMyFAQ\Helper\HttpHelper;
use phpMyFAQ\Language;
use phpMyFAQ\Language\Plurals;
use phpMyFAQ\Logging;
use phpMyFAQ\Permission\MediumPermission;
use phpMyFAQ\Strings;
use phpMyFAQ\System;
use phpMyFAQ\Template;
use phpMyFAQ\User\CurrentUser;
define('PMF_ROOT_DIR', dirname(__DIR__));
//
// Define the named constant used as a check by any included PHP file
//
const IS_VALID_PHPMYFAQ = null;
//
// Bootstrapping
//
require PMF_ROOT_DIR . '/src/Bootstrap.php';
// get language (default: english)
$Language = new Language($faqConfig);
$faqLangCode = $Language->setLanguage($faqConfig->get('main.languageDetection'), $faqConfig->get('main.language'));
// Preload English strings
require PMF_ROOT_DIR . '/lang/language_en.php';
$faqConfig->setLanguage($Language);
if (isset($faqLangCode) && Language::isASupportedLanguage($faqLangCode)) {
// Overwrite English strings with the ones we have in the current language
if (!file_exists(PMF_ROOT_DIR . '/lang/language_' . $faqLangCode . '.php')) {
$faqLangCode = 'en';
}
require PMF_ROOT_DIR . '/lang/language_' . $faqLangCode . '.php';
} else {
$faqLangCode = 'en';
}
//
// Load plurals support for selected language
//
$plr = new Plurals($PMF_LANG);
//
// Initializing static string wrapper
//
Strings::init($faqLangCode);
//
// Set actual template set name
//
Template::setTplSetName($faqConfig->get('main.templateSet'));
//
// Initialize attachment factory
//
AttachmentFactory::init(
$faqConfig->get('records.attachmentsStorageType'),
$faqConfig->get('records.defaultAttachmentEncKey'),
$faqConfig->get('records.enableAttachmentEncryption')
);
//
// Create a new phpMyFAQ system object
//
$faqSystem = new System();
//
// Create a new HTTP Helper
//
$http = new HttpHelper();
//
// Create a new FAQ object
//
$faq = new Faq($faqConfig);
//
// use mbstring extension if available and when possible
//
$validMbStrings = array('ja', 'en', 'uni');
$mbLanguage = ($PMF_LANG['metaLanguage'] != 'ja') ? 'uni' : $PMF_LANG['metaLanguage'];
if (function_exists('mb_language') && in_array($mbLanguage, $validMbStrings)) {
mb_language($mbLanguage);
mb_internal_encoding('utf-8');
}
//
// Get user action
//
$action = Filter::filterInput(INPUT_GET, 'action', FILTER_UNSAFE_RAW);
if (is_null($action)) {
$action = Filter::filterInput(INPUT_POST, 'action', FILTER_UNSAFE_RAW);
}
//
// Get CSRF Token
//
$csrfToken = Filter::filterInput(INPUT_GET, 'csrf', FILTER_UNSAFE_RAW);
if (!isset($_SESSION['phpmyfaq_csrf_token']) || $_SESSION['phpmyfaq_csrf_token'] !== $csrfToken) {
$csrfChecked = false;
} else {
$csrfChecked = true;
}
//
// Get possible redirect action
//
$redirectAction = Filter::filterInput(INPUT_POST, 'redirect-action', FILTER_UNSAFE_RAW);
if (is_null($action) && '' !== $redirectAction && 'logout' !== $redirectAction) {
$action = $redirectAction;
}
// authenticate current user
$auth = null;
$error = '';
$faqusername = Filter::filterInput(INPUT_POST, 'faqusername', FILTER_UNSAFE_RAW);
$faqpassword = Filter::filterInput(INPUT_POST, 'faqpassword', FILTER_UNSAFE_RAW, FILTER_FLAG_NO_ENCODE_QUOTES);
$faqremember = Filter::filterInput(INPUT_POST, 'faqrememberme', FILTER_UNSAFE_RAW);
// Set username via SSO
if ($faqConfig->get('security.ssoSupport') && isset($_SERVER['REMOTE_USER'])) {
$faqusername = trim($_SERVER['REMOTE_USER']);
$faqpassword = '';
}
// Login via local DB or LDAP or SSO
if (!is_null($faqusername) && !is_null($faqpassword)) {
$user = new CurrentUser($faqConfig);
if (!is_null($faqremember) && 'rememberMe' === $faqremember) {
$user->enableRememberMe();
}
if ($faqConfig->isLdapActive() && function_exists('ldap_connect')) {
try {
$authLdap = new AuthLdap($faqConfig);
$user->addAuth($authLdap, 'ldap');
} catch (Exception $e) {
$error = $e->getMessage() . '<br>';
}
}
if ($faqConfig->get('security.ssoSupport')) {
$authSso = new AuthSso($faqConfig);
$user->addAuth($authSso, 'sso');
}
if ($user->login($faqusername, $faqpassword)) {
// login, if user account is NOT blocked
if ($user->getStatus() != 'blocked') {
$auth = true;
} else {
$error = $error . $PMF_LANG['ad_auth_fail'];
}
} else {
// error
$logging = new Logging($faqConfig);
$logging->logAdmin($user, 'Loginerror\nLogin: ' . $faqusername . '\nErrors: ' . implode(', ', $user->errors));
$error = $error . $PMF_LANG['ad_auth_fail'];
}
} else {
// Try to authenticate with cookie information
$user = CurrentUser::getFromCookie($faqConfig);
// authenticate with session information
if (!$user instanceof CurrentUser) {
$user = CurrentUser::getFromSession($faqConfig);
}
if ($user instanceof CurrentUser) {
$auth = true;
} else {
$user = new CurrentUser($faqConfig);
}
}
// logout
if ($csrfChecked && $action === 'logout' && $auth) {
$user->deleteFromSession(true);
$auth = null;
$ssoLogout = $faqConfig->get('security.ssoLogoutRedirect');
if ($faqConfig->get('security.ssoSupport') && !empty($ssoLogout)) {
$http->redirect($ssoLogout);
}
}
//
// Get current admin user and group id - default: -1
//
if (isset($user) && is_object($user)) {
$currentAdminUser = $user->getUserId();
if ($user->perm instanceof MediumPermission) {
$currentAdminGroups = $user->perm->getUserGroups($currentAdminUser);
} else {
$currentAdminGroups = [-1];
}
if (0 === count($currentAdminGroups)) {
$currentAdminGroups = [-1];
}
}
//
// Get action from _GET and _POST first
$ajax = Filter::filterInput(INPUT_GET, 'ajax', FILTER_UNSAFE_RAW);
if (is_null($ajax)) {
$ajax = Filter::filterInput(INPUT_POST, 'ajax', FILTER_UNSAFE_RAW);
}
// if performing AJAX operation, needs to branch before header.php
if (isset($auth) && (count($user->perm->getAllUserRights($user->getUserId())) > 0 || $user->isSuperAdmin())) {
if (isset($action) && isset($ajax)) {
if ('ajax' === $action) {
switch ($ajax) {
// Attachments
case 'att':
require 'ajax.attachment.php';
break;
// Dashboard
case 'dashboard':
require 'ajax.dashboard.php';
break;
// Link verification
case 'verifyURL':
require 'ajax.verifyurl.php';
break;
case 'onDemandURL':
require 'ajax.ondemandurl.php';
break;
// Categories
case 'categories':
require 'ajax.category.php';
break;
// Configuration management
case 'config_list':
require 'ajax.config_list.php';
break;
case 'config':
require 'ajax.config.php';
break;
case 'elasticsearch':
require 'ajax.elasticsearch.php';
break;
// Tags management
case 'tags':
require 'ajax.tags.php';
break;
// Comments
case 'comment':
require 'ajax.comment.php';
break;
// Records
case 'records':
require 'ajax.records.php';
break;
case 'recordSave':
require 'record.save.php';
break;
case 'recordAdd':
require 'record.add.php';
break;
case 'markdown':
require 'ajax.markdown.php';
break;
// Search
case 'search':
require 'ajax.search.php';
break;
// Users
case 'user':
require 'ajax.user.php';
break;
// Groups
case 'group':
require 'ajax.group.php';
break;
// Sections
case 'section':
require 'ajax.section.php';
break;
// Interface translation
case 'trans':
require 'ajax.trans.php';
break;
// Image upload
case 'image':
require 'ajax.image.php';
break;
}
exit();
}
}
}
// are we running a PMF export file request?
switch ($action) {
case 'exportfile':
require 'export.file.php';
exit();
break;
case 'reportexport':
require 'report.export.php';
exit();
break;
}
// Header of the admin page including the navigation
require 'header.php';
$numRights = count($user->perm->getAllUserRights($user->getUserId()));
// User is authenticated
if (isset($auth) && ($numRights > 0 || $user->isSuperAdmin())) {
if (!is_null($action)) {
// the various sections of the admin area
switch ($action) {
// functions for user administration
case 'user':
require 'user.php';
break;
case 'group':
require 'group.php';
break;
case 'section':
require 'section.php';
break;
// functions for content administration
case 'faqs-overview':
require 'faqs.overview.php';
break;
case 'viewinactive':
case 'viewactive':
case 'view':
require 'record.show.php';
break;
case 'searchfaqs':
require 'record.search.php';
break;
case 'takequestion':
case 'editentry':
case 'copyentry':
case 'editpreview':
require 'record.edit.php';
break;
case 'insertentry':
require 'record.add.php';
break;
case 'saveentry':
require 'record.save.php';
break;
case 'delatt':
require 'record.delatt.php';
break;
case 'question':
require 'record.questions.php';
break;
case 'comments':
require 'record.comments.php';
break;
// functions for tags
case 'tags':
case 'delete-tag':
require 'tags.php';
break;
// news administration
case 'news':
case 'add-news':
case 'edit-news':
case 'save-news':
case 'update-news':
case 'delete-news':
require 'news.php';
break;
// category administration
case 'content':
case 'category':
case 'savecategory':
case 'updatecategory':
case 'checkIfCategoryExists':
case 'removecategory':
case 'changecategory':
case 'pastecategory':
require 'category.main.php';
break;
case 'addcategory':
require 'category.add.php';
break;
case 'editcategory':
require 'category.edit.php';
break;
case 'translatecategory':
require 'category.translate.php';
break;
case 'deletecategory':
require 'category.delete.php';
break;
case 'cutcategory':
require 'category.cut.php';
break;
case 'movecategory':
require 'category.move.php';
break;
case 'showcategory':
require 'category.showstructure.php';
break;
// glossary
case 'glossary':
case 'saveglossary':
case 'updateglossary':
case 'deleteglossary':
require 'glossary.main.php';
break;
case 'addglossary':
require 'glossary.add.php';
break;
case 'editglossary':
require 'glossary.edit.php';
break;
// functions for password administration
case 'passwd':
require 'pwd.change.php';
break;
// functions for session administration
case 'adminlog':
case 'deleteadminlog':
require 'stat.adminlog.php';
break;
case 'viewsessions':
case 'clear-visits':
require 'stat.main.php';
break;
case 'sessionbrowse':
require 'stat.browser.php';
break;
case 'viewsession':
require 'statistics.show.php';
break;
case 'clear-statistics':
case 'statistics':
require 'stat.ratings.php';
break;
case 'truncatesearchterms':
case 'searchstats':
require 'stat.search.php';
break;
// Reports
case 'reports':
require 'report.main.php';
break;
case 'reportview':
require 'report.view.php';
break;
// Config administration
case 'config':
require 'configuration.php';
break;
case 'system':
require 'system.php';
break;
case 'updateinstance':
case 'instances':
require 'instances.php';
break;
case 'editinstance':
require 'instances.edit.php';
break;
case 'stopwordsconfig':
require 'stopwords.php';
break;
case 'elasticsearch':
require 'elasticsearch.php';
break;
case 'meta':
case 'meta.update';
require 'meta.php';
break;
case 'meta.edit':
require 'meta.edit.php';
break;
// functions for backup administration
case 'backup':
require 'backup.main.php';
break;
case 'restore':
require 'backup.import.php';
break;
// functions for FAQ export
case 'export':
require 'export.main.php';
break;
// attachment administration
case 'attachments':
require 'attachments.php';
break;
default:
echo 'Dave, this conversation can serve no purpose anymore. Goodbye.';
break;
}
} else {
require 'dashboard.php';
}
// User is authenticated, but has no rights
} elseif (isset($auth) && $numRights === 0) {
require 'noperm.php';
// User is NOT authenticated
} else {
require 'loginform.php';
}
require 'footer.php';
$faqConfig->getDb()->close();
|
<?php
/**
* The main admin backend index file.
*
* 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 phpMyFAQ
* @author Thorsten Rinne <thorsten@phpmyfaq.de>
* @author Bastian Poettner <bastian@poettner.net>
* @author Meikel Katzengreis <meikel@katzengreis.com>
* @author Minoru TODA <todam@netjapan.co.jp>
* @author Matteo Scaramuccia <matteo@phpmyfaq.de>
* @copyright 2002-2022 phpMyFAQ Team
* @license http://www.mozilla.org/MPL/2.0/ Mozilla Public License Version 2.0
* @link https://www.phpmyfaq.de
* @since 2002-09-16
*/
use phpMyFAQ\Attachment\AttachmentFactory;
use phpMyFAQ\Auth\AuthLdap;
use phpMyFAQ\Auth\AuthSso;
use phpMyFAQ\Faq;
use phpMyFAQ\Filter;
use phpMyFAQ\Helper\HttpHelper;
use phpMyFAQ\Language;
use phpMyFAQ\Language\Plurals;
use phpMyFAQ\Logging;
use phpMyFAQ\Permission\MediumPermission;
use phpMyFAQ\Strings;
use phpMyFAQ\System;
use phpMyFAQ\Template;
use phpMyFAQ\User\CurrentUser;
define('PMF_ROOT_DIR', dirname(__DIR__));
//
// Define the named constant used as a check by any included PHP file
//
const IS_VALID_PHPMYFAQ = null;
//
// Bootstrapping
//
require PMF_ROOT_DIR . '/src/Bootstrap.php';
// get language (default: english)
$Language = new Language($faqConfig);
$faqLangCode = $Language->setLanguage($faqConfig->get('main.languageDetection'), $faqConfig->get('main.language'));
// Preload English strings
require PMF_ROOT_DIR . '/lang/language_en.php';
$faqConfig->setLanguage($Language);
if (isset($faqLangCode) && Language::isASupportedLanguage($faqLangCode)) {
// Overwrite English strings with the ones we have in the current language
if (!file_exists(PMF_ROOT_DIR . '/lang/language_' . $faqLangCode . '.php')) {
$faqLangCode = 'en';
}
require PMF_ROOT_DIR . '/lang/language_' . $faqLangCode . '.php';
} else {
$faqLangCode = 'en';
}
//
// Load plurals support for selected language
//
$plr = new Plurals($PMF_LANG);
//
// Initializing static string wrapper
//
Strings::init($faqLangCode);
//
// Set actual template set name
//
Template::setTplSetName($faqConfig->get('main.templateSet'));
//
// Initialize attachment factory
//
AttachmentFactory::init(
$faqConfig->get('records.attachmentsStorageType'),
$faqConfig->get('records.defaultAttachmentEncKey'),
$faqConfig->get('records.enableAttachmentEncryption')
);
//
// Create a new phpMyFAQ system object
//
$faqSystem = new System();
//
// Create a new HTTP Helper
//
$http = new HttpHelper();
//
// Create a new FAQ object
//
$faq = new Faq($faqConfig);
//
// use mbstring extension if available and when possible
//
$validMbStrings = array('ja', 'en', 'uni');
$mbLanguage = ($PMF_LANG['metaLanguage'] != 'ja') ? 'uni' : $PMF_LANG['metaLanguage'];
if (function_exists('mb_language') && in_array($mbLanguage, $validMbStrings)) {
mb_language($mbLanguage);
mb_internal_encoding('utf-8');
}
//
// Get user action
//
$action = Filter::filterInput(INPUT_GET, 'action', FILTER_UNSAFE_RAW);
if (is_null($action)) {
$action = Filter::filterInput(INPUT_POST, 'action', FILTER_UNSAFE_RAW);
}
$action = Strings::htmlentities($action);
//
// Get CSRF Token
//
$csrfToken = Filter::filterInput(INPUT_GET, 'csrf', FILTER_UNSAFE_RAW);
if (!isset($_SESSION['phpmyfaq_csrf_token']) || $_SESSION['phpmyfaq_csrf_token'] !== $csrfToken) {
$csrfChecked = false;
} else {
$csrfChecked = true;
}
//
// Get possible redirect action
//
$redirectAction = Filter::filterInput(INPUT_POST, 'redirect-action', FILTER_UNSAFE_RAW);
if (is_null($action) && '' !== $redirectAction && 'logout' !== $redirectAction) {
$action = $redirectAction;
}
// authenticate current user
$auth = null;
$error = '';
$faqusername = Filter::filterInput(INPUT_POST, 'faqusername', FILTER_UNSAFE_RAW);
$faqpassword = Filter::filterInput(INPUT_POST, 'faqpassword', FILTER_UNSAFE_RAW, FILTER_FLAG_NO_ENCODE_QUOTES);
$faqremember = Filter::filterInput(INPUT_POST, 'faqrememberme', FILTER_UNSAFE_RAW);
// Set username via SSO
if ($faqConfig->get('security.ssoSupport') && isset($_SERVER['REMOTE_USER'])) {
$faqusername = trim($_SERVER['REMOTE_USER']);
$faqpassword = '';
}
// Login via local DB or LDAP or SSO
if (!is_null($faqusername) && !is_null($faqpassword)) {
$user = new CurrentUser($faqConfig);
if (!is_null($faqremember) && 'rememberMe' === $faqremember) {
$user->enableRememberMe();
}
if ($faqConfig->isLdapActive() && function_exists('ldap_connect')) {
try {
$authLdap = new AuthLdap($faqConfig);
$user->addAuth($authLdap, 'ldap');
} catch (Exception $e) {
$error = $e->getMessage() . '<br>';
}
}
if ($faqConfig->get('security.ssoSupport')) {
$authSso = new AuthSso($faqConfig);
$user->addAuth($authSso, 'sso');
}
if ($user->login($faqusername, $faqpassword)) {
// login, if user account is NOT blocked
if ($user->getStatus() != 'blocked') {
$auth = true;
} else {
$error = $error . $PMF_LANG['ad_auth_fail'];
}
} else {
// error
$logging = new Logging($faqConfig);
$logging->logAdmin($user, 'Loginerror\nLogin: ' . $faqusername . '\nErrors: ' . implode(', ', $user->errors));
$error = $error . $PMF_LANG['ad_auth_fail'];
}
} else {
// Try to authenticate with cookie information
$user = CurrentUser::getFromCookie($faqConfig);
// authenticate with session information
if (!$user instanceof CurrentUser) {
$user = CurrentUser::getFromSession($faqConfig);
}
if ($user instanceof CurrentUser) {
$auth = true;
} else {
$user = new CurrentUser($faqConfig);
}
}
// logout
if ($csrfChecked && $action === 'logout' && $auth) {
$user->deleteFromSession(true);
$auth = null;
$ssoLogout = $faqConfig->get('security.ssoLogoutRedirect');
if ($faqConfig->get('security.ssoSupport') && !empty($ssoLogout)) {
$http->redirect($ssoLogout);
}
}
//
// Get current admin user and group id - default: -1
//
if (isset($user) && is_object($user)) {
$currentAdminUser = $user->getUserId();
if ($user->perm instanceof MediumPermission) {
$currentAdminGroups = $user->perm->getUserGroups($currentAdminUser);
} else {
$currentAdminGroups = [-1];
}
if (0 === count($currentAdminGroups)) {
$currentAdminGroups = [-1];
}
}
//
// Get action from _GET and _POST first
$ajax = Filter::filterInput(INPUT_GET, 'ajax', FILTER_UNSAFE_RAW);
if (is_null($ajax)) {
$ajax = Filter::filterInput(INPUT_POST, 'ajax', FILTER_UNSAFE_RAW);
}
// if performing AJAX operation, needs to branch before header.php
if (isset($auth) && (count($user->perm->getAllUserRights($user->getUserId())) > 0 || $user->isSuperAdmin())) {
if (isset($action) && isset($ajax)) {
if ('ajax' === $action) {
switch ($ajax) {
// Attachments
case 'att':
require 'ajax.attachment.php';
break;
// Dashboard
case 'dashboard':
require 'ajax.dashboard.php';
break;
// Link verification
case 'verifyURL':
require 'ajax.verifyurl.php';
break;
case 'onDemandURL':
require 'ajax.ondemandurl.php';
break;
// Categories
case 'categories':
require 'ajax.category.php';
break;
// Configuration management
case 'config_list':
require 'ajax.config_list.php';
break;
case 'config':
require 'ajax.config.php';
break;
case 'elasticsearch':
require 'ajax.elasticsearch.php';
break;
// Tags management
case 'tags':
require 'ajax.tags.php';
break;
// Comments
case 'comment':
require 'ajax.comment.php';
break;
// Records
case 'records':
require 'ajax.records.php';
break;
case 'recordSave':
require 'record.save.php';
break;
case 'recordAdd':
require 'record.add.php';
break;
case 'markdown':
require 'ajax.markdown.php';
break;
// Search
case 'search':
require 'ajax.search.php';
break;
// Users
case 'user':
require 'ajax.user.php';
break;
// Groups
case 'group':
require 'ajax.group.php';
break;
// Sections
case 'section':
require 'ajax.section.php';
break;
// Interface translation
case 'trans':
require 'ajax.trans.php';
break;
// Image upload
case 'image':
require 'ajax.image.php';
break;
}
exit();
}
}
}
// are we running a PMF export file request?
switch ($action) {
case 'exportfile':
require 'export.file.php';
exit();
break;
case 'reportexport':
require 'report.export.php';
exit();
break;
}
// Header of the admin page including the navigation
require 'header.php';
$numRights = count($user->perm->getAllUserRights($user->getUserId()));
// User is authenticated
if (isset($auth) && ($numRights > 0 || $user->isSuperAdmin())) {
if (!is_null($action)) {
// the various sections of the admin area
switch ($action) {
// functions for user administration
case 'user':
require 'user.php';
break;
case 'group':
require 'group.php';
break;
case 'section':
require 'section.php';
break;
// functions for content administration
case 'faqs-overview':
require 'faqs.overview.php';
break;
case 'viewinactive':
case 'viewactive':
case 'view':
require 'record.show.php';
break;
case 'searchfaqs':
require 'record.search.php';
break;
case 'takequestion':
case 'editentry':
case 'copyentry':
case 'editpreview':
require 'record.edit.php';
break;
case 'insertentry':
require 'record.add.php';
break;
case 'saveentry':
require 'record.save.php';
break;
case 'delatt':
require 'record.delatt.php';
break;
case 'question':
require 'record.questions.php';
break;
case 'comments':
require 'record.comments.php';
break;
// functions for tags
case 'tags':
case 'delete-tag':
require 'tags.php';
break;
// news administration
case 'news':
case 'add-news':
case 'edit-news':
case 'save-news':
case 'update-news':
case 'delete-news':
require 'news.php';
break;
// category administration
case 'content':
case 'category':
case 'savecategory':
case 'updatecategory':
case 'checkIfCategoryExists':
case 'removecategory':
case 'changecategory':
case 'pastecategory':
require 'category.main.php';
break;
case 'addcategory':
require 'category.add.php';
break;
case 'editcategory':
require 'category.edit.php';
break;
case 'translatecategory':
require 'category.translate.php';
break;
case 'deletecategory':
require 'category.delete.php';
break;
case 'cutcategory':
require 'category.cut.php';
break;
case 'movecategory':
require 'category.move.php';
break;
case 'showcategory':
require 'category.showstructure.php';
break;
// glossary
case 'glossary':
case 'saveglossary':
case 'updateglossary':
case 'deleteglossary':
require 'glossary.main.php';
break;
case 'addglossary':
require 'glossary.add.php';
break;
case 'editglossary':
require 'glossary.edit.php';
break;
// functions for password administration
case 'passwd':
require 'pwd.change.php';
break;
// functions for session administration
case 'adminlog':
case 'deleteadminlog':
require 'stat.adminlog.php';
break;
case 'viewsessions':
case 'clear-visits':
require 'stat.main.php';
break;
case 'sessionbrowse':
require 'stat.browser.php';
break;
case 'viewsession':
require 'statistics.show.php';
break;
case 'clear-statistics':
case 'statistics':
require 'stat.ratings.php';
break;
case 'truncatesearchterms':
case 'searchstats':
require 'stat.search.php';
break;
// Reports
case 'reports':
require 'report.main.php';
break;
case 'reportview':
require 'report.view.php';
break;
// Config administration
case 'config':
require 'configuration.php';
break;
case 'system':
require 'system.php';
break;
case 'updateinstance':
case 'instances':
require 'instances.php';
break;
case 'editinstance':
require 'instances.edit.php';
break;
case 'stopwordsconfig':
require 'stopwords.php';
break;
case 'elasticsearch':
require 'elasticsearch.php';
break;
case 'meta':
case 'meta.update';
require 'meta.php';
break;
case 'meta.edit':
require 'meta.edit.php';
break;
// functions for backup administration
case 'backup':
require 'backup.main.php';
break;
case 'restore':
require 'backup.import.php';
break;
// functions for FAQ export
case 'export':
require 'export.main.php';
break;
// attachment administration
case 'attachments':
require 'attachments.php';
break;
default:
echo 'Dave, this conversation can serve no purpose anymore. Goodbye.';
break;
}
} else {
require 'dashboard.php';
}
// User is authenticated, but has no rights
} elseif (isset($auth) && $numRights === 0) {
require 'noperm.php';
// User is NOT authenticated
} else {
require 'loginform.php';
}
require 'footer.php';
$faqConfig->getDb()->close();
|
1d73af34bf42764f9f9491c7ba5e9495d70e3ca5
|
https://github.com/thorsten/phpmyfaq
|
constants.js
|
javascript
|
var pythonMirror = process.env.npm_config_python_mirror || process.env.PYTHON_MIRROR || 'https://www.python.org/ftp/python/'
var buildTools = {
installerName: 'BuildTools_Full.exe',
installerUrl: 'http://download.microsoft.com/download/5/f/7/5f7acaeb-8363-451f-9425-68a90f98b238/visualcppbuildtools_full.exe',
logName: 'build-tools-log.txt'
}
var python = {
installerName: 'python-2.7.11.msi',
installerUrl: pythonMirror.replace(/\/*$/, '/2.7.11/python-2.7.11.msi'),
targetName: 'python27',
logName: 'python-log.txt'
}
module.exports = {
buildTools,
python
}
|
var pythonMirror = process.env.npm_config_python_mirror || process.env.PYTHON_MIRROR || 'https://www.python.org/ftp/python/'
var buildTools = {
installerName: 'BuildTools_Full.exe',
installerUrl: 'https://download.microsoft.com/download/5/f/7/5f7acaeb-8363-451f-9425-68a90f98b238/visualcppbuildtools_full.exe',
logName: 'build-tools-log.txt'
}
var python = {
installerName: 'python-2.7.11.msi',
installerUrl: pythonMirror.replace(/\/*$/, '/2.7.11/python-2.7.11.msi'),
targetName: 'python27',
logName: 'python-log.txt'
}
module.exports = {
buildTools,
python
}
|
9835d33e68f2cb5e4d148e954bb3ed0221d98e90
|
https://github.com/felixrieseberg/windows-build-tools
|
index.php
|
php
|
<!DOCTYPE html>
<html itemscope itemtype="http://schema.org/Webpage">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="description" content="Search Anime by ScreenShot. Search over 500 million images to lookup what anime, which episode, which moment the screenshot is taken from.">
<meta name="keywords" content="Anime Scene Search, Search by image, Anime Image Search, アニメのキャプ画像">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=995, initial-scale=1">
<title>WAIT: What Anime Is This? - Anime Scene Search Engine</title>
<!-- Schema.org markup (Google) -->
<meta itemprop="name" content="WAIT: What Anime Is This?">
<meta itemprop="description" content="Anime Scene Search Engine. Search over 500 million images to lookup what anime, which episode, which moment the screenshot is taken from.">
<meta itemprop="image" content="https://whatanime.ga/favicon128.png">
<!-- Twitter Card markup-->
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:site" content="@soruly">
<meta name="twitter:title" content="WAIT: What Anime Is This?">
<meta name="twitter:description" content="Anime Scene Search Engine. Search over 500 million images to lookup what anime, which episode, which moment the screenshot is taken from.">
<meta name="twitter:creator" content="@soruly">
<!-- Twitter summary card with large image must be at least 280x150px -->
<meta name="twitter:image" content="https://whatanime.ga/favicon128.png">
<meta name="twitter:image:alt" content="Anime Scene Search Engine. Search over 500 million images to lookup what anime, which episode, which moment the screenshot is taken from.">
<!-- Open Graph markup (Facebook, Pinterest) -->
<meta property="og:title" content="WAIT: What Anime Is This?" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://whatanime.ga" />
<meta property="og:image" content="https://whatanime.ga/favicon128.png" />
<meta property="og:description" content="Anime Scene Search Engine. Search over 500 million images to lookup what anime, which episode, which moment the screenshot is taken from." />
<meta property="og:site_name" content="whatanime.ga" />
<link rel="icon" type="image/png" href="/favicon.png">
<link rel="icon" type="image/png" href="/favicon128.png" sizes="128x128">
<link href="/css/bootstrap.min.css" rel="stylesheet">
<link href="/style.css" rel="stylesheet">
<link href="/index.css" rel="stylesheet">
<link rel="dns-prefetch" href="https://image.whatanime.ga/">
<script src="/recaptcha.js" defer></script>
<script src="/analytics.js" defer></script>
</head>
<body>
<!--<div class="alert alert-warning">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<strong>Scheduled Maintenance</strong> A server maintenance will be carried out on 22 Mar, 2016 01:30-09:30am (UTC)
</div>-->
<input id="autoSearch" type="checkbox" style="display: none;">
<img id="originalImage" src="" crossorigin="anonymous" style="display: none;">
<div class="row">
<div class="col-xs-8">
<div id="main">
<div class="noselect">
<div id="loading" class="hidden">
<span class="glyphicon glyphicon-repeat spinning"></span>
</div>
<canvas id="preview" width="640" height="360"></canvas>
<video id="player" style="display:none" volume="1" autoplay></video>
</div>
<form action="" method="get">
<span class="btn btn-default btn-file btn-sm">
Browse a file <input type="file" id="file" name="files[]" />
</span>
<span id="instruction"> / Drag & Drop Anime ScreenShot / Ctrl+V / Enter Image URL</span>
<br>
<input type="text" class="form-control" id="imageURL" placeholder="Image URL" style="margin:5px 0 5px 0">
<div style="text-align: right">
<span id="messageText" style="float:left;line-height:30px"></span>
<label class="radio-inline"><input type="radio" name="fitRadio" id="fitWidthRadio" checked>Fit Width</label>
<label class="radio-inline" style="margin-right:10px"><input type="radio" name="fitRadio" id="fitHeightRadio">Fit Height</label>
<button id="flipBtn" type="button" class="btn btn-default btn-sm" disabled>
<span class="glyphicon glyphicon-unchecked"></span> Flip Image
</button>
<button id="safeBtn" type="button" class="btn btn-default btn-sm">
<span class="glyphicon glyphicon-unchecked"></span> Safe Search
</button>
<button id="searchBtn" type="button" class="btn btn-default btn-sm btn-primary" disabled>
<span class="glyphicon glyphicon-search"></span> Search
</button>
</div>
Please read <a href="/faq">FAQ</a> to understand what can / cannot be searched.<br>
<span style="color:#FF6D6D">Caution: some results may be NSFW (Not Safe for Work).</span><br>
Official WebExtension available on <a href="https://chrome.google.com/webstore/detail/search-anime-by-screensho/gkamnldpllcbiidlfacaccdoadedncfp" target="_blank">Chrome</a>, <a href="https://addons.mozilla.org/en-US/firefox/addon/search-anime-by-screenshot/" target="_blank">Firefox</a>, and <a href="https://addons.opera.com/en/extensions/details/search-anime-by-screenshot/" target="_blank">Opera</a>.<br>
Official Telegram Bot available <a href="https://telegram.me/WhatAnimeBot">@WhatAnimeBot</a><br>
</form>
</div>
<div id="info"></div>
<br>
</div>
<div class="col-xs-4">
<div id="results-list">
<div id="controls" class="checkbox">
<label><input type="checkbox" id="autoplay" name="autoplay" checked />AutoPlay</label>
<label><input type="checkbox" id="loop" name="loop" />Loop</label>
<label><input type="checkbox" id="mute" name="mute" />Mute</label>
</div>
<div class="g-recaptcha hidden" data-sitekey="6LdluhITAAAAAD4-wl-hL-gR6gxesY6b4_SZew7v" data-callback="recaptcha_success" data-size="normal"></div>
<ul id="results" class="nav nav-pills nav-stacked"></ul>
</div>
</div>
<a href="https://github.com/soruly/whatanime.ga" class="github-corner" aria-label="View source on Github">
<svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg>
</a>
<style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
<footer class="footer">
<div class="container">
<ol class="breadcrumb">
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
<li><a href="/changelog">Changelog</a></li>
<li><a href="/faq">FAQ</a></li>
<li><a href="/terms" class="active">Terms</a></li>
</ol>
</div>
</footer>
<script src="/jquery-2.1.1.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
<script src="/jquery.html5uploader.min.js"></script>
<script src="/index.js"></script>
<?php
if(isset($_GET["url"])){
echo '<script>
document.querySelector("#autoSearch").checked = true;
document.querySelector("#messageText").classList.remove("error");
document.querySelector("#messageText").classList.remove("success");
document.querySelector("#messageText").innerHTML = \'<span class="glyphicon glyphicon-repeat spinning"></span>\';
originalImage.src = "https://image.whatanime.ga/imgproxy?url='.str_replace(' ','%20',rawurldecode($_GET["url"])).'";
document.querySelector("#imageURL").value = "'.str_replace(' ','%20',rawurldecode($_GET["url"])).'";
</script>';
}
?>
</body>
</html>
|
<!DOCTYPE html>
<html itemscope itemtype="http://schema.org/Webpage">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="description" content="Search Anime by ScreenShot. Search over 500 million images to lookup what anime, which episode, which moment the screenshot is taken from.">
<meta name="keywords" content="Anime Scene Search, Search by image, Anime Image Search, アニメのキャプ画像">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=995, initial-scale=1">
<title>WAIT: What Anime Is This? - Anime Scene Search Engine</title>
<!-- Schema.org markup (Google) -->
<meta itemprop="name" content="WAIT: What Anime Is This?">
<meta itemprop="description" content="Anime Scene Search Engine. Search over 500 million images to lookup what anime, which episode, which moment the screenshot is taken from.">
<meta itemprop="image" content="https://whatanime.ga/favicon128.png">
<!-- Twitter Card markup-->
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:site" content="@soruly">
<meta name="twitter:title" content="WAIT: What Anime Is This?">
<meta name="twitter:description" content="Anime Scene Search Engine. Search over 500 million images to lookup what anime, which episode, which moment the screenshot is taken from.">
<meta name="twitter:creator" content="@soruly">
<!-- Twitter summary card with large image must be at least 280x150px -->
<meta name="twitter:image" content="https://whatanime.ga/favicon128.png">
<meta name="twitter:image:alt" content="Anime Scene Search Engine. Search over 500 million images to lookup what anime, which episode, which moment the screenshot is taken from.">
<!-- Open Graph markup (Facebook, Pinterest) -->
<meta property="og:title" content="WAIT: What Anime Is This?" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://whatanime.ga" />
<meta property="og:image" content="https://whatanime.ga/favicon128.png" />
<meta property="og:description" content="Anime Scene Search Engine. Search over 500 million images to lookup what anime, which episode, which moment the screenshot is taken from." />
<meta property="og:site_name" content="whatanime.ga" />
<link rel="icon" type="image/png" href="/favicon.png">
<link rel="icon" type="image/png" href="/favicon128.png" sizes="128x128">
<link href="/css/bootstrap.min.css" rel="stylesheet">
<link href="/style.css" rel="stylesheet">
<link href="/index.css" rel="stylesheet">
<link rel="dns-prefetch" href="https://image.whatanime.ga/">
<script src="/recaptcha.js" defer></script>
<script src="/analytics.js" defer></script>
</head>
<body>
<!--<div class="alert alert-warning">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<strong>Scheduled Maintenance</strong> A server maintenance will be carried out on 22 Mar, 2016 01:30-09:30am (UTC)
</div>-->
<input id="autoSearch" type="checkbox" style="display: none;">
<img id="originalImage" src="" crossorigin="anonymous" style="display: none;">
<div class="row">
<div class="col-xs-8">
<div id="main">
<div class="noselect">
<div id="loading" class="hidden">
<span class="glyphicon glyphicon-repeat spinning"></span>
</div>
<canvas id="preview" width="640" height="360"></canvas>
<video id="player" style="display:none" volume="1" autoplay></video>
</div>
<form action="" method="get">
<span class="btn btn-default btn-file btn-sm">
Browse a file <input type="file" id="file" name="files[]" />
</span>
<span id="instruction"> / Drag & Drop Anime ScreenShot / Ctrl+V / Enter Image URL</span>
<br>
<input type="text" class="form-control" id="imageURL" placeholder="Image URL" style="margin:5px 0 5px 0">
<div style="text-align: right">
<span id="messageText" style="float:left;line-height:30px"></span>
<label class="radio-inline"><input type="radio" name="fitRadio" id="fitWidthRadio" checked>Fit Width</label>
<label class="radio-inline" style="margin-right:10px"><input type="radio" name="fitRadio" id="fitHeightRadio">Fit Height</label>
<button id="flipBtn" type="button" class="btn btn-default btn-sm" disabled>
<span class="glyphicon glyphicon-unchecked"></span> Flip Image
</button>
<button id="safeBtn" type="button" class="btn btn-default btn-sm">
<span class="glyphicon glyphicon-unchecked"></span> Safe Search
</button>
<button id="searchBtn" type="button" class="btn btn-default btn-sm btn-primary" disabled>
<span class="glyphicon glyphicon-search"></span> Search
</button>
</div>
Please read <a href="/faq">FAQ</a> to understand what can / cannot be searched.<br>
<span style="color:#FF6D6D">Caution: some results may be NSFW (Not Safe for Work).</span><br>
Official WebExtension available on <a href="https://chrome.google.com/webstore/detail/search-anime-by-screensho/gkamnldpllcbiidlfacaccdoadedncfp" target="_blank">Chrome</a>, <a href="https://addons.mozilla.org/en-US/firefox/addon/search-anime-by-screenshot/" target="_blank">Firefox</a>, and <a href="https://addons.opera.com/en/extensions/details/search-anime-by-screenshot/" target="_blank">Opera</a>.<br>
Official Telegram Bot available <a href="https://telegram.me/WhatAnimeBot">@WhatAnimeBot</a><br>
</form>
</div>
<div id="info"></div>
<br>
</div>
<div class="col-xs-4">
<div id="results-list">
<div id="controls" class="checkbox">
<label><input type="checkbox" id="autoplay" name="autoplay" checked />AutoPlay</label>
<label><input type="checkbox" id="loop" name="loop" />Loop</label>
<label><input type="checkbox" id="mute" name="mute" />Mute</label>
</div>
<div class="g-recaptcha hidden" data-sitekey="6LdluhITAAAAAD4-wl-hL-gR6gxesY6b4_SZew7v" data-callback="recaptcha_success" data-size="normal"></div>
<ul id="results" class="nav nav-pills nav-stacked"></ul>
</div>
</div>
<a href="https://github.com/soruly/whatanime.ga" class="github-corner" aria-label="View source on Github">
<svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg>
</a>
<style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
<footer class="footer">
<div class="container">
<ol class="breadcrumb">
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
<li><a href="/changelog">Changelog</a></li>
<li><a href="/faq">FAQ</a></li>
<li><a href="/terms" class="active">Terms</a></li>
</ol>
</div>
</footer>
<script src="/jquery-2.1.1.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
<script src="/jquery.html5uploader.min.js"></script>
<script src="/index.js"></script>
<?php
if(isset($_GET["url"]) && filter_var($_GET["url"], FILTER_VALIDATE_URL)){
echo '<script>
document.querySelector("#autoSearch").checked = true;
document.querySelector("#messageText").classList.remove("error");
document.querySelector("#messageText").classList.remove("success");
document.querySelector("#messageText").innerHTML = \'<span class="glyphicon glyphicon-repeat spinning"></span>\';
originalImage.src = "https://image.whatanime.ga/imgproxy?url='.str_replace(' ','%20',rawurldecode($_GET["url"])).'";
document.querySelector("#imageURL").value = "'.str_replace(' ','%20',rawurldecode($_GET["url"])).'";
</script>';
}
?>
</body>
</html>
|
c334dd8499a681587dd4199e90b0aa0eba814c1d
|
https://github.com/soruly/whatanime.ga
|
base.py
|
python
|
"""
Django settings for nsupdate project
Note: do not directly use these settings, rather use "dev" or "prod".
"""
# Note: django internally first loads its own defaults and then loads the
# project's settings on top of that. Due to this, no import * is required here.
import os
# To make this work, put a unique, long, random, secret string into your environment.
# E.g. in ~/.bashrc: export SECRET_KEY="..."
try:
SECRET_KEY = os.environ['SECRET_KEY']
except KeyError:
# if there is no SECRET_KEY in the environment, it will be just undefined and
# Django will refuse running - except if you define it somehow else later (e.g. in
# a local_settings.py file that imports this file).
pass
# service contact for showing on the "about" page:
SERVICE_CONTACT = 'your_email AT example DOT com'
# sender address for e.g. user activation emails
DEFAULT_FROM_EMAIL = "your_email@example.com"
# admins will get traceback emails
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'nsupdate.sqlite', # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': '',
'PASSWORD': '',
'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '' # Set to empty string for default.
}
}
# these useragents are unacceptable for /nic/update service
BAD_AGENTS = set([]) # list can have str elements
# these IPAdresses and/or IPNetworks are unacceptable for /nic/update service
# like e.g. IPs of servers related to illegal activities
from netaddr import IPSet, IPAddress, IPNetwork
BAD_IPS_HOST = IPSet([]) # inner list can have IPAddress and IPNetwork elements
# when encountering these hostnames (fqdn), block them early/silently from
# api usage. avoid any database access, so if someone tries to update
# every 5s, the database won't be locked all the time and we can at least
# delete the host from django admin.
BAD_HOSTS = set([])
# nameservers used e.g. for MX lookups in the registration email validation.
# google / cloudflare DNS IPs are only given as example / fallback -
# please configure your own nameservers in your local settings file.
NAMESERVERS = ['8.8.8.8', '1.1.1.1', ]
# registration email validation: disallow specific email domains,
# e.g. domains that have a non-working mx / that are frequently abused.
# we use a multiline string here with one regex per line (used with re.search).
# the domains given below are just examples, please configure your own
# regexes in your local settings file.
MAILDOMAIN_BLACKLIST = r"""
mailcatch\.com$
mailspam\.xyz$
"""
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'Europe/Berlin'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = ''
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
# STATIC_ROOT = "/srv/nsupdate.info/htdocs/static"
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
# '/where/you/have/additional/templates',
],
'OPTIONS': {
'context_processors': [
# Insert your TEMPLATE_CONTEXT_PROCESSORS here or use this
# list if you haven't customized them:
# 'django.contrib.auth.context_processors.auth',
# 'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'nsupdate.context_processors.add_settings',
'nsupdate.context_processors.update_ips',
# 'django.template.context_processors.media',
# 'django.template.context_processors.static',
# 'django.template.context_processors.tz',
# 'django.contrib.messages.context_processors.messages',
'social_django.context_processors.backends',
'social_django.context_processors.login_redirect',
],
'loaders': [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
],
},
},
]
MIDDLEWARE = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django_referrer_policy.middleware.ReferrerPolicyMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'social_django.middleware.SocialAuthExceptionMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'nsupdate.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'nsupdate.wsgi.application'
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'social_django',
'nsupdate.login',
'nsupdate',
'nsupdate.accounts',
'nsupdate.api',
'nsupdate.main',
'bootstrapform',
'django.contrib.admin',
'registration',
'django_extensions',
)
# A sample logging configuration.
# Sends an email to the site admins on every HTTP 500 error when DEBUG=False.
# Do some stderr logging for some views.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
},
'stderr': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'stderr'
},
'stderr_request': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'stderr_request'
}
},
'loggers': {
'nsupdate.api.views': {
'handlers': ['stderr_request', ],
'level': 'DEBUG',
'propagate': True,
},
'nsupdate.main.views': {
'handlers': ['stderr_request', ],
'level': 'DEBUG',
'propagate': True,
},
'nsupdate.main.dnstools': {
'handlers': ['stderr', ],
'level': 'DEBUG',
'propagate': True,
},
# this is the toplevel handler for all request processing:
'django.request': {
'handlers': ['mail_admins', 'stderr'],
'level': 'ERROR',
'propagate': True,
},
},
'formatters': {
'stderr': {
'format': '[%(asctime)s] %(levelname)s %(message)s',
},
'stderr_request': {
'format': '[%(asctime)s] %(levelname)s %(message)s '
'[ip: %(request.META.REMOTE_ADDR)s, ua: "%(request.META.HTTP_USER_AGENT)s"]',
},
},
}
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
ACCOUNT_ACTIVATION_DAYS = 7
REGISTRATION_EMAIL_HTML = False # we override the text, but not the html email template
REGISTRATION_FORM = 'nsupdate.accounts.registration_form.RegistrationFormValidateEmail'
LOGIN_REDIRECT_URL = '/overview/'
LOGOUT_REDIRECT_URL = '/'
X_FRAME_OPTIONS = 'DENY' # for clickjacking middleware
SECURE_BROWSER_XSS_FILTER = True
SECURE_CONTENT_TYPE_NOSNIFF = True
REFERRER_POLICY = 'same-origin'
CSRF_FAILURE_VIEW = 'nsupdate.main.views.csrf_failure_view'
# Settings for CSRF cookie.
CSRF_COOKIE_NAME = 'csrftoken'
CSRF_COOKIE_PATH = '/'
CSRF_COOKIE_HTTPONLY = False
# Settings for session cookie.
SESSION_COOKIE_NAME = 'sessionid'
SESSION_COOKIE_PATH = '/'
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_AGE = 10 * 60 * 60 # 10 hours, in seconds (remember_me is True), see #381
SESSION_EXPIRE_AT_BROWSER_CLOSE = True # more safe (remember_me is False)
# Allow SHA1 for host update secrets
PASSWORD_HASHERS = [
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
'django.contrib.auth.hashers.Argon2PasswordHasher',
'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
'django.contrib.auth.hashers.BCryptPasswordHasher',
'django.contrib.auth.hashers.SHA1PasswordHasher',
]
# python-social-auth settings
AUTHENTICATION_BACKENDS = (
'social_core.backends.amazon.AmazonOAuth2',
'social_core.backends.bitbucket.BitbucketOAuth',
'social_core.backends.disqus.DisqusOAuth2',
'social_core.backends.dropbox.DropboxOAuth',
'social_core.backends.github.GithubOAuth2',
'social_core.backends.google.GoogleOAuth2',
'social_core.backends.reddit.RedditOAuth2',
'social_core.backends.soundcloud.SoundcloudOAuth2',
'social_core.backends.stackoverflow.StackoverflowOAuth2',
'social_core.backends.twitter.TwitterOAuth',
'django.contrib.auth.backends.ModelBackend',
)
SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/'
# Used to redirect the user once the auth process ended successfully.
# The value of ?next=/foo is used if it was present
SOCIAL_AUTH_LOGIN_ERROR_URL = '/accounts/login/'
# URL where the user will be redirected in case of an error
SOCIAL_AUTH_LOGIN_URL = '/accounts/login/'
# Is used as a fallback for LOGIN_ERROR_URL (if it is not defined).
# SOCIAL_AUTH_NEW_USER_REDIRECT_URL = '/new-users-redirect-url/'
# Used to redirect new registered users, will be used in place of SOCIAL_AUTH_LOGIN_REDIRECT_URL if defined.
SOCIAL_AUTH_NEW_ASSOCIATION_REDIRECT_URL = '/account/profile/'
# Like SOCIAL_AUTH_NEW_USER_REDIRECT_URL but for new associated accounts (user is already logged in).
# Used in place of SOCIAL_AUTH_LOGIN_REDIRECT_URL.
SOCIAL_AUTH_DISCONNECT_REDIRECT_URL = '/account/profile'
# The user will be redirected to this URL when a social account is disconnected
SOCIAL_AUTH_INACTIVE_USER_URL = '/'
# Inactive users can be redirected to this URL when trying to authenticate.
# SOCIAL_AUTH_USER_MODEL = 'foo.bar.User'
# User model must have a username and email field, these are required.
# Also an is_authenticated and is_active boolean flags are recommended, these can be methods if necessary (must
# return True or False). If the model lacks them a True value is assumed.
# SOCIAL_AUTH_UID_LENGTH = <int>
# Used to define the max length of the field uid. A value of 223 should work when using MySQL InnoDB which impose
# a 767 bytes limit (assuming UTF-8 encoding).
# SOCIAL_AUTH_NONCE_SERVER_URL_LENGTH = <int>
# Nonce model has a unique constraint over ('server_url', 'timestamp', 'salt'), salt has a max length of 40, so
# server_url length must be tweaked using this setting.
# SOCIAL_AUTH_ASSOCIATION_SERVER_URL_LENGTH = <int> or SOCIAL_AUTH_ASSOCIATION_HANDLE_LENGTH = <int>
# Association model has a unique constraint over ('server_url', 'handle'), both fields lengths can be tweaked by
# these settings.
SOCIAL_AUTH_DEFAULT_USERNAME = 'user'
# Default value to use as username, can be a callable. An UUID will be appended in case of duplicate entries.
SOCIAL_AUTH_UUID_LENGTH = 16
# This controls the length of the UUID appended to usernames.
SOCIAL_AUTH_USERNAME_IS_FULL_EMAIL = True
# If you want to use the full email address as the username, define this setting.
# SOCIAL_AUTH_SLUGIFY_USERNAMES = False
# For those that prefer slugged usernames, the get_username pipeline can apply a slug transformation (code borrowed
# from Django project) by defining this setting to True. The feature is disabled by default to to not force this
# option to all projects.
# SOCIAL_AUTH_CLEAN_USERNAMES = True
# By default the regex r'[^\w.@+-_]+' is applied over usernames to clean them from usual undesired characters like
# spaces. Set this setting to False to disable this behavior.
# SOCIAL_AUTH_SANITIZE_REDIRECTS = False
# The auth process finishes with a redirect, by default it's done to the value of SOCIAL_AUTH_LOGIN_REDIRECT_URL
# but can be overridden with next GET argument. If this settings is True, this application will verify the domain of
# the final URL and only redirect to it if it's on the same domain.
# SOCIAL_AUTH_REDIRECT_IS_HTTPS = False
# On projects behind a reverse proxy that uses HTTPS, the redirect URIs can became with the wrong schema
# (http:// instead of https://) when the request lacks some headers, and might cause errors with the auth process,
# to force HTTPS in the final URIs set this setting to True
# SOCIAL_AUTH_URLOPEN_TIMEOUT = 30
# Any urllib2.urlopen call will be performed with the default timeout value, to change it without affecting the
# global socket timeout define this setting (the value specifies timeout seconds).
# urllib2.urlopen uses socket.getdefaulttimeout() value by default, so setting socket.setdefaulttimeout(...) will
# affect urlopen when this setting is not defined, otherwise this setting takes precedence. Also this might affect
# other places in Django.
# timeout argument was introduced in python 2.6 according to urllib2 documentation
# SOCIAL_AUTH_<BACKEND_NAME>_WHITELISTED_DOMAINS = ['foo.com', 'bar.com']
# Supply a list of domain names to be white-listed. Any user with an email address on any of the allowed domains will
# login successfully, otherwise AuthForbidden is raised.
# SOCIAL_AUTH_<BACKEND_NAME>_WHITELISTED_EMAILS = ['me@foo.com', 'you@bar.com']
# Supply a list of email addresses to be white-listed. Any user with an email address in this list will login
# successfully, otherwise AuthForbidden is raised.
# SOCIAL_AUTH_PROTECTED_USER_FIELDS = ['email', ]
# The user_details pipeline processor will set certain fields on user objects, such as email. Set this to a list of
# fields you only want to set for newly created users and avoid updating on further logins.
# SOCIAL_AUTH_SESSION_EXPIRATION = True
# Some providers return the time that the access token will live, the value is stored in UserSocialAuth.extra_data
# under the key expires. By default the current user session is set to expire if this value is present, this
# behavior can be disabled by setting.
# SOCIAL_AUTH_OPENID_PAPE_MAX_AUTH_AGE = <int value>
# Enable OpenID PAPE extension support by defining this setting.
# SOCIAL_AUTH_FIELDS_STORED_IN_SESSION = ['foo', ]
# If you want to store extra parameters from POST or GET in session, like it was made for next parameter, define
# this setting with the parameter names.
# In this case foo field's value will be stored when user follows this link
# <a href="{% url socialauth_begin 'github' %}?foo=bar">...</a>.
# we need slightly different classes for bootstrap3 than the default ones
from django.contrib.messages import constants
MESSAGE_TAGS = {
constants.DEBUG: '',
constants.INFO: 'alert-info',
constants.SUCCESS: 'alert-success',
constants.WARNING: 'alert-warning',
constants.ERROR: 'alert-danger',
}
# translations - for details, see:
# https://docs.djangoproject.com/en/dev/topics/i18n/translation/#message-files and
# https://docs.djangoproject.com/en/dev/topics/i18n/translation/#how-django-discovers-language-preference
# By default language is set to english - modify settings.py to set list of languages
gettext_noop = lambda s: s
LANGUAGES = (
('en', gettext_noop('English')),
('de', gettext_noop('German')),
('el', gettext_noop('Greek')),
('fr', gettext_noop('French')),
('it', gettext_noop('Italian')),
# ('es', gettext_noop('Spanish')),
# ('zh-cn', gettext_noop('Chinese (China)')),
)
# silences 1_6.W001 warning you get without this:
TEST_RUNNER = 'django.test.runner.DiscoverRunner'
|
"""
Django settings for nsupdate project
Note: do not directly use these settings, rather use "dev" or "prod".
"""
# Note: django internally first loads its own defaults and then loads the
# project's settings on top of that. Due to this, no import * is required here.
import os
# To make this work, put a unique, long, random, secret string into your environment.
# E.g. in ~/.bashrc: export SECRET_KEY="..."
try:
SECRET_KEY = os.environ['SECRET_KEY']
except KeyError:
# if there is no SECRET_KEY in the environment, it will be just undefined and
# Django will refuse running - except if you define it somehow else later (e.g. in
# a local_settings.py file that imports this file).
pass
# service contact for showing on the "about" page:
SERVICE_CONTACT = 'your_email AT example DOT com'
# sender address for e.g. user activation emails
DEFAULT_FROM_EMAIL = "your_email@example.com"
# admins will get traceback emails
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'nsupdate.sqlite', # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': '',
'PASSWORD': '',
'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '' # Set to empty string for default.
}
}
# these useragents are unacceptable for /nic/update service
BAD_AGENTS = set([]) # list can have str elements
# these IPAdresses and/or IPNetworks are unacceptable for /nic/update service
# like e.g. IPs of servers related to illegal activities
from netaddr import IPSet, IPAddress, IPNetwork
BAD_IPS_HOST = IPSet([]) # inner list can have IPAddress and IPNetwork elements
# when encountering these hostnames (fqdn), block them early/silently from
# api usage. avoid any database access, so if someone tries to update
# every 5s, the database won't be locked all the time and we can at least
# delete the host from django admin.
BAD_HOSTS = set([])
# nameservers used e.g. for MX lookups in the registration email validation.
# google / cloudflare DNS IPs are only given as example / fallback -
# please configure your own nameservers in your local settings file.
NAMESERVERS = ['8.8.8.8', '1.1.1.1', ]
# registration email validation: disallow specific email domains,
# e.g. domains that have a non-working mx / that are frequently abused.
# we use a multiline string here with one regex per line (used with re.search).
# the domains given below are just examples, please configure your own
# regexes in your local settings file.
MAILDOMAIN_BLACKLIST = r"""
mailcatch\.com$
mailspam\.xyz$
"""
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'Europe/Berlin'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = ''
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
# STATIC_ROOT = "/srv/nsupdate.info/htdocs/static"
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
# '/where/you/have/additional/templates',
],
'OPTIONS': {
'context_processors': [
# Insert your TEMPLATE_CONTEXT_PROCESSORS here or use this
# list if you haven't customized them:
# 'django.contrib.auth.context_processors.auth',
# 'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'nsupdate.context_processors.add_settings',
'nsupdate.context_processors.update_ips',
# 'django.template.context_processors.media',
# 'django.template.context_processors.static',
# 'django.template.context_processors.tz',
# 'django.contrib.messages.context_processors.messages',
'social_django.context_processors.backends',
'social_django.context_processors.login_redirect',
],
'loaders': [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
],
},
},
]
MIDDLEWARE = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django_referrer_policy.middleware.ReferrerPolicyMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'social_django.middleware.SocialAuthExceptionMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'nsupdate.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'nsupdate.wsgi.application'
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'social_django',
'nsupdate.login',
'nsupdate',
'nsupdate.accounts',
'nsupdate.api',
'nsupdate.main',
'bootstrapform',
'django.contrib.admin',
'registration',
'django_extensions',
)
# A sample logging configuration.
# Sends an email to the site admins on every HTTP 500 error when DEBUG=False.
# Do some stderr logging for some views.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
},
'stderr': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'stderr'
},
'stderr_request': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'stderr_request'
}
},
'loggers': {
'nsupdate.api.views': {
'handlers': ['stderr_request', ],
'level': 'DEBUG',
'propagate': True,
},
'nsupdate.main.views': {
'handlers': ['stderr_request', ],
'level': 'DEBUG',
'propagate': True,
},
'nsupdate.main.dnstools': {
'handlers': ['stderr', ],
'level': 'DEBUG',
'propagate': True,
},
# this is the toplevel handler for all request processing:
'django.request': {
'handlers': ['mail_admins', 'stderr'],
'level': 'ERROR',
'propagate': True,
},
},
'formatters': {
'stderr': {
'format': '[%(asctime)s] %(levelname)s %(message)s',
},
'stderr_request': {
'format': '[%(asctime)s] %(levelname)s %(message)s '
'[ip: %(request.META.REMOTE_ADDR)s, ua: "%(request.META.HTTP_USER_AGENT)s"]',
},
},
}
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
ACCOUNT_ACTIVATION_DAYS = 7
REGISTRATION_EMAIL_HTML = False # we override the text, but not the html email template
REGISTRATION_FORM = 'nsupdate.accounts.registration_form.RegistrationFormValidateEmail'
LOGIN_REDIRECT_URL = '/overview/'
LOGOUT_REDIRECT_URL = '/'
X_FRAME_OPTIONS = 'DENY' # for clickjacking middleware
SECURE_BROWSER_XSS_FILTER = True
SECURE_CONTENT_TYPE_NOSNIFF = True
REFERRER_POLICY = 'same-origin'
CSRF_FAILURE_VIEW = 'nsupdate.main.views.csrf_failure_view'
# Settings for CSRF cookie.
CSRF_COOKIE_NAME = 'csrftoken'
CSRF_COOKIE_PATH = '/'
CSRF_COOKIE_HTTPONLY = True
# Settings for session cookie.
SESSION_COOKIE_NAME = 'sessionid'
SESSION_COOKIE_PATH = '/'
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_AGE = 10 * 60 * 60 # 10 hours, in seconds (remember_me is True), see #381
SESSION_EXPIRE_AT_BROWSER_CLOSE = True # more safe (remember_me is False)
# Allow SHA1 for host update secrets
PASSWORD_HASHERS = [
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
'django.contrib.auth.hashers.Argon2PasswordHasher',
'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
'django.contrib.auth.hashers.BCryptPasswordHasher',
'django.contrib.auth.hashers.SHA1PasswordHasher',
]
# python-social-auth settings
AUTHENTICATION_BACKENDS = (
'social_core.backends.amazon.AmazonOAuth2',
'social_core.backends.bitbucket.BitbucketOAuth',
'social_core.backends.disqus.DisqusOAuth2',
'social_core.backends.dropbox.DropboxOAuth',
'social_core.backends.github.GithubOAuth2',
'social_core.backends.google.GoogleOAuth2',
'social_core.backends.reddit.RedditOAuth2',
'social_core.backends.soundcloud.SoundcloudOAuth2',
'social_core.backends.stackoverflow.StackoverflowOAuth2',
'social_core.backends.twitter.TwitterOAuth',
'django.contrib.auth.backends.ModelBackend',
)
SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/'
# Used to redirect the user once the auth process ended successfully.
# The value of ?next=/foo is used if it was present
SOCIAL_AUTH_LOGIN_ERROR_URL = '/accounts/login/'
# URL where the user will be redirected in case of an error
SOCIAL_AUTH_LOGIN_URL = '/accounts/login/'
# Is used as a fallback for LOGIN_ERROR_URL (if it is not defined).
# SOCIAL_AUTH_NEW_USER_REDIRECT_URL = '/new-users-redirect-url/'
# Used to redirect new registered users, will be used in place of SOCIAL_AUTH_LOGIN_REDIRECT_URL if defined.
SOCIAL_AUTH_NEW_ASSOCIATION_REDIRECT_URL = '/account/profile/'
# Like SOCIAL_AUTH_NEW_USER_REDIRECT_URL but for new associated accounts (user is already logged in).
# Used in place of SOCIAL_AUTH_LOGIN_REDIRECT_URL.
SOCIAL_AUTH_DISCONNECT_REDIRECT_URL = '/account/profile'
# The user will be redirected to this URL when a social account is disconnected
SOCIAL_AUTH_INACTIVE_USER_URL = '/'
# Inactive users can be redirected to this URL when trying to authenticate.
# SOCIAL_AUTH_USER_MODEL = 'foo.bar.User'
# User model must have a username and email field, these are required.
# Also an is_authenticated and is_active boolean flags are recommended, these can be methods if necessary (must
# return True or False). If the model lacks them a True value is assumed.
# SOCIAL_AUTH_UID_LENGTH = <int>
# Used to define the max length of the field uid. A value of 223 should work when using MySQL InnoDB which impose
# a 767 bytes limit (assuming UTF-8 encoding).
# SOCIAL_AUTH_NONCE_SERVER_URL_LENGTH = <int>
# Nonce model has a unique constraint over ('server_url', 'timestamp', 'salt'), salt has a max length of 40, so
# server_url length must be tweaked using this setting.
# SOCIAL_AUTH_ASSOCIATION_SERVER_URL_LENGTH = <int> or SOCIAL_AUTH_ASSOCIATION_HANDLE_LENGTH = <int>
# Association model has a unique constraint over ('server_url', 'handle'), both fields lengths can be tweaked by
# these settings.
SOCIAL_AUTH_DEFAULT_USERNAME = 'user'
# Default value to use as username, can be a callable. An UUID will be appended in case of duplicate entries.
SOCIAL_AUTH_UUID_LENGTH = 16
# This controls the length of the UUID appended to usernames.
SOCIAL_AUTH_USERNAME_IS_FULL_EMAIL = True
# If you want to use the full email address as the username, define this setting.
# SOCIAL_AUTH_SLUGIFY_USERNAMES = False
# For those that prefer slugged usernames, the get_username pipeline can apply a slug transformation (code borrowed
# from Django project) by defining this setting to True. The feature is disabled by default to to not force this
# option to all projects.
# SOCIAL_AUTH_CLEAN_USERNAMES = True
# By default the regex r'[^\w.@+-_]+' is applied over usernames to clean them from usual undesired characters like
# spaces. Set this setting to False to disable this behavior.
# SOCIAL_AUTH_SANITIZE_REDIRECTS = False
# The auth process finishes with a redirect, by default it's done to the value of SOCIAL_AUTH_LOGIN_REDIRECT_URL
# but can be overridden with next GET argument. If this settings is True, this application will verify the domain of
# the final URL and only redirect to it if it's on the same domain.
# SOCIAL_AUTH_REDIRECT_IS_HTTPS = False
# On projects behind a reverse proxy that uses HTTPS, the redirect URIs can became with the wrong schema
# (http:// instead of https://) when the request lacks some headers, and might cause errors with the auth process,
# to force HTTPS in the final URIs set this setting to True
# SOCIAL_AUTH_URLOPEN_TIMEOUT = 30
# Any urllib2.urlopen call will be performed with the default timeout value, to change it without affecting the
# global socket timeout define this setting (the value specifies timeout seconds).
# urllib2.urlopen uses socket.getdefaulttimeout() value by default, so setting socket.setdefaulttimeout(...) will
# affect urlopen when this setting is not defined, otherwise this setting takes precedence. Also this might affect
# other places in Django.
# timeout argument was introduced in python 2.6 according to urllib2 documentation
# SOCIAL_AUTH_<BACKEND_NAME>_WHITELISTED_DOMAINS = ['foo.com', 'bar.com']
# Supply a list of domain names to be white-listed. Any user with an email address on any of the allowed domains will
# login successfully, otherwise AuthForbidden is raised.
# SOCIAL_AUTH_<BACKEND_NAME>_WHITELISTED_EMAILS = ['me@foo.com', 'you@bar.com']
# Supply a list of email addresses to be white-listed. Any user with an email address in this list will login
# successfully, otherwise AuthForbidden is raised.
# SOCIAL_AUTH_PROTECTED_USER_FIELDS = ['email', ]
# The user_details pipeline processor will set certain fields on user objects, such as email. Set this to a list of
# fields you only want to set for newly created users and avoid updating on further logins.
# SOCIAL_AUTH_SESSION_EXPIRATION = True
# Some providers return the time that the access token will live, the value is stored in UserSocialAuth.extra_data
# under the key expires. By default the current user session is set to expire if this value is present, this
# behavior can be disabled by setting.
# SOCIAL_AUTH_OPENID_PAPE_MAX_AUTH_AGE = <int value>
# Enable OpenID PAPE extension support by defining this setting.
# SOCIAL_AUTH_FIELDS_STORED_IN_SESSION = ['foo', ]
# If you want to store extra parameters from POST or GET in session, like it was made for next parameter, define
# this setting with the parameter names.
# In this case foo field's value will be stored when user follows this link
# <a href="{% url socialauth_begin 'github' %}?foo=bar">...</a>.
# we need slightly different classes for bootstrap3 than the default ones
from django.contrib.messages import constants
MESSAGE_TAGS = {
constants.DEBUG: '',
constants.INFO: 'alert-info',
constants.SUCCESS: 'alert-success',
constants.WARNING: 'alert-warning',
constants.ERROR: 'alert-danger',
}
# translations - for details, see:
# https://docs.djangoproject.com/en/dev/topics/i18n/translation/#message-files and
# https://docs.djangoproject.com/en/dev/topics/i18n/translation/#how-django-discovers-language-preference
# By default language is set to english - modify settings.py to set list of languages
gettext_noop = lambda s: s
LANGUAGES = (
('en', gettext_noop('English')),
('de', gettext_noop('German')),
('el', gettext_noop('Greek')),
('fr', gettext_noop('French')),
('it', gettext_noop('Italian')),
# ('es', gettext_noop('Spanish')),
# ('zh-cn', gettext_noop('Chinese (China)')),
)
# silences 1_6.W001 warning you get without this:
TEST_RUNNER = 'django.test.runner.DiscoverRunner'
|
60a3fe559c453bc36b0ec3e5dd39c1303640a59a
|
https://github.com/nsupdate-info/nsupdate.info
|
index.php
|
php
|
<?php
session_start();
define('NO_AUTH_REQUIRED',true);
$TAB = 'RESET PASSWORD';
if (isset($_SESSION['user'])) {
header("Location: /list/user");
}
// Main include
include($_SERVER['DOCUMENT_ROOT']."/inc/main.php");
if ((!empty($_POST['user'])) && (empty($_POST['code']))) {
$v_user = escapeshellarg($_POST['user']);
$user = $_POST['user'];
$cmd="/usr/bin/sudo /usr/local/vesta/bin/v-list-user";
exec ($cmd." ".$v_user." json", $output, $return_var);
if ( $return_var == 0 ) {
$data = json_decode(implode('', $output), true);
$rkey = $data[$user]['RKEY'];
$fname = $data[$user]['FNAME'];
$lname = $data[$user]['LNAME'];
$contact = $data[$user]['CONTACT'];
$to = $data[$user]['CONTACT'];
$subject = __('MAIL_RESET_SUBJECT',date("Y-m-d H:i:s"));
$hostname = exec('hostname');
$from = __('MAIL_FROM',$hostname);
if (!empty($fname)) {
$mailtext = __('GREETINGS_GORDON_FREEMAN',$fname,$lname);
} else {
$mailtext = __('GREETINGS');
}
$mailtext .= __('PASSWORD_RESET_REQUEST',$_SERVER['HTTP_HOST'],$user,$rkey,$_SERVER['HTTP_HOST'],$user,$rkey);
if (!empty($rkey)) send_email($to, $subject, $mailtext, $from);
unset($output);
}
header("Location: /reset/?action=code&user=".$_POST['user']);
exit;
}
if ((!empty($_POST['user'])) && (!empty($_POST['code'])) && (!empty($_POST['password'])) ) {
if ( $_POST['password'] == $_POST['password_confirm'] ) {
$v_user = escapeshellarg($_POST['user']);
$user = $_POST['user'];
$cmd="/usr/bin/sudo /usr/local/vesta/bin/v-list-user";
exec ($cmd." ".$v_user." json", $output, $return_var);
if ( $return_var == 0 ) {
$data = json_decode(implode('', $output), true);
$rkey = $data[$user]['RKEY'];
if ($rkey == $_POST['code']) {
$v_password = tempnam("/tmp","vst");
$fp = fopen($v_password, "w");
fwrite($fp, $_POST['password']."\n");
fclose($fp);
$cmd="/usr/bin/sudo /usr/local/vesta/bin/v-change-user-password";
exec ($cmd." ".$v_user." ".$v_password, $output, $return_var);
unlink($v_password);
if ( $return_var > 0 ) {
$ERROR = "<a class=\"error\">".__('An internal error occurred')."</a>";
} else {
$_SESSION['user'] = $_POST['user'];
header("Location: /");
exit;
}
} else {
$ERROR = "<a class=\"error\">".__('Invalid username or code')."</a>";
}
} else {
$ERROR = "<a class=\"error\">".__('Invalid username or code')."</a>";
}
} else {
$ERROR = "<a class=\"error\">".__('Passwords not match')."</a>";
}
}
// Detect language
if (empty($_SESSION['language'])) $_SESSION['language'] = detect_user_language();
if (empty($_GET['action'])) {
require_once '../templates/header.html';
require_once '../templates/reset_1.html';
} else {
require_once '../templates/header.html';
if ($_GET['action'] == 'code' ) {
require_once '../templates/reset_2.html';
}
if (($_GET['action'] == 'confirm' ) && (!empty($_GET['code']))) {
require_once '../templates/reset_3.html';
}
}
?>
|
<?php
session_start();
define('NO_AUTH_REQUIRED',true);
$TAB = 'RESET PASSWORD';
if (isset($_SESSION['user'])) {
header("Location: /list/user");
}
// Main include
include($_SERVER['DOCUMENT_ROOT']."/inc/main.php");
if ((!empty($_POST['user'])) && (empty($_POST['code']))) {
$v_user = escapeshellarg($_POST['user']);
$user = $_POST['user'];
$cmd="/usr/bin/sudo /usr/local/vesta/bin/v-list-user";
exec ($cmd." ".$v_user." json", $output, $return_var);
if ( $return_var == 0 ) {
$data = json_decode(implode('', $output), true);
$rkey = $data[$user]['RKEY'];
$fname = $data[$user]['FNAME'];
$lname = $data[$user]['LNAME'];
$contact = $data[$user]['CONTACT'];
$to = $data[$user]['CONTACT'];
$subject = __('MAIL_RESET_SUBJECT',date("Y-m-d H:i:s"));
$hostname = exec('hostname');
$from = __('MAIL_FROM',$hostname);
if (!empty($fname)) {
$mailtext = __('GREETINGS_GORDON_FREEMAN',$fname,$lname);
} else {
$mailtext = __('GREETINGS');
}
$mailtext .= __('PASSWORD_RESET_REQUEST',$_SERVER['HTTP_HOST'],$user,$rkey,$_SERVER['HTTP_HOST'],$user,$rkey);
if (!empty($rkey)) send_email($to, $subject, $mailtext, $from);
unset($output);
}
header("Location: /reset/?action=code&user=".$_POST['user']);
exit;
}
if ((!empty($_POST['user'])) && (!empty($_POST['code'])) && (!empty($_POST['password'])) ) {
if ( $_POST['password'] == $_POST['password_confirm'] ) {
$v_user = escapeshellarg($_POST['user']);
$user = $_POST['user'];
$cmd="/usr/bin/sudo /usr/local/vesta/bin/v-list-user";
exec ($cmd." ".$v_user." json", $output, $return_var);
if ( $return_var == 0 ) {
$data = json_decode(implode('', $output), true);
$rkey = $data[$user]['RKEY'];
if (hash_equals($rkey, $POST[‘code’])) {
$v_password = tempnam("/tmp","vst");
$fp = fopen($v_password, "w");
fwrite($fp, $_POST['password']."\n");
fclose($fp);
$cmd="/usr/bin/sudo /usr/local/vesta/bin/v-change-user-password";
exec ($cmd." ".$v_user." ".$v_password, $output, $return_var);
unlink($v_password);
if ( $return_var > 0 ) {
$ERROR = "<a class=\"error\">".__('An internal error occurred')."</a>";
} else {
$_SESSION['user'] = $_POST['user'];
header("Location: /");
exit;
}
} else {
$ERROR = "<a class=\"error\">".__('Invalid username or code')."</a>";
}
} else {
$ERROR = "<a class=\"error\">".__('Invalid username or code')."</a>";
}
} else {
$ERROR = "<a class=\"error\">".__('Passwords not match')."</a>";
}
}
// Detect language
if (empty($_SESSION['language'])) $_SESSION['language'] = detect_user_language();
if (empty($_GET['action'])) {
require_once '../templates/header.html';
require_once '../templates/reset_1.html';
} else {
require_once '../templates/header.html';
if ($_GET['action'] == 'code' ) {
require_once '../templates/reset_2.html';
}
if (($_GET['action'] == 'confirm' ) && (!empty($_GET['code']))) {
require_once '../templates/reset_3.html';
}
}
?>
|
5f68c1b634abec2d5a4f83156bfd223d3a792f77
|
https://github.com/serghey-rodin/vesta
|
formats.js
|
javascript
|
exports['date-time'] = /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-[0-9]{2}[tT ]\d{2}:\d{2}:\d{2}(\.\d+)?([zZ]|[+-]\d{2}:\d{2})$/
exports['date'] = /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-[0-9]{2}$/
exports['time'] = /^\d{2}:\d{2}:\d{2}$/
exports['email'] = /^\S+@\S+$/
exports['ip-address'] = exports['ipv4'] = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
exports['ipv6'] = /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/
exports['uri'] = /^[a-zA-Z][a-zA-Z0-9+-.]*:[^\s]*$/
exports['color'] = /(#?([0-9A-Fa-f]{3,6})\b)|(aqua)|(black)|(blue)|(fuchsia)|(gray)|(green)|(lime)|(maroon)|(navy)|(olive)|(orange)|(purple)|(red)|(silver)|(teal)|(white)|(yellow)|(rgb\(\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*\))|(rgb\(\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*\))/
exports['hostname'] = /^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]))*$/
exports['alpha'] = /^[a-zA-Z]+$/
exports['alphanumeric'] = /^[a-zA-Z0-9]+$/
exports['style'] = /\s*(.+?):\s*([^;]+);?/g
exports['phone'] = /^\+(?:[0-9] ?){6,14}[0-9]$/
exports['utc-millisec'] = /^[0-9]+(\.?[0-9]+)?$/
|
exports['date-time'] = /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-[0-9]{2}[tT ]\d{2}:\d{2}:\d{2}(\.\d+)?([zZ]|[+-]\d{2}:\d{2})$/
exports['date'] = /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-[0-9]{2}$/
exports['time'] = /^\d{2}:\d{2}:\d{2}$/
exports['email'] = /^\S+@\S+$/
exports['ip-address'] = exports['ipv4'] = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
exports['ipv6'] = /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/
exports['uri'] = /^[a-zA-Z][a-zA-Z0-9+-.]*:[^\s]*$/
exports['color'] = /(#?([0-9A-Fa-f]{3,6})\b)|(aqua)|(black)|(blue)|(fuchsia)|(gray)|(green)|(lime)|(maroon)|(navy)|(olive)|(orange)|(purple)|(red)|(silver)|(teal)|(white)|(yellow)|(rgb\(\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*\))|(rgb\(\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*\))/
exports['hostname'] = /^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]))*$/
exports['alpha'] = /^[a-zA-Z]+$/
exports['alphanumeric'] = /^[a-zA-Z0-9]+$/
exports['style'] = /\s*(.+?):\s*([^;]+);?/g
exports['phone'] = /^\+(?:[0-9] ?){6,14}[0-9]$/
exports['utc-millisec'] = /^[0-9]{1,15}\.?[0-9]{0,15}$/
|
eca4beb21e61877d76fdf6bea771f72f39544d9b
|
https://github.com/mafintosh/is-my-json-valid
|
search_opensearch.php
|
php
|
<script language="PHP">
require "search_functions.php";
$mode = array_key_exists('v', $_GET)?$_GET['v']:"";
$query = array_key_exists('query', $_GET)?$_GET['query']:"";
$query_results = run_query($query);
switch ($mode)
{
case "opensearch.xml":
opensearch_description();
break;
case "json":
opensearch_json_results($query, $query_results);
break;
case "xml":
opensearch_xml_results($query, $query_results);
break;
default:
invalid_format($query, $query_results);
break;
}
function opensearch_description()
{
global $config;
global $translator;
$shortname = $translator['search']." ".$config['PROJECT_NAME'];
$link = "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['SCRIPT_NAME']);
header("Content-Type: application/xml");
echo <<<END_OPENSEARCH
<?xml version="1.0" encoding="UTF-8"?>
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
<ShortName>$shortname</ShortName>
<Description>Doxygen Search</Description>
<InputEncoding>UTF-8</InputEncoding>
<!--
<Image height="16" width="16" type="image/x-icon">
http://dev.squello.com/doc/html/favicon.ico</Image>
-->
<Url type="text/html" method="GET"
template="$link/search.php?query={searchTerms}" />
<Url type="application/x-suggestions+json" method="GET"
template="$link/search_opensearch.php?v=json&query={searchTerms}" />
<Url type="application/x-suggestions+xml" method="GET"
template="$link/search_opensearch.php?v=xml&query={searchTerms}" />
</OpenSearchDescription>
END_OPENSEARCH;
}
function opensearch_xml_results($query, array $results)
{
// Much as I hate copy'n'paste code re-use, this is for testing;
// I expect a richer version to come soon.
// Although I hate that IE does this richer than FF more...
$qs_results = array();
foreach ($results as $i => $val)
{
foreach ($val['words'] as $j => $word)
{
if (array_key_exists($word, $qs_results))
$qs_results[$word['match']]++;
else
$qs_results[$word['match']] = 1;
}
}
$result = <<<END_FRAG
<?xml version="1.0"?>
<SearchSuggestion xmlns="http://schemas.microsoft.com/Search/2008/suggestions">
<Query>$query</Query>
<Section>
END_FRAG;
foreach ($qs_results as $word => $count)
{
$result .= <<<END_FRAG
<Item>
<Text>$word</Text>
<Description>$count results</Description>
</Item>
END_FRAG;
}
$result .= <<<END_FRAG
</Section>
</SearchSuggestion>
END_FRAG;
echo $result;
}
function opensearch_json_results($query, array $results)
{
$qs_results = array();
foreach ($results as $i => $val)
{
foreach ($val['words'] as $j => $word)
{
if (array_key_exists($word, $qs_results))
$qs_results[$word['match']]++;
else
$qs_results[$word['match']] = 1;
}
}
$result = '["'.$query.'", [';
$json_words = "";
$json_descriptions = "";
$i = 0;
foreach ($qs_results as $word => $count)
{
if ($i != 0)
{
$json_words .= ", ";
$json_descriptions .= ", ";
}
$json_words .= '"'.$word.'"';
$json_descriptions .= '"'.$count.' result'.($count==1?'':'s').'"';
$i++;
}
print "[\"$query\", [$json_words],[$json_descriptions]]";
}
function invalid_format($query, array $results)
{
print "Search results for '$query':\n\n";
print_r($results);
}
</script>
|
<script language="PHP">
require "search_functions.php";
$mode = array_key_exists('v', $_GET)?$_GET['v']:"";
$query = array_key_exists('query', $_GET)?$_GET['query']:"";
$query = preg_replace("/[^a-zA-Z0-9\-\_\.\x80-\xFF]/i", " ", $query );
$query_results = run_query($query);
switch ($mode)
{
case "opensearch.xml":
opensearch_description();
break;
case "json":
opensearch_json_results($query, $query_results);
break;
case "xml":
opensearch_xml_results($query, $query_results);
break;
default:
invalid_format($query, $query_results);
break;
}
function opensearch_description()
{
global $config;
global $translator;
$shortname = $translator['search']." ".$config['PROJECT_NAME'];
$link = "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['SCRIPT_NAME']);
header("Content-Type: application/xml");
echo <<<END_OPENSEARCH
<?xml version="1.0" encoding="UTF-8"?>
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
<ShortName>$shortname</ShortName>
<Description>Doxygen Search</Description>
<InputEncoding>UTF-8</InputEncoding>
<!--
<Image height="16" width="16" type="image/x-icon">
http://dev.squello.com/doc/html/favicon.ico</Image>
-->
<Url type="text/html" method="GET"
template="$link/search.php?query={searchTerms}" />
<Url type="application/x-suggestions+json" method="GET"
template="$link/search_opensearch.php?v=json&query={searchTerms}" />
<Url type="application/x-suggestions+xml" method="GET"
template="$link/search_opensearch.php?v=xml&query={searchTerms}" />
</OpenSearchDescription>
END_OPENSEARCH;
}
function opensearch_xml_results($query, array $results)
{
// Much as I hate copy'n'paste code re-use, this is for testing;
// I expect a richer version to come soon.
// Although I hate that IE does this richer than FF more...
$qs_results = array();
foreach ($results as $i => $val)
{
foreach ($val['words'] as $j => $word)
{
if (array_key_exists($word, $qs_results))
$qs_results[$word['match']]++;
else
$qs_results[$word['match']] = 1;
}
}
$result = <<<END_FRAG
<?xml version="1.0"?>
<SearchSuggestion xmlns="http://schemas.microsoft.com/Search/2008/suggestions">
<Query>$query</Query>
<Section>
END_FRAG;
foreach ($qs_results as $word => $count)
{
$result .= <<<END_FRAG
<Item>
<Text>$word</Text>
<Description>$count results</Description>
</Item>
END_FRAG;
}
$result .= <<<END_FRAG
</Section>
</SearchSuggestion>
END_FRAG;
echo $result;
}
function opensearch_json_results($query, array $results)
{
$qs_results = array();
foreach ($results as $i => $val)
{
foreach ($val['words'] as $j => $word)
{
if (array_key_exists($word, $qs_results))
$qs_results[$word['match']]++;
else
$qs_results[$word['match']] = 1;
}
}
$result = '["'.$query.'", [';
$json_words = "";
$json_descriptions = "";
$i = 0;
foreach ($qs_results as $word => $count)
{
if ($i != 0)
{
$json_words .= ", ";
$json_descriptions .= ", ";
}
$json_words .= '"'.$word.'"';
$json_descriptions .= '"'.$count.' result'.($count==1?'':'s').'"';
$i++;
}
print "[\"$query\", [$json_words],[$json_descriptions]]";
}
function invalid_format($query, array $results)
{
print "Search results for '$query':\n\n";
print_r($results);
}
</script>
|
1cc1adad2de03a0f013881b8960daf89aa155081
|
https://github.com/doxygen/doxygen
|
stats.php
|
php
|
<?php
require_once '../inc/config.inc.php';
$title = "Statistiques de recherche";
$description = "Mapicoin, statistiques de recherche - Découvrez les recherches effectuées sur Mapicoin !";
$searches = stats_get_searches();
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<title><?= $title ?> - Mapicoin</title>
<meta name="description" content="<?= $description ?>" />
<!-- Open Graph -->
<meta property="og:title" content="<?= $title ?? 'Mapicoin' ?>" />
<meta property="og:description" content="<?= $description ?>" />
<meta property="og:type" content="website" />
<meta property="og:url" content="https://<?= $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'] ?>" />
<meta property="og:image" content="https://<?= $_SERVER['HTTP_HOST']?>/img/mapicoin-meta-og.png" />
<?php include 'inc/header.inc.php'; ?>
<link href="/css/mapicoin-page.css?<?= VERSION ?>" rel="stylesheet" />
</head>
<body class="page">
<?php include 'inc/cookies-cnil-banner.inc.php' ?>
<div class="page-container">
<div class="text-center">
<a href="/">
<img id="logo" src="/img/mapicoin-logo.png" width="409" height="112" />
</a>
</div>
<div class="page-body">
<div class="page-breadcrumb">
<a href="/">Accueil</a> » Mapicoin : Statistiques de recherche
</div>
<h1><span>Mapicoin : <?= $title ?></span></h1>
<div class="page-content">
<table>
<thead>
<tr>
<th>Recherche</th>
<th>Compteur</th>
<th>Dernière recherche</th>
</tr>
</thead>
<tbody>
<?php foreach ($searches as $search):?>
<?php $link = str_replace(['?','&'], ['%3F','%26'], $search['search']); ?>
<tr>
<td>
<a href="https://mapicoin.fr/?u=<?= $link ?>"><?= $search['search'] ?></a>
</td>
<td><?= $search['count'] ?></td>
<td><?= time_elapsed_string(strtotime($search['updated'])) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div><!-- /.page-content -->
</div><!-- /.page-body -->
<?php include 'inc/page-footer.inc.php' ?>
</div><!-- /.page-container -->
<?php include 'inc/ga.inc.php' ?>
</body>
</html>
|
<?php
require_once '../inc/config.inc.php';
$title = "Statistiques de recherche";
$description = "Mapicoin, statistiques de recherche - Découvrez les recherches effectuées sur Mapicoin !";
$searches = stats_get_searches();
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<title><?= $title ?> - Mapicoin</title>
<meta name="description" content="<?= $description ?>" />
<!-- Open Graph -->
<meta property="og:title" content="<?= $title ?? 'Mapicoin' ?>" />
<meta property="og:description" content="<?= $description ?>" />
<meta property="og:type" content="website" />
<meta property="og:url" content="https://<?= $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'] ?>" />
<meta property="og:image" content="https://<?= $_SERVER['HTTP_HOST']?>/img/mapicoin-meta-og.png" />
<?php include 'inc/header.inc.php'; ?>
<link href="/css/mapicoin-page.css?<?= VERSION ?>" rel="stylesheet" />
</head>
<body class="page">
<?php include 'inc/cookies-cnil-banner.inc.php' ?>
<div class="page-container">
<div class="text-center">
<a href="/">
<img id="logo" src="/img/mapicoin-logo.png" width="409" height="112" />
</a>
</div>
<div class="page-body">
<div class="page-breadcrumb">
<a href="/">Accueil</a> » Mapicoin : Statistiques de recherche
</div>
<h1><span>Mapicoin : <?= $title ?></span></h1>
<div class="page-content">
<table>
<thead>
<tr>
<th>Recherche</th>
<th>Compteur</th>
<th>Dernière recherche</th>
</tr>
</thead>
<tbody>
<?php foreach ($searches as $search):?>
<?php $link = str_replace(['?','&'], ['%3F','%26'], $search['search']); ?>
<tr>
<td>
<a href="https://mapicoin.fr/?u=<?= htmlentities($link, ENT_QUOTES, "UTF-8"); ?>"><?= htmlentities($search['search'], ENT_QUOTES, "UTF-8") ?></a>
</td>
<td><?= $search['count'] ?></td>
<td><?= time_elapsed_string(strtotime($search['updated'])) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div><!-- /.page-content -->
</div><!-- /.page-body -->
<?php include 'inc/page-footer.inc.php' ?>
</div><!-- /.page-container -->
<?php include 'inc/ga.inc.php' ?>
</body>
</html>
|
67e87f0f0c1ac238fcd050f4c3db298229bc9679
|
https://github.com/ydalb/mapicoin
|
admin.rb
|
ruby
|
require 'sinatra'
require 'zip'
config_options = JSON.parse(File.read('./config.json'))
# set the report_assessment_types for <1.2 versions of Serpico
unless config_options['report_assessment_types']
config_options['report_assessment_types'] = ['Network Internal', 'External', 'Web application', 'Physical', 'Social engineering', 'Configuration audit']
end
######
# Admin Interfaces
######
get '/admin/' do
redirect to('/no_access') unless is_administrator?
@admin = true
haml :admin
end
get '/admin/add_user' do
redirect to('/no_access') unless is_administrator?
@admin = true
haml :add_user
end
# serve a copy of the code
get '/admin/pull' do
redirect to('/no_access') unless is_administrator?
if File.exist?('./export.zip')
send_file './export.zip', filename: 'export.zip', type: 'Application/octet-stream'
serpico_log("Copy of code exported")
else
'No copy of the code available. Run scripts/make_export.sh.'
end
end
# create DB backup
get '/admin/dbbackup' do
redirect to('/no_access') unless is_administrator?
bdate = Time.now
filename = './tmp/master' + '-' + (bdate.strftime('%Y%m%d%H%M%S') + '.bak')
FileUtils.copy_file('./db/master.db', filename)
if !File.zero?(filename)
send_file filename, filename: filename.to_s, type: 'Application/octet-stream'
serpico_log("DB backup created")
else
'No copy of the database is available. Please try again.'
sleep(5)
redirect to('/admin/')
end
end
# create backup of all attachments
get '/admin/attacments_backup' do
bdate = Time.now
zip_file = './tmp/Attachments' + '-' + (bdate.strftime('%Y%m%d%H%M%S') + '.zip')
Zip::File.open(zip_file, Zip::File::CREATE) do |zipfile|
Dir['./attachments/*'].each do |name|
zipfile.add(name.split('/').last, name)
end
end
send_file zip_file, type: 'zip', filename: zip_file
# File.delete(rand_zip) should the temp file be deleted?
serpico_log("Backup of attachments created")
end
# Create a new user
post '/admin/add_user' do
redirect to('/no_access') unless is_administrator?
user = User.first(username: params[:username])
if user
if params[:password] && (params[:password].size > 1)
# we have to hardcode the input params to prevent param pollution
user.update(type: params[:type], auth_type: params[:auth_type], password: params[:password])
else
# we have to hardcode the params to prevent param pollution
user.update(type: params[:type], auth_type: params[:auth_type])
end
else
user = User.new
user.username = params[:username]
user.password = params[:password]
user.type = params[:type]
user.auth_type = params[:auth_type]
user.save
end
serpico_log("User #{user.username} created")
redirect to('/admin/list_user')
end
get '/admin/list_user' do
redirect to('/no_access') unless is_administrator?
@admin = true
@users = User.all
@plugin = is_plugin?
haml :list_user
end
get '/admin/edit_user/:id' do
redirect to('/no_access') unless is_administrator?
@user = User.first(id: params[:id])
haml :add_user
end
get '/admin/delete/:id' do
redirect to('/no_access') unless is_administrator?
@user = User.first(id: params[:id])
@user.destroy if @user
serpico_log("User #{@user.username} deleted")
redirect to('/admin/list_user')
end
get '/admin/add_user/:id' do
unless is_administrator?
id = params[:id]
redirect to('/no_access') unless get_report(id)
end
@users = User.all(order: [:username.asc])
@report = Reports.first(id: params[:id])
@admin = true if is_administrator?
haml :add_user_report
end
post '/admin/add_user/:id' do
unless is_administrator?
id = params[:id]
redirect to('/no_access') unless get_report(id)
end
report = Reports.first(id: params[:id])
return 'No Such Report' if report.nil?
authors = report.authors
authors = if authors
authors.push(params[:author])
else
[params[:author].to_s]
end
report.authors = authors
report.save
serpico_log("User added to report")
redirect to("/admin/add_user/#{params[:id]}")
end
get '/admin/del_user_report/:id/:author' do
unless is_administrator?
id = params[:id]
redirect to('/no_access') unless get_report(id)
end
report = Reports.first(id: params[:id])
return 'No Such Report' if report.nil?
authors = report.authors
authors -= [params[:author].to_s] if authors
report.authors = authors
report.save
serpico_log("User removed from report")
redirect to("/admin/add_user/#{params[:id]}")
end
get '/admin/config' do
redirect to('/no_access') unless is_administrator?
@config = config_options
@scoring = if config_options['cvss']
'cvss'
elsif config_options['cvssv3']
'cvssv3'
elsif config_options['dread']
'dread'
elsif config_options['riskmatrix']
'riskmatrix'
elsif config_options["nist800"]
'nist800'
else
'default'
end
haml :config
end
post '/admin/config' do
redirect to('/no_access') unless is_administrator?
ft = params['finding_types'].split(',')
udv = params['user_defined_variables'].split(',')
rat = params['report_assessment_types'].split(',')
lang = params['languages'].delete(' ').split(',')
config_options['effort'] = params['effort'].split(',') if params['effort']
config_options['finding_types'] = ft
config_options['user_defined_variables'] = udv
config_options['port'] = params['port']
config_options['report_assessment_types'] = rat
config_options['languages'] = lang
config_options['use_ssl'] = params['use_ssl'] ? true : false
config_options['bind_address'] = params['bind_address']
config_options['ldap'] = params['ldap'] ? true : false
config_options['ldap_domain'] = params['ldap_domain']
config_options['ldap_dc'] = params['ldap_dc']
config_options['burpmap'] = params['burpmap'] ? true : false
config_options['nessusmap'] = params['nessusmap'] ? true : false
config_options['vulnmap'] = params['vulnmap'] ? true : false
config_options['logo'] = params['logo']
config_options['auto_import'] = params['auto_import'] ? true : false
config_options['chart'] = params['chart'] ? true : false
config_options['threshold'] = params['threshold']
config_options['show_exceptions'] = params['show_exceptions'] ? true : false
config_options['cvssv2_scoring_override'] = params['cvssv2_scoring_override'] ? true : false
if params['risk_scoring'] == 'CVSSv2'
config_options['dread'] = false
config_options['cvss'] = true
config_options['cvssv3'] = false
config_options['riskmatrix'] = false
config_options['nist800'] = false
elsif params['risk_scoring'] == 'CVSSv3'
config_options['dread'] = false
config_options['cvss'] = false
config_options['cvssv3'] = true
config_options['riskmatrix'] = false
config_options['nist800'] = false
elsif params['risk_scoring'] == 'DREAD'
config_options['dread'] = true
config_options['cvss'] = false
config_options['cvssv3'] = false
config_options['riskmatrix'] = false
config_options['nist800'] = false
elsif params['risk_scoring'] == 'RISKMATRIX'
config_options['dread'] = false
config_options['cvss'] = false
config_options['cvssv3'] = false
config_options['riskmatrix'] = true
config_options['nist800'] = false
elsif params['risk_scoring'] == 'NIST800-30'
config_options['dread'] = false
config_options['cvss'] = false
config_options['cvssv3'] = false
config_options['riskmatrix'] = false
config_options['nist800'] = true
else
config_options['dread'] = false
config_options['cvss'] = false
config_options['cvssv3'] = false
config_options['riskmatrix'] = false
config_options['nist800'] = false
end
File.open('./config.json', 'w') do |f|
f.write(JSON.pretty_generate(config_options))
serpico_log("Configuration file modified")
end
redirect to('/admin/config')
end
# get plugins available
get '/admin/plugins' do
redirect to('/no_access') unless is_administrator?
@plugins = []
Dir[File.join(File.dirname(__FILE__), '../plugins/**/', '*.json')].each do |lib|
@plugins.push(JSON.parse(File.open(lib).read))
end
@admin = true if is_administrator?
@plugin = true if is_plugin?
haml :plugins
end
# enable plugins
post '/admin/plugins' do
redirect to('/no_access') unless is_administrator?
@plugins = []
Dir[File.join(File.dirname(__FILE__), '../plugins/**/', '*.json')].each do |lib|
@plugins.push(JSON.parse(File.open(lib).read))
end
@plugins.each do |plug|
if params[plug['name']]
plug['enabled'] = true
File.open("./plugins/#{plug['name']}/plugin.json", 'w') do |f|
f.write(JSON.pretty_generate(plug))
serpico_log("Plugin #{plug['name']} enabled")
end
else
plug['enabled'] = false
File.open("./plugins/#{plug['name']}/plugin.json", 'w') do |f|
f.write(JSON.pretty_generate(plug))
serpico_log("Plugin #{plug['name']} disabled")
end
end
end
redirect to('/admin/plugins')
end
# upload plugin zip
post '/admin/plugin_upload' do
redirect to('/no_access') unless is_administrator?
redirect to('/no_access') unless is_plugin?
# take each zip in turn
params['files'].map do |upf|
# We use a random filename
rand_file = "./tmp/#{rand(36**36).to_s(36)}"
# reject if the file is above a certain limit
return 'File too large. 100MB limit' if upf[:tempfile].size > 100_000_000
# unzip the plugin and write it to the fs, writing the OS is possible but so is RCE
File.open(rand_file, 'wb') { |f| f.write(upf[:tempfile].read) }
# find the config.json file
config = ''
Zip::File.open(rand_file) do |zipfile|
# read the config file
zipfile.each do |entry|
if entry.name == 'plugin.json'
configj = entry.get_input_stream.read
config = JSON.parse(configj)
serpico_log("Custom plugin uploaded")
end
end
end
return 'plugin.json does not exist in zip.' if config == ''
Zip::File.open(rand_file) do |zipfile|
# read the config file
zipfile.each do |entry|
# Extract to file/directory/symlink
fn = "./plugins/#{config['name']}/" + entry.name
# create the directory if dne
dirj = fn.split('/')
dirj.pop
FileUtils.mkdir_p(dirj.join('/')) unless File.directory?(dirj.join('/'))
next if fn[-1] == '/'
# Read into memory
content = entry.get_input_stream.read
File.open(fn, 'a') do |f|
f.write(content)
end
end
end
end
redirect to('/admin/plugins')
end
# Manage Templated Reports
get '/admin/templates' do
redirect to('/no_access') unless is_administrator?
@admin = true
# Query for all Findings
@templates = Xslt.all(order: [:report_type.asc])
haml :template_list
end
# Manage Templated Reports
get '/admin/templates/add' do
redirect to('/no_access') unless is_administrator?
@admin = true
haml :add_template
end
# Manage Templated Reports
get '/admin/templates/:id/download' do
redirect to('/no_access') unless is_administrator?
@admin = true
xslt = Xslt.first(id: params[:id])
send_file xslt.docx_location, type: 'docx', filename: "#{xslt.report_type}.docx"
end
get '/admin/delete/templates/:id' do
redirect to('/no_access') unless is_administrator?
@xslt = Xslt.first(id: params[:id])
if @xslt
@xslt.components.destroy
@xslt.destroy
File.delete(@xslt.xslt_location) if File.file?(@xslt.xslt_location)
File.delete(@xslt.docx_location) if File.file?(@xslt.docx_location)
serpico_log("Report template deleted")
end
redirect to('/admin/templates')
end
# Manage Templated Reports
post '/admin/templates/add' do
redirect to('/no_access') unless is_administrator?
@admin = true
xslt_file = "./templates/#{rand(36**36).to_s(36)}.xslt"
redirect to('/admin/templates/add') unless params[:file]
# reject if the file is above a certain limit
if params[:file][:tempfile].size > 100_000_000
return 'File too large. 10MB limit'
end
docx = "./templates/#{rand(36**36).to_s(36)}.docx"
File.open(docx, 'wb') { |f| f.write(params[:file][:tempfile].read) }
error = false
detail = ''
begin
xslt = generate_xslt(docx)
xslt_components = generate_xslt_components(docx)
rescue TemplateVerificationError => detail
@error_message = CGI::escapeHTML(detail.errorString)
@tree = CGI::escapeHTML(detail.template_tree)
return haml :template_error
rescue ReportingError => detail
error = true
end
if error
"The report template you uploaded threw an error when parsing:<p><p> #{detail.errorString}"
else
# open up a file handle and write the attachment
File.open(xslt_file, 'wb') { |f| f.write(xslt) }
# extract the screenshot names from the file
screenshot_names = xslt.scan(/\[!!(.*?)!!\]/)
# delete the file data from the attachment
datax = {}
# to prevent traversal we hardcode this
datax['docx_location'] = docx.to_s
datax['xslt_location'] = xslt_file.to_s
datax['description'] = params[:description]
datax['report_type'] = params[:report_type]
datax['screenshot_names'] = screenshot_names.join(',')
data = url_escape_hash(datax)
data['finding_template'] = params[:finding_template] ? true : false
data['status_template'] = params[:status_template] ? true : false
@template = Xslt.first(report_type: data['report_type'])
if @template
@template.update(xslt_location: data['xslt_location'], docx_location: data['docx_location'], description: data['description'], screenshot_names: data['screenshot_names'])
@template.components.destroy
else
@template = Xslt.new(data)
@template.save
end
# create a xslt file for each component
list_components_files = []
xslt_components.each do |component_name, component_xslt|
componentHash = {}
componentHash['xslt_location'] = "./templates/#{rand(36**36).to_s(36)}.xslt"
componentHash['name'] = component_name
componentHash['xslt'] = @template
File.open(componentHash['xslt_location'], 'wb') { |f| f.write(component_xslt) }
list_components_files.push(componentHash)
end
# insert components into the db
list_components_files.each do |component|
@component = Xslt_component.new(component)
@component.save
end
serpico_log("New report template successfully added")
redirect to('/admin/templates')
haml :add_template
end
end
get '/admin/templates/:id/tree' do
redirect to('/no_access') unless is_administrator?
@admin = true
xslt = Xslt.first(id: params[:id])
document = read_rels(xslt.docx_location,"word/document.xml")
@tree = verify_document(document)
@tree = @tree[2]
haml :template_tree
end
# Manage Templated Reports
get '/admin/templates/:id/edit' do
redirect to('/no_access') unless is_administrator?
@admin = true
@template = Xslt.first(id: params[:id])
haml :edit_template
end
# Manage Templated Reports
post '/admin/templates/edit' do
redirect to('/no_access') unless is_administrator?
@admin = true
template = Xslt.first(id: params[:id])
xslt_file = template.xslt_location
redirect to("/admin/templates/#{params[:id]}/edit") unless params[:file]
# reject if the file is above a certain limit
if params[:file][:tempfile].size > 100_000_000
return 'File too large. 10MB limit'
end
docx = "./templates/#{rand(36**36).to_s(36)}.docx"
File.open(docx, 'wb') { |f| f.write(params[:file][:tempfile].read) }
error = false
detail = ''
begin
xslt = generate_xslt(docx)
xslt_components = generate_xslt_components(docx)
rescue TemplateVerificationError => detail
@error_message = CGI::escapeHTML(detail.errorString)
@tree = CGI::escapeHTML(detail.template_tree)
return haml :template_error
rescue ReportingError => detail
error = true
end
if error
"The report template you uploaded threw an error when parsing:<p><p> #{detail.errorString}"
else
# open up a file handle and write the attachment
File.open(xslt_file, 'wb') { |f| f.write(xslt) }
# extract the screenshot names from the file
screenshot_names = xslt.scan(/\[!!(.*?)!!\]/)
# delete the file data from the attachment
datax = {}
# to prevent traversal we hardcode this
datax['docx_location'] = docx.to_s
datax['xslt_location'] = xslt_file.to_s
datax['description'] = params[:description]
datax['report_type'] = params[:report_type]
datax['screenshot_names'] = screenshot_names.join(',')
data = url_escape_hash(datax)
data['finding_template'] = params[:finding_template] ? true : false
data['status_template'] = params[:status_template] ? true : false
@template = Xslt.first(report_type: data['report_type'])
if @template
@template.update(xslt_location: data['xslt_location'], docx_location: data['docx_location'], description: data['description'], screenshot_names: data['screenshot_names'])
@template.components.destroy
else
@template = Xslt.new(data)
@template.save
end
# create a xslt file for each component
list_components_files = []
xslt_components.each do |component_name, component_xslt|
componentHash = {}
componentHash['xslt_location'] = "./templates/#{rand(36**36).to_s(36)}.xslt"
componentHash['name'] = component_name
componentHash['xslt'] = @template
File.open(componentHash['xslt_location'], 'wb') { |f| f.write(component_xslt) }
list_components_files.push(componentHash)
end
# insert components into the db
list_components_files.each do |component|
@component = Xslt_component.new(component)
@component.save
end
serpico_log("Report template modified")
redirect to('/admin/templates')
end
end
# get enabled plugins
get '/admin/admin_plugins' do
@admin = true if is_administrator?
@plugin = true if is_plugin?
@menu = get_plugin_list('admin')
haml :enabled_plugins
end
get '/admin/udo_templates' do
redirect to('/no_access') unless is_administrator?
# delete UDO template part
if params[:delete]
udo_template = UserDefinedObjectTemplates.get(params[:delete])
return 'UDO Template not found' if udo_template.nil?
udo_template.destroy
end
@udos_templates = UserDefinedObjectTemplates.all
@admin = true if is_administrator?
@plugin = true if is_plugin?
haml :user_defined_object_templates
end
post '/admin/udo_templates' do
redirect to('/no_access') unless is_administrator?
data = url_escape_hash(request.POST)
# Save new UDO template part
if data['action'] = 'Save'
new_udo_template = UserDefinedObjectTemplates.new
new_udo_template.type = data['object_type']
udo_properties = {}
# we extract the udo properties from the posted data
data.each do |param, value|
if param =~ /property_/
udo_properties[value] = '' unless value.to_s.empty?
end
end
new_udo_template.udo_properties = udo_properties.to_json
new_udo_template.save
end
@udos_templates = UserDefinedObjectTemplates.all
serpico_log("UDO template added")
redirect to('/admin/udo_templates')
end
# edit udo template
get '/admin/udo_template/:template_id/edit' do
redirect to('/no_access') unless is_administrator?
@udo_to_edit = UserDefinedObjectTemplates.get(params[:template_id])
return 'No such UDO Template' if @udo_to_edit.nil?
@udo_to_edit_properties = JSON.parse(@udo_to_edit.udo_properties)
@admin = true if is_administrator?
@plugin = true if is_plugin?
haml :udo_template_edit
end
post '/admin/udo_template/:template_id/edit' do
redirect to('/no_access') unless is_administrator?
data = url_escape_hash(request.POST)
@udo_to_edit = UserDefinedObjectTemplates.get(params[:template_id])
return 'No such UDO Template' if @udo_to_edit.nil?
@udo_to_edit_properties = JSON.parse(@udo_to_edit.udo_properties)
udo_properties = {}
# we extract the udo properties from the posted data
data.each do |param1, value1|
unless value1.to_s.empty?
# we add the new properties
if param1 =~ /prop_new_\d+/
id = param1.split('_')[2]
data.each do |param2, value2|
next unless param2 =~ /default_new_#{id}/
udo_properties[value1] = if value2 !~ /\<paragraph\>/
"<paragraph>#{value2}</paragraph>"
else
value2
end
end
# we edit the already existing properties
elsif param1 =~ /prop_/
data.each do |param2, value2|
next unless param2 =~ /default_#{param1.split("_")[-1]}/
udo_properties[value1] = if value2 !~ /\<paragraph\>/
"<paragraph>#{value2}</paragraph>"
else
value2
end
end
end
end
end
@udo_to_edit.udo_properties = udo_properties.to_json
@udo_to_edit.save
serpico_log("UDO template modified")
redirect to('/admin/udo_templates')
end
|
require 'sinatra'
require 'zip'
config_options = JSON.parse(File.read('./config.json'))
# set the report_assessment_types for <1.2 versions of Serpico
unless config_options['report_assessment_types']
config_options['report_assessment_types'] = ['Network Internal', 'External', 'Web application', 'Physical', 'Social engineering', 'Configuration audit']
end
######
# Admin Interfaces
######
get '/admin/' do
redirect to('/no_access') unless is_administrator?
@admin = true
haml :admin
end
get '/admin/add_user' do
redirect to('/no_access') unless is_administrator?
@admin = true
haml :add_user
end
# serve a copy of the code
get '/admin/pull' do
redirect to('/no_access') unless is_administrator?
if File.exist?('./export.zip')
send_file './export.zip', filename: 'export.zip', type: 'Application/octet-stream'
serpico_log("Copy of code exported")
else
'No copy of the code available. Run scripts/make_export.sh.'
end
end
# create DB backup
get '/admin/dbbackup' do
redirect to('/no_access') unless is_administrator?
bdate = Time.now
filename = './tmp/master' + '-' + (bdate.strftime('%Y%m%d%H%M%S') + '.bak')
FileUtils.copy_file('./db/master.db', filename)
if !File.zero?(filename)
send_file filename, filename: filename.to_s, type: 'Application/octet-stream'
serpico_log("DB backup created")
else
'No copy of the database is available. Please try again.'
sleep(5)
redirect to('/admin/')
end
end
# create backup of all attachments
get '/admin/attacments_backup' do
redirect to('/no_access') unless is_administrator?
bdate = Time.now
zip_file = './tmp/Attachments' + '-' + (bdate.strftime('%Y%m%d%H%M%S') + '.zip')
Zip::File.open(zip_file, Zip::File::CREATE) do |zipfile|
Dir['./attachments/*'].each do |name|
zipfile.add(name.split('/').last, name)
end
end
send_file zip_file, type: 'zip', filename: zip_file
# File.delete(rand_zip) should the temp file be deleted?
serpico_log("Backup of attachments created")
end
# Create a new user
post '/admin/add_user' do
redirect to('/no_access') unless is_administrator?
user = User.first(username: params[:username])
if user
if params[:password] && (params[:password].size > 1)
# we have to hardcode the input params to prevent param pollution
user.update(type: params[:type], auth_type: params[:auth_type], password: params[:password])
else
# we have to hardcode the params to prevent param pollution
user.update(type: params[:type], auth_type: params[:auth_type])
end
else
user = User.new
user.username = params[:username]
user.password = params[:password]
user.type = params[:type]
user.auth_type = params[:auth_type]
user.save
end
serpico_log("User #{user.username} created")
redirect to('/admin/list_user')
end
get '/admin/list_user' do
redirect to('/no_access') unless is_administrator?
@admin = true
@users = User.all
@plugin = is_plugin?
haml :list_user
end
get '/admin/edit_user/:id' do
redirect to('/no_access') unless is_administrator?
@user = User.first(id: params[:id])
haml :add_user
end
get '/admin/delete/:id' do
redirect to('/no_access') unless is_administrator?
@user = User.first(id: params[:id])
@user.destroy if @user
serpico_log("User #{@user.username} deleted")
redirect to('/admin/list_user')
end
get '/admin/add_user/:id' do
unless is_administrator?
id = params[:id]
redirect to('/no_access') unless get_report(id)
end
@users = User.all(order: [:username.asc])
@report = Reports.first(id: params[:id])
@admin = true if is_administrator?
haml :add_user_report
end
post '/admin/add_user/:id' do
unless is_administrator?
id = params[:id]
redirect to('/no_access') unless get_report(id)
end
report = Reports.first(id: params[:id])
return 'No Such Report' if report.nil?
authors = report.authors
authors = if authors
authors.push(params[:author])
else
[params[:author].to_s]
end
report.authors = authors
report.save
serpico_log("User added to report")
redirect to("/admin/add_user/#{params[:id]}")
end
get '/admin/del_user_report/:id/:author' do
unless is_administrator?
id = params[:id]
redirect to('/no_access') unless get_report(id)
end
report = Reports.first(id: params[:id])
return 'No Such Report' if report.nil?
authors = report.authors
authors -= [params[:author].to_s] if authors
report.authors = authors
report.save
serpico_log("User removed from report")
redirect to("/admin/add_user/#{params[:id]}")
end
get '/admin/config' do
redirect to('/no_access') unless is_administrator?
@config = config_options
@scoring = if config_options['cvss']
'cvss'
elsif config_options['cvssv3']
'cvssv3'
elsif config_options['dread']
'dread'
elsif config_options['riskmatrix']
'riskmatrix'
elsif config_options["nist800"]
'nist800'
else
'default'
end
haml :config
end
post '/admin/config' do
redirect to('/no_access') unless is_administrator?
ft = params['finding_types'].split(',')
udv = params['user_defined_variables'].split(',')
rat = params['report_assessment_types'].split(',')
lang = params['languages'].delete(' ').split(',')
config_options['effort'] = params['effort'].split(',') if params['effort']
config_options['finding_types'] = ft
config_options['user_defined_variables'] = udv
config_options['port'] = params['port']
config_options['report_assessment_types'] = rat
config_options['languages'] = lang
config_options['use_ssl'] = params['use_ssl'] ? true : false
config_options['bind_address'] = params['bind_address']
config_options['ldap'] = params['ldap'] ? true : false
config_options['ldap_domain'] = params['ldap_domain']
config_options['ldap_dc'] = params['ldap_dc']
config_options['burpmap'] = params['burpmap'] ? true : false
config_options['nessusmap'] = params['nessusmap'] ? true : false
config_options['vulnmap'] = params['vulnmap'] ? true : false
config_options['logo'] = params['logo']
config_options['auto_import'] = params['auto_import'] ? true : false
config_options['chart'] = params['chart'] ? true : false
config_options['threshold'] = params['threshold']
config_options['show_exceptions'] = params['show_exceptions'] ? true : false
config_options['cvssv2_scoring_override'] = params['cvssv2_scoring_override'] ? true : false
if params['risk_scoring'] == 'CVSSv2'
config_options['dread'] = false
config_options['cvss'] = true
config_options['cvssv3'] = false
config_options['riskmatrix'] = false
config_options['nist800'] = false
elsif params['risk_scoring'] == 'CVSSv3'
config_options['dread'] = false
config_options['cvss'] = false
config_options['cvssv3'] = true
config_options['riskmatrix'] = false
config_options['nist800'] = false
elsif params['risk_scoring'] == 'DREAD'
config_options['dread'] = true
config_options['cvss'] = false
config_options['cvssv3'] = false
config_options['riskmatrix'] = false
config_options['nist800'] = false
elsif params['risk_scoring'] == 'RISKMATRIX'
config_options['dread'] = false
config_options['cvss'] = false
config_options['cvssv3'] = false
config_options['riskmatrix'] = true
config_options['nist800'] = false
elsif params['risk_scoring'] == 'NIST800-30'
config_options['dread'] = false
config_options['cvss'] = false
config_options['cvssv3'] = false
config_options['riskmatrix'] = false
config_options['nist800'] = true
else
config_options['dread'] = false
config_options['cvss'] = false
config_options['cvssv3'] = false
config_options['riskmatrix'] = false
config_options['nist800'] = false
end
File.open('./config.json', 'w') do |f|
f.write(JSON.pretty_generate(config_options))
serpico_log("Configuration file modified")
end
redirect to('/admin/config')
end
# get plugins available
get '/admin/plugins' do
redirect to('/no_access') unless is_administrator?
@plugins = []
Dir[File.join(File.dirname(__FILE__), '../plugins/**/', '*.json')].each do |lib|
@plugins.push(JSON.parse(File.open(lib).read))
end
@admin = true if is_administrator?
@plugin = true if is_plugin?
haml :plugins
end
# enable plugins
post '/admin/plugins' do
redirect to('/no_access') unless is_administrator?
@plugins = []
Dir[File.join(File.dirname(__FILE__), '../plugins/**/', '*.json')].each do |lib|
@plugins.push(JSON.parse(File.open(lib).read))
end
@plugins.each do |plug|
if params[plug['name']]
plug['enabled'] = true
File.open("./plugins/#{plug['name']}/plugin.json", 'w') do |f|
f.write(JSON.pretty_generate(plug))
serpico_log("Plugin #{plug['name']} enabled")
end
else
plug['enabled'] = false
File.open("./plugins/#{plug['name']}/plugin.json", 'w') do |f|
f.write(JSON.pretty_generate(plug))
serpico_log("Plugin #{plug['name']} disabled")
end
end
end
redirect to('/admin/plugins')
end
# upload plugin zip
post '/admin/plugin_upload' do
redirect to('/no_access') unless is_administrator?
redirect to('/no_access') unless is_plugin?
# take each zip in turn
params['files'].map do |upf|
# We use a random filename
rand_file = "./tmp/#{rand(36**36).to_s(36)}"
# reject if the file is above a certain limit
return 'File too large. 100MB limit' if upf[:tempfile].size > 100_000_000
# unzip the plugin and write it to the fs, writing the OS is possible but so is RCE
File.open(rand_file, 'wb') { |f| f.write(upf[:tempfile].read) }
# find the config.json file
config = ''
Zip::File.open(rand_file) do |zipfile|
# read the config file
zipfile.each do |entry|
if entry.name == 'plugin.json'
configj = entry.get_input_stream.read
config = JSON.parse(configj)
serpico_log("Custom plugin uploaded")
end
end
end
return 'plugin.json does not exist in zip.' if config == ''
Zip::File.open(rand_file) do |zipfile|
# read the config file
zipfile.each do |entry|
# Extract to file/directory/symlink
fn = "./plugins/#{config['name']}/" + entry.name
# create the directory if dne
dirj = fn.split('/')
dirj.pop
FileUtils.mkdir_p(dirj.join('/')) unless File.directory?(dirj.join('/'))
next if fn[-1] == '/'
# Read into memory
content = entry.get_input_stream.read
File.open(fn, 'a') do |f|
f.write(content)
end
end
end
end
redirect to('/admin/plugins')
end
# Manage Templated Reports
get '/admin/templates' do
redirect to('/no_access') unless is_administrator?
@admin = true
# Query for all Findings
@templates = Xslt.all(order: [:report_type.asc])
haml :template_list
end
# Manage Templated Reports
get '/admin/templates/add' do
redirect to('/no_access') unless is_administrator?
@admin = true
haml :add_template
end
# Manage Templated Reports
get '/admin/templates/:id/download' do
redirect to('/no_access') unless is_administrator?
@admin = true
xslt = Xslt.first(id: params[:id])
send_file xslt.docx_location, type: 'docx', filename: "#{xslt.report_type}.docx"
end
get '/admin/delete/templates/:id' do
redirect to('/no_access') unless is_administrator?
@xslt = Xslt.first(id: params[:id])
if @xslt
@xslt.components.destroy
@xslt.destroy
File.delete(@xslt.xslt_location) if File.file?(@xslt.xslt_location)
File.delete(@xslt.docx_location) if File.file?(@xslt.docx_location)
serpico_log("Report template deleted")
end
redirect to('/admin/templates')
end
# Manage Templated Reports
post '/admin/templates/add' do
redirect to('/no_access') unless is_administrator?
@admin = true
xslt_file = "./templates/#{rand(36**36).to_s(36)}.xslt"
redirect to('/admin/templates/add') unless params[:file]
# reject if the file is above a certain limit
if params[:file][:tempfile].size > 100_000_000
return 'File too large. 10MB limit'
end
docx = "./templates/#{rand(36**36).to_s(36)}.docx"
File.open(docx, 'wb') { |f| f.write(params[:file][:tempfile].read) }
error = false
detail = ''
begin
xslt = generate_xslt(docx)
xslt_components = generate_xslt_components(docx)
rescue TemplateVerificationError => detail
@error_message = CGI::escapeHTML(detail.errorString)
@tree = CGI::escapeHTML(detail.template_tree)
return haml :template_error
rescue ReportingError => detail
error = true
end
if error
"The report template you uploaded threw an error when parsing:<p><p> #{detail.errorString}"
else
# open up a file handle and write the attachment
File.open(xslt_file, 'wb') { |f| f.write(xslt) }
# extract the screenshot names from the file
screenshot_names = xslt.scan(/\[!!(.*?)!!\]/)
# delete the file data from the attachment
datax = {}
# to prevent traversal we hardcode this
datax['docx_location'] = docx.to_s
datax['xslt_location'] = xslt_file.to_s
datax['description'] = params[:description]
datax['report_type'] = params[:report_type]
datax['screenshot_names'] = screenshot_names.join(',')
data = url_escape_hash(datax)
data['finding_template'] = params[:finding_template] ? true : false
data['status_template'] = params[:status_template] ? true : false
@template = Xslt.first(report_type: data['report_type'])
if @template
@template.update(xslt_location: data['xslt_location'], docx_location: data['docx_location'], description: data['description'], screenshot_names: data['screenshot_names'])
@template.components.destroy
else
@template = Xslt.new(data)
@template.save
end
# create a xslt file for each component
list_components_files = []
xslt_components.each do |component_name, component_xslt|
componentHash = {}
componentHash['xslt_location'] = "./templates/#{rand(36**36).to_s(36)}.xslt"
componentHash['name'] = component_name
componentHash['xslt'] = @template
File.open(componentHash['xslt_location'], 'wb') { |f| f.write(component_xslt) }
list_components_files.push(componentHash)
end
# insert components into the db
list_components_files.each do |component|
@component = Xslt_component.new(component)
@component.save
end
serpico_log("New report template successfully added")
redirect to('/admin/templates')
haml :add_template
end
end
get '/admin/templates/:id/tree' do
redirect to('/no_access') unless is_administrator?
@admin = true
xslt = Xslt.first(id: params[:id])
document = read_rels(xslt.docx_location,"word/document.xml")
@tree = verify_document(document)
@tree = @tree[2]
haml :template_tree
end
# Manage Templated Reports
get '/admin/templates/:id/edit' do
redirect to('/no_access') unless is_administrator?
@admin = true
@template = Xslt.first(id: params[:id])
haml :edit_template
end
# Manage Templated Reports
post '/admin/templates/edit' do
redirect to('/no_access') unless is_administrator?
@admin = true
template = Xslt.first(id: params[:id])
xslt_file = template.xslt_location
redirect to("/admin/templates/#{params[:id]}/edit") unless params[:file]
# reject if the file is above a certain limit
if params[:file][:tempfile].size > 100_000_000
return 'File too large. 10MB limit'
end
docx = "./templates/#{rand(36**36).to_s(36)}.docx"
File.open(docx, 'wb') { |f| f.write(params[:file][:tempfile].read) }
error = false
detail = ''
begin
xslt = generate_xslt(docx)
xslt_components = generate_xslt_components(docx)
rescue TemplateVerificationError => detail
@error_message = CGI::escapeHTML(detail.errorString)
@tree = CGI::escapeHTML(detail.template_tree)
return haml :template_error
rescue ReportingError => detail
error = true
end
if error
"The report template you uploaded threw an error when parsing:<p><p> #{detail.errorString}"
else
# open up a file handle and write the attachment
File.open(xslt_file, 'wb') { |f| f.write(xslt) }
# extract the screenshot names from the file
screenshot_names = xslt.scan(/\[!!(.*?)!!\]/)
# delete the file data from the attachment
datax = {}
# to prevent traversal we hardcode this
datax['docx_location'] = docx.to_s
datax['xslt_location'] = xslt_file.to_s
datax['description'] = params[:description]
datax['report_type'] = params[:report_type]
datax['screenshot_names'] = screenshot_names.join(',')
data = url_escape_hash(datax)
data['finding_template'] = params[:finding_template] ? true : false
data['status_template'] = params[:status_template] ? true : false
@template = Xslt.first(report_type: data['report_type'])
if @template
@template.update(xslt_location: data['xslt_location'], docx_location: data['docx_location'], description: data['description'], screenshot_names: data['screenshot_names'])
@template.components.destroy
else
@template = Xslt.new(data)
@template.save
end
# create a xslt file for each component
list_components_files = []
xslt_components.each do |component_name, component_xslt|
componentHash = {}
componentHash['xslt_location'] = "./templates/#{rand(36**36).to_s(36)}.xslt"
componentHash['name'] = component_name
componentHash['xslt'] = @template
File.open(componentHash['xslt_location'], 'wb') { |f| f.write(component_xslt) }
list_components_files.push(componentHash)
end
# insert components into the db
list_components_files.each do |component|
@component = Xslt_component.new(component)
@component.save
end
serpico_log("Report template modified")
redirect to('/admin/templates')
end
end
# get enabled plugins
get '/admin/admin_plugins' do
@admin = true if is_administrator?
@plugin = true if is_plugin?
@menu = get_plugin_list('admin')
haml :enabled_plugins
end
get '/admin/udo_templates' do
redirect to('/no_access') unless is_administrator?
# delete UDO template part
if params[:delete]
udo_template = UserDefinedObjectTemplates.get(params[:delete])
return 'UDO Template not found' if udo_template.nil?
udo_template.destroy
end
@udos_templates = UserDefinedObjectTemplates.all
@admin = true if is_administrator?
@plugin = true if is_plugin?
haml :user_defined_object_templates
end
post '/admin/udo_templates' do
redirect to('/no_access') unless is_administrator?
data = url_escape_hash(request.POST)
# Save new UDO template part
if data['action'] = 'Save'
new_udo_template = UserDefinedObjectTemplates.new
new_udo_template.type = data['object_type']
udo_properties = {}
# we extract the udo properties from the posted data
data.each do |param, value|
if param =~ /property_/
udo_properties[value] = '' unless value.to_s.empty?
end
end
new_udo_template.udo_properties = udo_properties.to_json
new_udo_template.save
end
@udos_templates = UserDefinedObjectTemplates.all
serpico_log("UDO template added")
redirect to('/admin/udo_templates')
end
# edit udo template
get '/admin/udo_template/:template_id/edit' do
redirect to('/no_access') unless is_administrator?
@udo_to_edit = UserDefinedObjectTemplates.get(params[:template_id])
return 'No such UDO Template' if @udo_to_edit.nil?
@udo_to_edit_properties = JSON.parse(@udo_to_edit.udo_properties)
@admin = true if is_administrator?
@plugin = true if is_plugin?
haml :udo_template_edit
end
post '/admin/udo_template/:template_id/edit' do
redirect to('/no_access') unless is_administrator?
data = url_escape_hash(request.POST)
@udo_to_edit = UserDefinedObjectTemplates.get(params[:template_id])
return 'No such UDO Template' if @udo_to_edit.nil?
@udo_to_edit_properties = JSON.parse(@udo_to_edit.udo_properties)
udo_properties = {}
# we extract the udo properties from the posted data
data.each do |param1, value1|
unless value1.to_s.empty?
# we add the new properties
if param1 =~ /prop_new_\d+/
id = param1.split('_')[2]
data.each do |param2, value2|
next unless param2 =~ /default_new_#{id}/
udo_properties[value1] = if value2 !~ /\<paragraph\>/
"<paragraph>#{value2}</paragraph>"
else
value2
end
end
# we edit the already existing properties
elsif param1 =~ /prop_/
data.each do |param2, value2|
next unless param2 =~ /default_#{param1.split("_")[-1]}/
udo_properties[value1] = if value2 !~ /\<paragraph\>/
"<paragraph>#{value2}</paragraph>"
else
value2
end
end
end
end
end
@udo_to_edit.udo_properties = udo_properties.to_json
@udo_to_edit.save
serpico_log("UDO template modified")
redirect to('/admin/udo_templates')
end
|
0b8600414976a5ad733604c7b1428071baf239c2
|
https://github.com/serpicoproject/serpico
|
order_filtering.blade.php
|
php
|
<script>
function orderRedirection(val) {
alert(val);
}
$(document).ready(function () {
});
</script>
<form method="get" class="js-form-order-filtering">
<div class="manage-toobar d-flex justify-content-between align-items-center">
<div id="cartsnav">
<a href="{{route('admin.order.index')}}"
class="btn btn-link btn-sm px-0 <?php if (!isset($abandoned)): ?>font-weight-bold text-dark active<?php else: ?>text-muted<?php endif; ?>">
<?php _e("Completed orders"); ?> (<?php echo $orders_count; ?>)
</a>
<a href="{{route('admin.order.abandoned')}}"
class="btn btn-link btn-sm <?php if (isset($abandoned)): ?>font-weight-bold text-dark active<?php else: ?>text-muted<?php endif; ?>">
<?php _e("Abandoned carts"); ?> (<?php echo $abandoned_count; ?>)
</a>
</div>
</div>
<?php if ($orders->count() > 0 || $filteringResults) { ?>
<div class="js-filtering-orders-box bg-primary-opacity-1 rounded p-4 mb-4" <?php if (!$filteringResults): ?>style="display: none"<?php endif;?>>
<div class="row d-flex justify-content-between align-content-end">
<div class="col-md-6">
<div class="form-group">
<label for="" class="form-label"><?php _e("Order ID"); ?></label>
<div class="input-group mb-0">
<input type="text" class="form-control" value="{{$id}}" name="id" placeholder="<?php _e("Order ID");?>">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="" class="form-label"><?php _e("Order Status"); ?></label>
<div class="input-group mb-0">
<select name="orderStatus" class="selectpicker" data-width="100%">
<option value="" @if($orderStatus == '') selected="selected" @endif>
<?php _e('All'); ?>
</option>
<option value="new" @if($orderStatus == 'new') selected="selected" @endif>
<?php _e('New'); ?>
</option>
<option value="pending" @if($orderStatus == 'pending') selected="selected" @endif>
<?php _e('Pending'); ?>
</option>
<option value="completed" @if($orderStatus == 'completed') selected="selected" @endif>
<?php _e('Completed'); ?>
</option>
</select>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="" class="form-label"><?php _e("Date from"); ?></label>
<div class="input-group mb-0">
<div class="input-group-prepend">
<span class="input-group-text"><i class="mdi mdi-calendar"></i> </span>
</div>
<input type="text" class="form-control" value="{{$minDate}}" name="minDate" id="js-order-filter-date-from" placeholder="<?php _e("Set the orders from date");?>">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="" class="form-label"><?php _e("Date to"); ?></label>
<div class="input-group mb-0">
<div class="input-group-prepend">
<span class="input-group-text"><i class="mdi mdi-calendar"></i> </span>
</div>
<input type="text" class="form-control" value="{{$maxDate}}" name="maxDate" id="js-order-filter-date-to" placeholder="<?php _e("Set the orders to date");?>">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="" class="form-label"><?php _e("Order amount from"); ?></label>
<div class="input-group mb-0">
<div class="input-group-prepend">
<span class="input-group-text">{{get_currency_symbol()}}</span>
</div>
<input type="number" class="form-control" value="{{$minPrice}}" name="minPrice" placeholder="<?php _e("Show the order with minimum amount");?>">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="" class="form-label"><?php _e("Order amount to"); ?></label>
<div class="input-group mb-0">
<div class="input-group-prepend">
<span class="input-group-text">{{get_currency_symbol()}} </span>
</div>
<input type="number" class="form-control" value="{{$maxPrice}}" name="maxPrice" placeholder="<?php _e("Show the order with maximum amount");?>">
</div>
</div>
</div>
<script>
mw.lib.require("air_datepicker");
if ($.fn.datepicker) {
$.fn.datepicker.language['en'] = {
days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
daysMin: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
daysShort: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
monthsShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
today: 'Today',
clear: 'Clear',
dateFormat: 'yyyy-mm-dd',
firstDay: 0
};
var datePickerBaseSetup = {
language:'en',
timepicker: false,
onSelect: function (fd, d, picker) {
// Do nothing if selection was cleared
if (!d[0]) return;
if (!d[1]) return;
var dateFromRange = d[0].getFullYear() + "-" + numericMonth(d[0]) + "-" + numericDate(d[0]);
var dateToRange = d[1].getFullYear() + "-" + numericMonth(d[1]) + "-" + numericDate(d[1]);
}
};
$('#js-order-filter-date-from').datepicker(datePickerBaseSetup);
$('#js-order-filter-date-to').datepicker(datePickerBaseSetup);
}
$(document).ready(function () {
var searchOrdersByProduct = new mw.autoComplete({
element: "#js-orders-search-by-products",
placeholder: "<?php if ($productKeyword) { echo $productKeyword; } else { _e("Search by products..."); }?>",
autoComplete:true,
ajaxConfig: {
method: 'get',
url: mw.settings.api_url + 'get_content_admin?get_extra_data=1&content_type=product&keyword=${val}'
},
map: {
value: 'id',
title: 'title',
image: 'picture'
}
});
$(searchOrdersByProduct).on("change", function (e, val) {
$(".js-orders-search-product").val(val[0].id).trigger('change')
$(".js-orders-search-product-keyword").val(val[0].title).trigger('change')
});
});
</script>
<div class="col-md-6">
<div class="form-group">
<label for="" class="form-label"><?php _e("Search by products"); ?></label>
<div class="input-group">
<input type="hidden" class="js-orders-search-product-keyword" name="productKeyword" value="{{$productKeyword}}" />
<input type="hidden" class="js-orders-search-product" name="productId" value="{{$productId}}" />
<div id="js-orders-search-by-products"></div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="" class="form-label"><?php _e("Payment Status"); ?></label>
<div class="input-group mb-0">
<select name="isPaid" class="selectpicker" data-width="100%">
<option value="" @if($isPaid == '') selected="selected" @endif>
<?php _e('All'); ?>
</option>
<option value="1" @if($isPaid == '1') selected="selected" @endif>
<?php _e('Paid'); ?>
</option>
<option value="0" @if($isPaid == '0') selected="selected" @endif>
<?php _e('Unpaid'); ?>
</option>
</select>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="" class="form-label"><?php _e("Search"); ?></label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="mdi mdi-magnify"></i></span>
</div>
<input type="text" class="form-control" value="{{$keyword}}" name="keyword" placeholder="<?php _e("Free search by phone, name, email etc...");?>">
</div>
</div>
</div>
<div class="col-md-6">
</div>
<div class="col-md-6">
<div class="d-grid gap-2 d-md-flex justify-content-md-end">
<button type="submit" name="filteringResults" value="true" class="js-submit-order-filtering btn btn-primary mr-2">
<?php _e("Submit this criteria"); ?>
</button>
<a href="{{route('admin.order.index')}}" class="btn btn-outline-primary">
<?php _e("Reset filter"); ?>
</a>
</div>
</div>
</div>
</div>
<?php } ?>
</form>
|
<script>
function orderRedirection(val) {
alert(val);
}
$(document).ready(function () {
});
</script>
<form method="get" class="js-form-order-filtering">
<div class="manage-toobar d-flex justify-content-between align-items-center">
<div id="cartsnav">
<a href="{{route('admin.order.index')}}"
class="btn btn-link btn-sm px-0 <?php if (!isset($abandoned)): ?>font-weight-bold text-dark active<?php else: ?>text-muted<?php endif; ?>">
<?php _e("Completed orders"); ?> (<?php echo $orders_count; ?>)
</a>
<a href="{{route('admin.order.abandoned')}}"
class="btn btn-link btn-sm <?php if (isset($abandoned)): ?>font-weight-bold text-dark active<?php else: ?>text-muted<?php endif; ?>">
<?php _e("Abandoned carts"); ?> (<?php echo $abandoned_count; ?>)
</a>
</div>
</div>
<?php if ($orders->count() > 0 || $filteringResults) { ?>
<div class="js-filtering-orders-box bg-primary-opacity-1 rounded p-4 mb-4" <?php if (!$filteringResults): ?>style="display: none"<?php endif;?>>
<div class="row d-flex justify-content-between align-content-end">
<div class="col-md-6">
<div class="form-group">
<label for="" class="form-label"><?php _e("Order ID"); ?></label>
<div class="input-group mb-0">
<input type="text" class="form-control" value="{{$id}}" name="id" placeholder="<?php _e("Order ID");?>">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="" class="form-label"><?php _e("Order Status"); ?></label>
<div class="input-group mb-0">
<select name="orderStatus" class="selectpicker" data-width="100%">
<option value="" @if($orderStatus == '') selected="selected" @endif>
<?php _e('All'); ?>
</option>
<option value="new" @if($orderStatus == 'new') selected="selected" @endif>
<?php _e('New'); ?>
</option>
<option value="pending" @if($orderStatus == 'pending') selected="selected" @endif>
<?php _e('Pending'); ?>
</option>
<option value="completed" @if($orderStatus == 'completed') selected="selected" @endif>
<?php _e('Completed'); ?>
</option>
</select>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="" class="form-label"><?php _e("Date from"); ?></label>
<div class="input-group mb-0">
<div class="input-group-prepend">
<span class="input-group-text"><i class="mdi mdi-calendar"></i> </span>
</div>
<input type="text" class="form-control" value="{{$minDate}}" name="minDate" id="js-order-filter-date-from" placeholder="<?php _e("Set the orders from date");?>">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="" class="form-label"><?php _e("Date to"); ?></label>
<div class="input-group mb-0">
<div class="input-group-prepend">
<span class="input-group-text"><i class="mdi mdi-calendar"></i> </span>
</div>
<input type="text" class="form-control" value="{{$maxDate}}" name="maxDate" id="js-order-filter-date-to" placeholder="<?php _e("Set the orders to date");?>">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="" class="form-label"><?php _e("Order amount from"); ?></label>
<div class="input-group mb-0">
<div class="input-group-prepend">
<span class="input-group-text">{{get_currency_symbol()}}</span>
</div>
<input type="number" class="form-control" value="{{$minPrice}}" name="minPrice" placeholder="<?php _e("Show the order with minimum amount");?>">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="" class="form-label"><?php _e("Order amount to"); ?></label>
<div class="input-group mb-0">
<div class="input-group-prepend">
<span class="input-group-text">{{get_currency_symbol()}} </span>
</div>
<input type="number" class="form-control" value="{{$maxPrice}}" name="maxPrice" placeholder="<?php _e("Show the order with maximum amount");?>">
</div>
</div>
</div>
<script>
mw.lib.require("air_datepicker");
if ($.fn.datepicker) {
$.fn.datepicker.language['en'] = {
days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
daysMin: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
daysShort: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
monthsShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
today: 'Today',
clear: 'Clear',
dateFormat: 'yyyy-mm-dd',
firstDay: 0
};
var datePickerBaseSetup = {
language:'en',
timepicker: false,
onSelect: function (fd, d, picker) {
// Do nothing if selection was cleared
if (!d[0]) return;
if (!d[1]) return;
var dateFromRange = d[0].getFullYear() + "-" + numericMonth(d[0]) + "-" + numericDate(d[0]);
var dateToRange = d[1].getFullYear() + "-" + numericMonth(d[1]) + "-" + numericDate(d[1]);
}
};
$('#js-order-filter-date-from').datepicker(datePickerBaseSetup);
$('#js-order-filter-date-to').datepicker(datePickerBaseSetup);
}
$(document).ready(function () {
var searchOrdersByProduct = new mw.autoComplete({
element: "#js-orders-search-by-products",
placeholder: "<?php if ($productKeyword) { echo xss_clean($productKeyword); } else { _e("Search by products..."); }?>",
autoComplete:true,
ajaxConfig: {
method: 'get',
url: mw.settings.api_url + 'get_content_admin?get_extra_data=1&content_type=product&keyword=${val}'
},
map: {
value: 'id',
title: 'title',
image: 'picture'
}
});
$(searchOrdersByProduct).on("change", function (e, val) {
$(".js-orders-search-product").val(val[0].id).trigger('change')
$(".js-orders-search-product-keyword").val(val[0].title).trigger('change')
});
});
</script>
<div class="col-md-6">
<div class="form-group">
<label for="" class="form-label"><?php _e("Search by products"); ?></label>
<div class="input-group">
<input type="hidden" class="js-orders-search-product-keyword" name="productKeyword" value="{{$productKeyword}}" />
<input type="hidden" class="js-orders-search-product" name="productId" value="{{$productId}}" />
<div id="js-orders-search-by-products"></div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="" class="form-label"><?php _e("Payment Status"); ?></label>
<div class="input-group mb-0">
<select name="isPaid" class="selectpicker" data-width="100%">
<option value="" @if($isPaid == '') selected="selected" @endif>
<?php _e('All'); ?>
</option>
<option value="1" @if($isPaid == '1') selected="selected" @endif>
<?php _e('Paid'); ?>
</option>
<option value="0" @if($isPaid == '0') selected="selected" @endif>
<?php _e('Unpaid'); ?>
</option>
</select>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="" class="form-label"><?php _e("Search"); ?></label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="mdi mdi-magnify"></i></span>
</div>
<input type="text" class="form-control" value="{{$keyword}}" name="keyword" placeholder="<?php _e("Free search by phone, name, email etc...");?>">
</div>
</div>
</div>
<div class="col-md-6">
</div>
<div class="col-md-6">
<div class="d-grid gap-2 d-md-flex justify-content-md-end">
<button type="submit" name="filteringResults" value="true" class="js-submit-order-filtering btn btn-primary mr-2">
<?php _e("Submit this criteria"); ?>
</button>
<a href="{{route('admin.order.index')}}" class="btn btn-outline-primary">
<?php _e("Reset filter"); ?>
</a>
</div>
</div>
</div>
</div>
<?php } ?>
</form>
|
724e2d186a33c0c27273107dc4f160a09384877f
|
https://github.com/microweber/microweber
|
filesave.php
|
php
|
<?php
if(!empty($_POST['data'])){
$fname = $_POST['file'];
//check if file name ends with .json
if(substr($fname, -1, 5) != '.json') {
echo '<script>alert("ERROR: Incorrect file type submitted")</script>';
return;
}
$data = $_POST['data'];
$file = fopen($fname, "w");
fwrite($file, $data);
fclose($file);
}
?>
|
<?php
if(!empty($_POST['data'])){
$fname = $_POST['file'];
//check if file name ends with .json
if(substr($fname, -5) != '.json') {
echo '<script>alert("ERROR: Incorrect file type submitted")</script>';
return;
}
$data = $_POST['data'];
$file = fopen($fname, "w");
fwrite($file, $data);
fclose($file);
}
?>
|
445325c7cf1148a8cd38af3a90789c6cbf6c5112
|
https://github.com/erohtar/dasherr
|
ipv4.inc.php
|
php
|
<div class="panel panel-default panel-condensed">
<div class="panel-heading">
<strong>IPv4 Addresses</strong>
</div>
<table id="ipv4-search" class="table table-hover table-condensed table-striped">
<thead>
<tr>
<th data-column-id="hostname" data-order="asc">Device</th>
<th data-column-id="interface">Interface</th>
<th data-column-id="address" data-sortable="false" data-formatter="tooltip">Address</th>
<th data-column-id="description" data-sortable="false" data-formatter="tooltip">Description</th>
</tr>
</thead>
</table>
</div>
<script>
var grid = $("#ipv4-search").bootgrid({
ajax: true,
rowCount: [50, 100, 250, -1],
templates: {
header: "<div id=\"{{ctx.id}}\" class=\"{{css.header}}\"><div class=\"row\">"+
"<div class=\"col-sm-9 actionBar\"><span class=\"pull-left\">"+
"<form method=\"post\" action=\"\" class=\"form-inline\" role=\"form\">"+
"<?php echo addslashes(csrf_field()) ?>"+
"<div class=\"form-group\">"+
"<select name=\"device_id\" id=\"device_id\" class=\"form-control input-sm\">"+
"<option value=\"\">All Devices</option>"+
<?php
$sql = 'SELECT `devices`.`device_id`,`hostname`,`sysName`,`display` FROM `devices`';
$param = [];
if (! Auth::user()->hasGlobalRead()) {
$device_ids = Permissions::devicesForUser()->toArray() ?: [0];
$where .= ' WHERE `devices`.`device_id` IN ' . dbGenPlaceholders(count($device_ids));
$param = array_merge($param, $device_ids);
}
$sql .= " $where ORDER BY `hostname`";
foreach (dbFetchRows($sql, $param) as $data) {
echo '"<option value=\"' . $data['device_id'] . '\""+';
if ($data['device_id'] == $_POST['device_id']) {
echo '" selected "+';
}
echo '">' . format_hostname($data) . '</option>"+';
}
?>
"</select>"+
"</div> "+
"<div class=\"form-group\">"+
"<select name=\"interface\" id=\"interface\" class=\"form-control input-sm\">"+
"<option value=\"\">All Interfaces</option>"+
"<option value=\"Loopback%\""+
<?php
if ($_POST['interface'] == 'Loopback%') {
echo '" selected "+';
}
?>
">Loopbacks</option>"+
"<option value=\"Vlan%\""+
<?php
if ($_POST['interface'] == 'Vlan%') {
echo '" selected "+';
}
?>
">VLANs</option>"+
"</select>"+
"</div> "+
"<div class=\"form-group\">"+
"<input type=\"text\" name=\"address\" id=\"address\" size=40 value=\"<?php echo $_POST['address']; ?>\" class=\"form-control input-sm\" placeholder=\"IPv4 Address\"/>"+
"</div> "+
"<button type=\"submit\" class=\"btn btn-default input-sm\">Search</button>"+
"</form></span></div>"+
"<div class=\"col-sm-3 actionBar\"><p class=\"{{css.actions}}\"></p></div></div></div>"
},
post: function ()
{
return {
id: "address-search",
search_type: "ipv4",
device_id: '<?php echo htmlspecialchars($_POST['device_id']); ?>',
interface: '<?php echo htmlspecialchars($_POST['interface']); ?>',
address: '<?php echo htmlspecialchars($_POST['address']); ?>'
};
},
url: "ajax_table.php",
formatters: {
"tooltip": function (column, row) {
var value = row[column.id];
return "<span title=\'" + value + "\' data-toggle=\'tooltip\'>" + value + "</span>";
},
},
});
</script>
|
<div class="panel panel-default panel-condensed">
<div class="panel-heading">
<strong>IPv4 Addresses</strong>
</div>
<table id="ipv4-search" class="table table-hover table-condensed table-striped">
<thead>
<tr>
<th data-column-id="hostname" data-order="asc">Device</th>
<th data-column-id="interface">Interface</th>
<th data-column-id="address" data-sortable="false" data-formatter="tooltip">Address</th>
<th data-column-id="description" data-sortable="false" data-formatter="tooltip">Description</th>
</tr>
</thead>
</table>
</div>
<script>
var grid = $("#ipv4-search").bootgrid({
ajax: true,
rowCount: [50, 100, 250, -1],
templates: {
header: "<div id=\"{{ctx.id}}\" class=\"{{css.header}}\"><div class=\"row\">"+
"<div class=\"col-sm-9 actionBar\"><span class=\"pull-left\">"+
"<form method=\"post\" action=\"\" class=\"form-inline\" role=\"form\">"+
"<?php echo addslashes(csrf_field()) ?>"+
"<div class=\"form-group\">"+
"<select name=\"device_id\" id=\"device_id\" class=\"form-control input-sm\">"+
"<option value=\"\">All Devices</option>"+
<?php
$sql = 'SELECT `devices`.`device_id`,`hostname`,`sysName`,`display` FROM `devices`';
$param = [];
if (! Auth::user()->hasGlobalRead()) {
$device_ids = Permissions::devicesForUser()->toArray() ?: [0];
$where .= ' WHERE `devices`.`device_id` IN ' . dbGenPlaceholders(count($device_ids));
$param = array_merge($param, $device_ids);
}
$sql .= " $where ORDER BY `hostname`";
foreach (dbFetchRows($sql, $param) as $data) {
echo '"<option value=\"' . $data['device_id'] . '\""+';
if ($data['device_id'] == $_POST['device_id']) {
echo '" selected "+';
}
echo '">' . format_hostname($data) . '</option>"+';
}
?>
"</select>"+
"</div> "+
"<div class=\"form-group\">"+
"<select name=\"interface\" id=\"interface\" class=\"form-control input-sm\">"+
"<option value=\"\">All Interfaces</option>"+
"<option value=\"Loopback%\""+
<?php
if ($_POST['interface'] == 'Loopback%') {
echo '" selected "+';
}
?>
">Loopbacks</option>"+
"<option value=\"Vlan%\""+
<?php
if ($_POST['interface'] == 'Vlan%') {
echo '" selected "+';
}
?>
">VLANs</option>"+
"</select>"+
"</div> "+
"<div class=\"form-group\">"+
"<input type=\"text\" name=\"address\" id=\"address\" size=40 value=\"<?php echo htmlspecialchars($_POST['address']); ?>\" class=\"form-control input-sm\" placeholder=\"IPv4 Address\"/>"+
"</div> "+
"<button type=\"submit\" class=\"btn btn-default input-sm\">Search</button>"+
"</form></span></div>"+
"<div class=\"col-sm-3 actionBar\"><p class=\"{{css.actions}}\"></p></div></div></div>"
},
post: function ()
{
return {
id: "address-search",
search_type: "ipv4",
device_id: '<?php echo htmlspecialchars($_POST['device_id']); ?>',
interface: '<?php echo htmlspecialchars($_POST['interface']); ?>',
address: '<?php echo htmlspecialchars($_POST['address']); ?>'
};
},
url: "ajax_table.php",
formatters: {
"tooltip": function (column, row) {
var value = row[column.id];
return "<span title=\'" + value + "\' data-toggle=\'tooltip\'>" + value + "</span>";
},
},
});
</script>
|
e4c46a45364cb944b94abf9b83f0558b2c4c2fb7
|
https://github.com/librenms/librenms
|
fm_api.php
|
php
|
<?php
// Init
//error_reporting(NULL);
include($_SERVER['DOCUMENT_ROOT']."/inc/main.php");
include($_SERVER['DOCUMENT_ROOT']."/file_manager/fm_core.php");
// todo: set in session?
if (empty($panel)) {
$command = VESTA_CMD."v-list-user '".$user."' 'json'";
exec ($command, $output, $return_var);
if ( $return_var > 0 ) {
header("Location: /error/");
exit;
}
$panel = json_decode(implode('', $output), true);
}
$fm = new FileManager($user);
$fm->setRootDir($panel[$user]['HOME']);
$_REQUEST['action'] = empty($_REQUEST['action']) ? '' : $_REQUEST['action'];
switch ($_REQUEST['action']) {
case 'cd':
$dir = $_REQUEST['dir'];
print json_encode($fm->ls($dir));
break;
case 'check_file_type':
$dir = $_REQUEST['dir'];
print json_encode($fm->checkFileType($dir));
break;
case 'rename_file':
$dir = $_REQUEST['dir'];
$item = $dir . '/' . $_REQUEST['item'];
$target_name = $dir . '/' . $_REQUEST['target_name'];
print json_encode($fm->renameFile($item, $target_name));
break;
case 'rename_directory':
$dir = $_REQUEST['dir'];
$item = $dir.$_REQUEST['item'];
$target_name = $dir.$_REQUEST['target_name'];
print json_encode($fm->renameDirectory($item, $target_name));
break;
case 'move_file':
$item = $_REQUEST['item'];
$target_name = $_REQUEST['target_name'];
print json_encode($fm->renameFile($item, $target_name));
break;
case 'move_directory':
$item = $_REQUEST['item'];
$target_name = $_REQUEST['target_name'];
print json_encode($fm->renameDirectory($item, $target_name));
break;
case 'delete_files':
$dir = $_REQUEST['dir'];
$item = $_REQUEST['item'];
print json_encode($fm->deleteItem($dir, $item));
break;
case 'create_file':
$dir = $_REQUEST['dir'];
$filename = $_REQUEST['filename'];
print json_encode($fm->createFile($dir, $filename));
break;
case 'create_dir':
$dir = $_REQUEST['dir'];
$dirname = $_REQUEST['dirname'];
print json_encode($fm->createDir($dir, $dirname));
break;
case 'open_file':
$dir = $_REQUEST['dir'];
print json_encode($fm->open_file($dir));
break;
case 'copy_file':
$dir = $_REQUEST['dir'];
$target_dir = $_REQUEST['dir_target'];
$filename = $_REQUEST['filename'];
$item = $_REQUEST['item'];
print json_encode($fm->copyFile($item, $dir, $target_dir, $filename));
break;
case 'copy_directory':
$dir = $_REQUEST['dir'];
$target_dir = $_REQUEST['dir_target'];
$filename = $_REQUEST['filename'];
$item = $_REQUEST['item'];
print json_encode($fm->copyDirectory($item, $dir, $target_dir, $filename));
break;
case 'unpack_item':
$dir = $_REQUEST['dir'];
$target_dir = $_REQUEST['dir_target'];
$filename = $_REQUEST['filename'];
$item = $_REQUEST['item'];
print json_encode($fm->unpackItem($item, $dir, $target_dir, $filename));
break;
case 'pack_item':
$items = $_REQUEST['items'];
$dst_item = $_REQUEST['dst_item'];
print json_encode($fm->packItem($items, $dst_item));
break;
case 'backup':
$path = $_REQUEST['path'];
print json_encode($fm->backupItem($path));
break;
case 'chmod_item':
$dir = $_REQUEST['dir'];
$item = $_REQUEST['item'];
$permissions = $_REQUEST['permissions'];
print json_encode($fm->chmodItem($dir, $item, $permissions));
break;
default:
//print json_encode($fm->init());
break;
}
|
<?php
// Init
//error_reporting(NULL);
header('Content-Type: application/json');
include($_SERVER['DOCUMENT_ROOT']."/inc/main.php");
include($_SERVER['DOCUMENT_ROOT']."/file_manager/fm_core.php");
// todo: set in session?
if (empty($panel)) {
$command = VESTA_CMD."v-list-user '".$user."' 'json'";
exec ($command, $output, $return_var);
if ( $return_var > 0 ) {
header("Location: /error/");
exit;
}
$panel = json_decode(implode('', $output), true);
}
$fm = new FileManager($user);
$fm->setRootDir($panel[$user]['HOME']);
$_REQUEST['action'] = empty($_REQUEST['action']) ? '' : $_REQUEST['action'];
switch ($_REQUEST['action']) {
case 'cd':
$dir = $_REQUEST['dir'];
print json_encode($fm->ls($dir));
break;
case 'check_file_type':
$dir = $_REQUEST['dir'];
print json_encode($fm->checkFileType($dir));
break;
case 'rename_file':
$dir = $_REQUEST['dir'];
$item = $dir . '/' . $_REQUEST['item'];
$target_name = $dir . '/' . $_REQUEST['target_name'];
print json_encode($fm->renameFile($item, $target_name));
break;
case 'rename_directory':
$dir = $_REQUEST['dir'];
$item = $dir.$_REQUEST['item'];
$target_name = $dir.$_REQUEST['target_name'];
print json_encode($fm->renameDirectory($item, $target_name));
break;
case 'move_file':
$item = $_REQUEST['item'];
$target_name = $_REQUEST['target_name'];
print json_encode($fm->renameFile($item, $target_name));
break;
case 'move_directory':
$item = $_REQUEST['item'];
$target_name = $_REQUEST['target_name'];
print json_encode($fm->renameDirectory($item, $target_name));
break;
case 'delete_files':
$dir = $_REQUEST['dir'];
$item = $_REQUEST['item'];
print json_encode($fm->deleteItem($dir, $item));
break;
case 'create_file':
$dir = $_REQUEST['dir'];
$filename = $_REQUEST['filename'];
print json_encode($fm->createFile($dir, $filename));
break;
case 'create_dir':
$dir = $_REQUEST['dir'];
$dirname = $_REQUEST['dirname'];
print json_encode($fm->createDir($dir, $dirname));
break;
case 'open_file':
$dir = $_REQUEST['dir'];
print json_encode($fm->open_file($dir));
break;
case 'copy_file':
$dir = $_REQUEST['dir'];
$target_dir = $_REQUEST['dir_target'];
$filename = $_REQUEST['filename'];
$item = $_REQUEST['item'];
print json_encode($fm->copyFile($item, $dir, $target_dir, $filename));
break;
case 'copy_directory':
$dir = $_REQUEST['dir'];
$target_dir = $_REQUEST['dir_target'];
$filename = $_REQUEST['filename'];
$item = $_REQUEST['item'];
print json_encode($fm->copyDirectory($item, $dir, $target_dir, $filename));
break;
case 'unpack_item':
$dir = $_REQUEST['dir'];
$target_dir = $_REQUEST['dir_target'];
$filename = $_REQUEST['filename'];
$item = $_REQUEST['item'];
print json_encode($fm->unpackItem($item, $dir, $target_dir, $filename));
break;
case 'pack_item':
$items = $_REQUEST['items'];
$dst_item = $_REQUEST['dst_item'];
print json_encode($fm->packItem($items, $dst_item));
break;
case 'backup':
$path = $_REQUEST['path'];
print json_encode($fm->backupItem($path));
break;
case 'chmod_item':
$dir = $_REQUEST['dir'];
$item = $_REQUEST['item'];
$permissions = $_REQUEST['permissions'];
print json_encode($fm->chmodItem($dir, $item, $permissions));
break;
default:
//print json_encode($fm->init());
break;
}
|
c28c5d29a3c61bc8110c11349e3f2309cd537cfa
|
https://github.com/serghey-rodin/vesta
|
01article.php
|
php
|
<?PHP
/*
01-Artikelsystem V3 - Copyright 2006-2015 by Michael Lorer - 01-Scripts.de
Lizenz: Creative-Commons: Namensnennung-Keine kommerzielle Nutzung-Weitergabe unter gleichen Bedingungen 3.0 Deutschland
Weitere Lizenzinformationen unter: http://www.01-scripts.de/lizenz.php
Modul: 01article
Dateiinfo: Frontend-Ausgabe 01-Artikelsystem
#fv.321#
*/
//Hinweis zum Einbinden des Artikelsystems per include();
/*Folgender PHP-Code ntig:
<?PHP
$subfolder = "01scripts/";
$modul = "01article/";
include($subfolder."01module/".$modul."01article.php");
?>
*/
$frontp = 1;
$flag_acp = FALSE;
if(!isset($flag_utf8)) $flag_utf8 = FALSE;
if(!isset($flag_nocss)) $flag_nocss = FALSE;
if(!isset($flag_second)) $flag_second= FALSE;
@ini_set('session.use_trans_sid',0);
if(isset($subfolder) && !empty($subfolder)){
if(substr_count($subfolder, "/") < 1){ $subfolder .= "/"; }
}
elseif(isset($_GET['rss']) && ($_GET['rss'] == "show_rssfeed" || $_GET['rss'] == "show_commentrssfeed"))
$subfolder = "../../";
else
$subfolder = "";
// Globale Config-Datei einbinden
include_once($subfolder."01_config.php");
include_once($subfolder."01acp/system/headinclude.php");
if(!$flag_second) include_once($subfolder."01acp/system/functions.php");
$modulvz = $modul."/";
// Modul-Config-Dateien einbinden
include_once($moduldir.$modulvz."_headinclude.php");
include_once($moduldir.$modulvz."_functions.php");
// Variablen
$imagepf = $moduldir.$modulvz.$imagepf; // Pfad zum Bild-Verzeichnis
$tempdir = $moduldir.$modulvz.$tempdir; // Template-Verzeichnis
$filename = $_SERVER['PHP_SELF']; // Variable enthlt die Adresse der Datei, auf der das Artikelsystem eingebunden wurde
$flag_comments_js = TRUE; // Kommentar-Feld per Default via JavaScript ausblenden?
// Language-File einbinden
include_once($tempdir."lang_vars.php");
// Weitere Variablen +Bitte nehmen Sie hier keine nderungen vor+
$sites = 0;
$qt = 0;
$svl2a = "";
$qt_query = "";
$flag_archiv = "";
$flag_IamStandard = FALSE;
// ggf. Zuweisung $show[] -> $_GET[]
if(!isset($_REQUEST[$names['catid']]) && isset($show['catid']) && !empty($show['catid'])) $_REQUEST[$names['catid']] = $show['catid'];
if(!isset($_REQUEST[$names['search']]) && isset($show['search']) && !empty($show['search'])) $_REQUEST[$names['search']] = $show['search'];
if(!isset($_REQUEST[$names['page']]) && isset($show['page']) && !empty($show['page'])) $_REQUEST[$names['page']] = $show['page'];
if(!isset($_GET[$names['artid']]) && isset($show['artid']) && !empty($show['artid'])) $_GET[$names['artid']] = $show['artid'];
// Notice: Undefined index: ... beheben & strip_tags auf bergebene Werte anwenden (+ Anti-XSS)
if(!isset($_REQUEST[$names['search']])) $_REQUEST[$names['search']] = "";
else $_REQUEST[$names['search']] = strip_tags($_REQUEST[$names['search']]);
if(!isset($_REQUEST[$names['page']])) $_REQUEST[$names['page']] = "";
else $_REQUEST[$names['page']] = strip_tags($_REQUEST[$names['page']]);
if(!isset($_REQUEST[$names['catid']])) $_REQUEST[$names['catid']] = "";
else $_REQUEST[$names['catid']] = strip_tags($_REQUEST[$names['catid']]);
if(!isset($_REQUEST[$names['cpage']])) $_REQUEST[$names['cpage']] = "";
else $_REQUEST[$names['cpage']] = strip_tags($_REQUEST[$names['cpage']]);
if(!isset($_REQUEST[$names['rss']])) $_REQUEST[$names['rss']] = "";
else $_REQUEST[$names['rss']] = strip_tags($_REQUEST[$names['rss']]);
if(!isset($_GET[$names['artid']])) $_GET[$names['artid']] = "";
else $_GET[$names['artid']] = strip_tags($_GET[$names['artid']]);
if(!isset($_GET[$names['cpage']])) $_GET[$names['cpage']] = "";
else $_GET[$names['cpage']] = strip_tags($_GET[$names['cpage']]);
if(!isset($_GET[$names['rss']])) $_GET[$names['rss']] = "";
else $_GET[$names['rss']] = strip_tags($_GET[$names['rss']]);
if(!isset($static)) $static = 0;
if(!isset($_POST['deaktiv_bbc'])) $_POST['deaktiv_bbc'] = 0;
else $_POST['deaktiv_bbc'] = strip_tags($_POST['deaktiv_bbc']);
if(!isset($_GET[$names['page']]) || isset($_GET[$names['page']]) && $_GET[$names['page']] != $_REQUEST[$names['page']]) $_GET[$names['page']] = $_REQUEST[$names['page']];
if(!isset($_POST['antispam'])) $_POST['antispam'] = "";
//Link-String generieren
$system_link = addParameter2Link(_01article_echo_ArticleLink($_GET[$names['artid']]),$names['search']."=".$_REQUEST[$names['search']]."&".$names['page']."=".$_REQUEST[$names['page']]."&".$names['catid']."=".$_REQUEST[$names['catid']]);
$system_link_index = parse_cleanerlinks(addParameter2Link($filename,$names['search']."=".$_REQUEST[$names['search']]."&".$names['page']."=".$_REQUEST[$names['page']]."&".$names['catid']."=".$_REQUEST[$names['catid']]));
$system_link_rss = $subfolder."01module/".$modul."/01article.php";
// Ausfhrung der weiteren Seite wird nach dem Aufruf der ntigen RSS-Funktionen durch exit; unterbrochen
if(isset($_GET[$names['rss']]) && ($_GET[$names['rss']] == "show_rssfeed" || $_GET[$names['rss']] == "show_commentrssfeed") &&
$settings['rss_aktiv'] == 1 && ($settings['artikelrssfeedaktiv'] == 1 || $settings['artikelkommentarfeed'] == 1)){
if(!isset($_GET['entries'])) $_GET['entries'] = "";
else $_GET['entries'] = strip_tags($_GET['entries']);
include_once($subfolder."01acp/system/includes/htmLawed.php");
header("Content-type: text/xml");
echo _01article_RSS($_GET[$names['rss']],$_GET['entries'],$_REQUEST[$names['catid']]);
exit;
}
elseif(isset($_GET[$names['rss']]) && ($_GET[$names['rss']] == "show_rssfeed" || $_GET[$names['rss']] == "show_commentrssfeed")){
echo "Fehler: Der RSS-Feed wurde deaktiviert!";
exit;
}
// CSS-Datei einbinden
if(isset($settings['extern_css']) && !empty($settings['extern_css']) && filter_var($settings['extern_css'], FILTER_VALIDATE_URL) !== FALSE && !$flag_nocss)
$echo_css = "<link rel=\"stylesheet\" type=\"text/css\" href=\"".$settings['extern_css']."\" />";
elseif(!$flag_nocss)
$echo_css = "<link rel=\"stylesheet\" type=\"text/css\" href=\"".$tempdir."style.css\" />";
else $echo_css = "";
// Alle Kategorien in einen mehrdimensionalen Array einlesen
$listcat = $mysqli->query("SELECT * FROM ".$mysql_tables['cats']." ORDER BY sortid,name");
while($rowcat = $listcat->fetch_assoc()){
$category[$rowcat['id']]['id'] = $rowcat['id'];
$category[$rowcat['id']]['name'] = htmlentities($rowcat['name'],$htmlent_flags,$htmlent_encoding_acp);
$category[$rowcat['id']]['catpic'] = $rowcat['catpic'];
}
// ggf. Archiv-Zeit berechnen
if(!empty($settings['archiv_time']) && $settings['archiv_time'] > 0 && is_numeric($settings['archiv_time']))
$qt = time()-($settings['archiv_time']*24*60*60);
// Alternative Abfrage, wenn nur ein Artikel / eine Seite angezeigt werden soll
if(isset($_GET[$names['artid']]) && !empty($_GET[$names['artid']]) && $_GET[$names['artid']] != "archiv" && $_GET[$names['artid']] > 0 && is_numeric($_GET[$names['artid']])){
$query = "SELECT * FROM ".$mysql_tables['artikel']." WHERE frei='1' AND hide='0' AND utimestamp <= '".time()."' AND (endtime >= '".time()."' OR endtime = '0') AND id = '".$mysqli->escape_string($_GET[$names['artid']])."' LIMIT 1";
$iderror = 1;
//Hits +1:
$mysqli->query("UPDATE ".$mysql_tables['artikel']." SET hits = hits+1 WHERE id = '".$mysqli->escape_string($_GET[$names['artid']])."' LIMIT 1");
}
// Archiv-Ansicht
elseif(isset($_GET[$names['artid']]) && $_GET[$names['artid']] == "archiv" && !empty($settings['archiv_time']) && $settings['archiv_time'] > 0 && is_numeric($settings['archiv_time'])){
$flag_archiv = "&".$names['artid']."=archiv";
$add2query_cat = _01article_CreateCatQuery($_REQUEST[$names['catid']]);
$query = "SELECT * FROM ".$mysql_tables['artikel']." WHERE frei='1' AND hide='0' AND static = '0' AND (utimestamp <= '".$qt."' OR (endtime <= '".time()."' AND endtime != '0')) AND (endtime <= '".time()."' OR endtime = '0') AND (".$add2query_cat.") ORDER BY utimestamp DESC";
$settings['articleperpage'] = ANZ_PP_ARCHIV;
makepages($query,$sites,$names['page'],$settings['articleperpage']);
$iderror = 1;
}
// Alle Artikel anzeigen
else{
if(!empty($settings['archiv_time']) && $settings['archiv_time'] > 0 && is_numeric($settings['archiv_time']))
$qt_query = "AND (utimestamp>'".$qt."' OR top = '1' OR endtime >= '".time()."') ";
else $qt_query = "";
if(isset($_REQUEST[$names['search']]) && !empty($_REQUEST[$names['search']]) && $settings['artikelsuche'] == 1){
if($flag_utf8)
$parsed_searchstring = $mysqli->escape_string(parse_uml(utf8_decode(str_replace("*","",$_REQUEST[$names['search']]))));
else
$parsed_searchstring = $mysqli->escape_string(parse_uml(str_replace("*","",$_REQUEST[$names['search']])));
$add2query_cat = _01article_CreateCatQuery($_REQUEST[$names['catid']]);
$add2query = "AND MATCH (titel,content,zusammenfassung) AGAINST ('".$parsed_searchstring."') >= ".FULLTEXT_INDEX_SEARCH_SCHWELLE." AND (".$add2query_cat.")";
$iderror = 2; // Flag fr Fehlermeldung in main_top
}
elseif(isset($_REQUEST[$names['catid']]) && !empty($_REQUEST[$names['catid']])){
$add2query_cat = _01article_CreateCatQuery($_REQUEST[$names['catid']]);
$add2query = $qt_query."AND (".$add2query_cat.") ORDER BY top DESC,utimestamp DESC";
$iderror = 3; // Flag fr Fehlermeldung in main_top
}
else{
$add2query = $qt_query."ORDER BY top DESC,utimestamp DESC";
$flag_IamStandard = true;
$iderror = 1; // Flag fr Fehlermeldung in main_top
}
$query = "SELECT * FROM ".$mysql_tables['artikel']." WHERE frei='1' AND hide='0' AND static='0' AND utimestamp <= '".time()."' AND (endtime >= '".time()."' OR endtime='0') ".$add2query;
makepages($query,$sites,$names['page'],$settings['articleperpage']);
}
// List > 0?
$list = $mysqli->query($query);
echo "<!-- 2559ad821dde361560dbf967c3406f51 -->";
// Wenn nichts angezeigt werden konnte neuer Versuch mit Standardabfrage
if($list->num_rows == 0 && !$flag_IamStandard){
$query = "SELECT * FROM ".$mysql_tables['artikel']." WHERE frei='1' AND hide='0' AND static='0' AND utimestamp <= '".time()."' AND (endtime >= '".time()."' OR endtime='0') ".$qt_query."ORDER BY top DESC,utimestamp DESC";
makepages($query,$sites,$names['page'],$settings['articleperpage']);
$list = $mysqli->query($query);
$_GET[$names['artid']] = "";
}
elseif($list->num_rows > 0){
if(isset($_REQUEST[$names['search']]) && !empty($_REQUEST[$names['search']]) && $settings['artikelsuche'] == 1)
$iderror = 4;
elseif(isset($_REQUEST[$names['catid']]) && !empty($_REQUEST[$names['catid']]))
$iderror = 5;
else
$iderror = 0; // Flag fr Fehlermeldung zurcksetzen, wenn mind. 1 Artikel angezeigt werden kann
}
// main_top einbinden
include($tempdir."main_top.html");
// ARCHIV
if(isset($_GET[$names['artid']]) && $_GET[$names['artid']] == "archiv" && !empty($settings['archiv_time']) && $settings['archiv_time'] > 0 && is_numeric($settings['archiv_time'])){
include($tempdir."archiv_top.html");
$round = 1;
while($row = $list->fetch_assoc()){
if($round == 1){
$archiv_year = date("Y",$row['utimestamp']);
$archiv_month = date("n",$row['utimestamp']);
include($tempdir."archiv_top_year.html");
include($tempdir."archiv_top_month.html");
}
if($archiv_year != date("Y",$row['utimestamp'])){
$archiv_year = date("Y",$row['utimestamp']);
include($tempdir."archiv_top_year.html");
}
if($archiv_month != date("n",$row['utimestamp'])){
$archiv_month = date("n",$row['utimestamp']);
include($tempdir."archiv_top_month.html");
}
$datum = date("d.m.y",$row['utimestamp']).", ".date("G:i",$row['utimestamp']);
$titel = $row['titel'];
$username_array = getUserdatafields($row['uid'],"username");
$autor = htmlentities($username_array['username'],$htmlent_flags,$htmlent_encoding_acp);
include($tempdir."archiv_bit.html");
$round++;
}
include($tempdir."archiv_bottom.html");
$iderror = 0;
}
// NORMALE AUSGABE
else{
while($row = $list->fetch_assoc()){
$datum = date("d.m.y",$row['utimestamp']);
$uhrzeit = date("G:i",$row['utimestamp']);
//Catid & Catimage auslesen
if($row['newscatid'] != "0"){
$c = 0;
$catimg = ""; $catname = "";
$newscatids_array = explode(",",substr($row['newscatid'],1,strlen($row['newscatid'])-2));
foreach($newscatids_array as $newscatid_s){
if(isset($category[$newscatid_s]['name'])){
if(isset($category[$newscatid_s]['catpic']) && $category[$newscatid_s]['catpic'] != "")
$catimg .= "<a href=\"".addParameter2Link($filename,$names['catid']."=".$newscatid_s)."\"><img src=\"".$catuploaddir.$category[$newscatid_s]['catpic']."\" alt=\"Kategorie: ".$category[$newscatid_s]['name']."\" title=\"Kategorie: ".$category[$newscatid_s]['name']."\" align=\"left\" /></a> ";
else
$catimg .= "";
if($c > 0) $catname .= ", ";
$catname .= "<a href=\"".addParameter2Link($filename,$names['catid']."=".$newscatid_s)."\" class=\"catlink\">".$category[$newscatid_s]['name']."</a>";
$c++;
}
}
}
else{ $catimg = ""; $catname = ""; }
$more = 0;
// Normalen, kompletten Haupttext anzeigen
if((isset($_GET[$names['artid']]) && !empty($_GET[$names['artid']]) ||
$settings['artikeleinleitung'] == 0 ||
$settings['artikeleinleitung'] == 2 && $row['autozusammen'] == 0 && empty($row['zusammenfassung'])) &&
(!isset($_REQUEST[$names['search']]) || isset($_REQUEST[$names['search']]) && empty($_REQUEST[$names['search']]) || $iderror == 2)){
$artikeltext = $row['content'];
$artikeltext = str_replace("../01pics/",$picuploaddir,$artikeltext);
$artikeltext = str_replace("../01files/",$attachmentuploaddir,$artikeltext);
if($settings['artikellightbox'] == 1) $artikeltext = str_replace("class=\"lightbox\"","class=\"lightbox\" rel=\"lightbox-art".$row['id']."\"",$artikeltext);
$artikeltext = preg_replace_callback("/\{Insert#(\d+)GalleryPicsFrom#(\d+)\}/","_01article_callback_GetGalThumbs4Article",$artikeltext);
}
// Zusammenfassung anzeigen
else{
if($row['autozusammen'] == 0 && !empty($row['zusammenfassung'])){
$artikeltext = $row['zusammenfassung'];
$artikeltext = str_replace("../01pics/",$picuploaddir,$artikeltext);
$artikeltext = str_replace("../01files/",$attachmentuploaddir,$artikeltext);
if($settings['artikellightbox'] == 1) $artikeltext = str_replace("class=\"lightbox\"","class=\"lightbox\" rel=\"lightbox-art".$row['id']."\"",$artikeltext);
}
else{
$artikeltext = "<p>".substr(strip_tags($row['content']),0,$settings['artikeleinleitungslaenge']).$lang['weiterlesen']."</p>";
if($settings['artikellightbox'] == 1) $artikeltext = str_replace("class=\"lightbox\"","class=\"lightbox\" rel=\"lightbox-art".$row['id']."\"",$artikeltext);
}
$artikeltext = preg_replace_callback("/\{Insert#(\d+)GalleryPicsFrom#(\d+)\}/","_01article_callback_GetGalThumbs4Article",$artikeltext);
// Weiterlesen-Link nur einbinden, wenn Text lnger als Zusammenfassung oder eigener Text eingegeben wurde
if($row['autozusammen'] == 0 && !empty($row['zusammenfassung']) ||
strlen($artikeltext) < strlen($row['content']))
$more = 1;
else $more = 0;
}
// Anzahl bisheriger Kommentare ermitteln
if($settings['comments'] == 1){
$comments = 0;
list($comments) = $mysqli->query("SELECT COUNT(*) FROM ".$mysql_tables['comments']." WHERE frei = '1' AND modul = '".$mysqli->escape_string($modul)."' AND postid = '".$row['id']."'")->fetch_array(MYSQLI_NUM);
}
// Weitere Variablen fr die Template-Ausgabe aufbereiten
$username_array = getUserdatafields($row['uid'],"username,01acp_signatur");
$username = htmlentities($username_array['username'],$htmlent_flags,$htmlent_encoding_acp);
if(!empty($username_array['signatur']) && $more == 0 && $row['hide_signature'] == 0)
$signatur = "<p class=\"signatur\">".nl2br(str_replace("&","&",$username_array['signatur']))."</p>";
if($flag_utf8) $signatur = utf8_encode($signatur);
else
$signatur = "";
$titel = $row['titel'];
$static = $row['static'];
$system_link_row = parse_cleanerlinks(addParameter2Link(_01article_echo_ArticleLink($row['id'],$row['titel'],$row['utimestamp']),$names['page']."=".$_REQUEST[$names['page']]."&".$names['catid']."=".$_REQUEST[$names['catid']]));
// Get serialized data
if($ser_fields){
$return_temp = unserialize($row['serialized_data']);
if(empty($return_temp)){
for($x=1;$x<=ANZ_SER_FIELDS;$x++){
$row['ser_field_'.$x] = "";
}
}
else{
for($x=1;$x<=ANZ_SER_FIELDS;$x++){
$row['ser_field_'.$x] = htmlspecialchars($return_temp['field_'.$x],$htmlent_flags,$htmlent_encoding_acp);
}
}
}
// artikel_self-Link
$artikeltext = str_replace("{artikel_self}",$system_link_row,$artikeltext);
// ggf. Links zum vorherigen / nchsten Eintrag generieren
if(isset($_GET[$names['artid']]) && !empty($_GET[$names['artid']]) && $_GET[$names['artid']] != "archiv" && $row['static'] == 0){
$add2query_cat = _01article_CreateCatQuery($_REQUEST[$names['catid']]);
$listnext = $mysqli->query("SELECT id,utimestamp,titel FROM ".$mysql_tables['artikel']." WHERE frei='1' AND hide='0' AND static='0' AND utimestamp > '".$row['utimestamp']."' AND utimestamp <= '".time()."' AND (endtime>='".time()."' OR endtime = '0') AND (".$add2query_cat.") ORDER BY utimestamp LIMIT 1");
$rownext = $listnext->fetch_assoc();
$next_link = parse_cleanerlinks(addParameter2Link(_01article_echo_ArticleLink($rownext['id'],$rownext['titel'],$rownext['utimestamp']),$names['page']."=".$_REQUEST[$names['page']]."&".$names['catid']."=".$_REQUEST[$names['catid']]."#01jumpartikel"));
$next_titel = $rownext['titel'];
$listprev = $mysqli->query("SELECT id,utimestamp,titel FROM ".$mysql_tables['artikel']." WHERE frei='1' AND hide='0' AND static='0' AND utimestamp < '".$row['utimestamp']."' AND (endtime>='".time()."' OR endtime = '0') AND (".$add2query_cat.") ORDER BY utimestamp DESC LIMIT 1");
$rowprev = $listprev->fetch_assoc();
$prev_link = parse_cleanerlinks(addParameter2Link(_01article_echo_ArticleLink($rowprev['id'],$rowprev['titel'],$rowprev['utimestamp']),$names['page']."=".$_REQUEST[$names['page']]."&".$names['catid']."=".$_REQUEST[$names['catid']]."#01jumpartikel"));
$prev_titel = $rowprev['titel'];
}
// Template einbinden
include($tempdir."artikel.html");
// KOMMENTAR-AUSGABE & FORMULAR, etc.
if(isset($_GET[$names['artid']]) && !empty($_GET[$names['artid']]) && $_GET[$names['artid']] > 0 &&
is_numeric($_GET[$names['artid']]) && $_GET[$names['artid']] != "archiv" &&
$settings['comments'] == 1 && $settings['artikelcomments'] >= 1 && $row['comments'] == 1){
// Anti-XSS
if(isset($_POST['send_comment'])) $_POST['send_comment'] = strip_tags($_POST['send_comment']);
if(isset($_POST['modul_comment'])) $_POST['modul_comment'] = strip_tags($_POST['modul_comment']);
if(isset($_POST['autor'])) $_POST['autor'] = filter_var($_POST['autor'],FILTER_SANITIZE_SPECIAL_CHARS);
if(isset($_POST['email'])) $_POST['email'] = strip_tags($_POST['email']);
if(isset($_POST['url'])) $_POST['url'] = strip_tags($_POST['url']);
if(isset($_POST['comment'])) $_POST['comment'] = strip_tags($_POST['comment']);
if(isset($_POST['antispam'])) $_POST['antispam'] = strip_tags($_POST['antispam']);
if(isset($_POST['deaktiv_bbc'])) $_POST['deaktiv_bbc'] = strip_tags($_POST['deaktiv_bbc']);
if(isset($_POST['uid'])) $_POST['uid'] = strip_tags($_POST['uid']);
$message = 0;
// Neuen Kommentar hinzufgen
if(isset($_POST['send_comment']) && $_POST['send_comment'] == 1 &&
isset($_POST['modul_comment']) && $_POST['modul_comment'] == $modul){
$message = insert_Comment($_POST['autor'],$_POST['email'],$_POST['url'],$_POST['comment'],$_POST['antispam'],$_POST['deaktiv_bbc'],$row['id'],$_POST['uid'],0,$_POST['link'],$_POST['time']);
}
//Template einbinden
include($tempdir."comments_head.html");
// KOMMENTARE AUSGEBEN
$nr = 1;
$comment_query = "SELECT * FROM ".$mysql_tables['comments']." WHERE modul='".$modul."' AND postid='".$row['id']."' AND frei='1' ORDER BY utimestamp ".$mysqli->escape_string($comment_desc)."";
// Seiten-Funktion
if($settings['comments_perpage'] > 0){
$comment_sc = $mysqli->query($comment_query)->num_rows;
$comment_sites = ceil($comment_sc/$settings['comments_perpage']); //=Anzahl an Seiten
if(isset($_GET[$names['cpage']]) && $_GET[$names['cpage']] == "last" && $comment_sites > 1){
$_GET[$names['cpage']] = $comment_sites;
$commentsstart = $comment_sites*$settings['comments_perpage']-$settings['comments_perpage'];
$comment_query .= " LIMIT ".$mysqli->escape_string($commentsstart).",".$mysqli->escape_string($settings['comments_perpage'])."";
$nr = $commentsstart+1;
}
elseif(isset($_GET[$names['cpage']]) && !empty($_GET[$names['cpage']]) && $_GET[$names['cpage']] <= $comment_sites && $comment_sites > 1){
$commentsstart = $_GET[$names['cpage']]*$settings['comments_perpage']-$settings['comments_perpage'];
$comment_query .= " LIMIT ".$mysqli->escape_string($commentsstart).",".$mysqli->escape_string($settings['comments_perpage'])."";
$nr = $commentsstart+1;
}
else
$comment_query .= " LIMIT ".$mysqli->escape_string($settings['comments_perpage'])."";
}
$clist = $mysqli->query($comment_query);
while($crow = $clist->fetch_assoc()){
// URL
if(!empty($crow['url']) && $crow['url'] != "http://"){
if(substr_count($crow['url'], "http://") < 1)
$url = "http://".$crow['url'];
else
$url = $crow['url'];
}
else $url = "";
// Weitere Variablen fr die Template-Ausgabe aufbereiten
$datum = date("d.m.y - G:i",$crow['utimestamp']);
$autorenname = $crow['autor'];
$comment_id = $crow['id'];
// BB-Code & Smilies
$comment = $crow['message'];
if($crow['bbc'] == 1 && $settings['comments_bbc'] == 1 && $crow['smilies'] == 1 && $settings['comments_smilies'] == 1)
$comment = bb_code_comment($comment,1,1,1);
elseif($crow['bbc'] == 1 && $settings['comments_bbc'] == 1 && ($crow['smilies'] == 0 || $settings['comments_smilies'] == 0))
$comment = bb_code_comment($comment,1,1,0);
elseif(($crow['bbc'] == 0 || $settings['comments_bbc'] == 0) && $crow['smilies'] == 1 && $settings['comments_smilies'] == 1)
$comment = bb_code_comment($comment,1,0,1);
else
$comment = nl2br($comment);
// Template ausgeben
include($tempdir."commentbit.html");
$nr++;
}
//Seiten (Kommentare) ausgeben
if($comment_sites > 1 && $settings['comments_perpage'] > 0){
if(isset($_GET[$names['cpage']]) && $_GET[$names['cpage']] > 1){
$c_sz = $_GET[$names['cpage']]-1;
if($c_sz > 1)
$c_szl1 = parse_cleanerlinks(addParameter2Link(_01article_echo_ArticleLink($_GET[$names['artid']]),$names['page']."=".$_REQUEST[$names['page']]."&".$names['cpage']."=1&".$names['search']."=".$_REQUEST[$names['search']]."&".$names['catid']."=".$_REQUEST[$names['catid']]."#01jumpcomments"));
$c_szl2 = parse_cleanerlinks(addParameter2Link(_01article_echo_ArticleLink($_GET[$names['artid']]),$names['page']."=".$_REQUEST[$names['page']]."&".$names['cpage']."=".$c_sz."&".$names['search']."=".$_REQUEST[$names['search']]."&".$names['catid']."=".$_REQUEST[$names['catid']]."#01jumpcomments"));
}
else{ $c_szl1 = ""; $c_szl2 = ""; $c_sz = 0; }
if(!isset($_GET[$names['cpage']]) || isset($_GET[$names['cpage']]) && empty($_GET[$names['cpage']]))
{
$comment_current = 1;
if($comment_sites > 1) $c_sv = 2;
}
else{
$comment_current = $_GET[$names['cpage']];
$c_sv = $_GET[$names['cpage']]+1;
}
if(isset($_GET[$names['cpage']]) && $_GET[$names['cpage']] < $comment_sites || !isset($_GET[$names['cpage']]) && $comment_sites > 1){
$c_svl1 = parse_cleanerlinks(addParameter2Link(_01article_echo_ArticleLink($_GET[$names['artid']]),$names['page']."=".$_REQUEST[$names['page']]."&".$names['cpage']."=".$c_sv."&".$names['search']."=".$_REQUEST[$names['search']]."&".$names['catid']."=".$_REQUEST[$names['catid']]."#01jumpcomments"));
if($c_sv != $comment_sites)
$c_svl2 = parse_cleanerlinks(addParameter2Link(_01article_echo_ArticleLink($_GET[$names['artid']]),$names['page']."=".$_REQUEST[$names['page']]."&".$names['cpage']."=".$comment_sites."&".$names['search']."=".$_REQUEST[$names['search']]."&".$names['catid']."=".$_REQUEST[$names['catid']]."#01jumpcomments"));
}
else{ $c_svl1 = ""; $c_svl2 = ""; }
}
//Template ausgeben
if($message > 2) $flag_comments_js = FALSE; // Formular nicht per JS ausblenden, wenn eine Fehlermeldung erzeugt wurde.
include($tempdir."comments_end.html");
//Unterschiedliche Sprungmarken nach Absenden des Kommentarformulars
if(!isset($jumpto_id)) $jumpto_id = "";
if($settings['commentfreischaltung'] == 0) $jumpto = "01comment".$jumpto_id; else $jumpto = "01jumpcomments";
if($comment_desc == "") $jumpto_csite = "last"; else $jumpto_csite = "1";
$system_link_form = parse_cleanerlinks(addParameter2Link(_01article_echo_ArticleLink($_GET[$names['artid']]),$names['page']."=".$_REQUEST[$names['page']]."&".$names['cpage']."=".$jumpto_csite."&".$names['search']."=".$_REQUEST[$names['search']]."&".$names['catid']."=".$_REQUEST[$names['catid']]."#01jumpcomments_add"));
if($settings['artikelcomments'] == 1){
$zahl = mt_rand(1, 9999999999999);
$uid = md5(time().$_SERVER['REMOTE_ADDR'].$zahl.$_GET[$names['artid']]);
//Template ausgeben
include($tempdir."comments_add.html");
}
elseif ($settings['artikelcomments'] == 2 && !empty($settings['Disqus_Username'])) {
include($tempdir."comments_disqus.html");
}
}
unset($catimg);
unset($catname);
}
}
// Ausgabe der Seiten
if($sites > 1){
$option_sites = "";
for($o=1;$o<=$sites;$o++){
$option_sites .= "<option>".$o."</option>\n";
}
if(isset($_REQUEST[$names['page']]) && $_REQUEST[$names['page']] > 1){
$sz = $_REQUEST[$names['page']]-1;
if($sz != 1)
$szl1 = parse_cleanerlinks(addParameter2Link($filename,$names['page']."=1&".$names['search']."=".$_REQUEST[$names['search']]."&".$names['catid']."=".$_REQUEST[$names['catid']].$flag_archiv."#01jumpartikel"));
else $szl1 = "";
$szl2 = parse_cleanerlinks(addParameter2Link($filename,$names['page']."=".$sz."&".$names['search']."=".$_REQUEST[$names['search']]."&".$names['catid']."=".$_REQUEST[$names['catid']].$flag_archiv."#01jumpartikel"));
}
else{ $szl1 = ""; $szl2 = ""; }
if(!isset($_REQUEST[$names['page']]) || isset($_REQUEST[$names['page']]) && empty($_REQUEST[$names['page']])){
$current = 1;
if($sites > 1){ $sv = 2; }
}
else{
$current = $_REQUEST[$names['page']];
$sv = $_REQUEST[$names['page']]+1;
}
if(isset($_REQUEST[$names['page']]) && $_REQUEST[$names['page']] < $sites || !isset($_REQUEST[$names['page']]) && $sites > 1){
$svl1 = parse_cleanerlinks(addParameter2Link($filename,$names['page']."=".$sv."&".$names['search']."=".$_REQUEST[$names['search']]."&".$names['catid']."=".$_REQUEST[$names['catid']].$flag_archiv."#01jumpartikel"));
if($sv != $sites)
$svl2 = parse_cleanerlinks(addParameter2Link($filename,$names['page']."=".$sites."&".$names['search']."=".$_REQUEST[$names['search']]."&".$names['catid']."=".$_REQUEST[$names['catid']].$flag_archiv."#01jumpartikel"));
}
else{
$svl1 = "";
$svl2 = "";
if(isset($_REQUEST[$names['page']]) && $_REQUEST[$names['page']] == $sites &&
!empty($settings['archiv_time']) && $settings['archiv_time'] > 0 && $_GET[$names['artid']] != "archiv")
$svl2a = "<a href=\"".parse_cleanerlinks(addParameter2Link($filename,$names['artid']."=archiv&".$names['catid']."=".$_REQUEST[$names['catid']]."#01jumpartikel"))."\">Archiv »</a>";
}
}
// Kategorien vorhanden? --> Ausgeben
if(isset($category) && count($category) > 0){
$listcats = "";
foreach($category as $cat){
// Sind Eintrge dieser Kategorie zugeordnet?
if($qt > 0)
list($newsvorhanden) = $mysqli->query("SELECT COUNT(*) FROM ".$mysql_tables['artikel']." WHERE frei='1' AND hide='0' AND static = '0' AND utimestamp <= '".time()."' AND utimestamp>'".$qt."' AND (endtime >= '".time()."' OR endtime='0') AND newscatid LIKE '%,".$cat['id'].",%'")->fetch_array(MYSQLI_NUM);
else
list($newsvorhanden) = $mysqli->query("SELECT COUNT(*) FROM ".$mysql_tables['artikel']." WHERE frei='1' AND hide='0' AND static = '0' AND utimestamp <= '".time()."' AND (endtime >= '".time()."' OR endtime='0') AND newscatid LIKE '%,".$cat['id'].",%'")->fetch_array(MYSQLI_NUM);
if($newsvorhanden > 0)
$listcats .= "<option value=\"".$cat['id']."\">".$cat['name']." (".$newsvorhanden.")</option>\n";
$newsvorhanden = 0;
}
}
//Template einbinden
include($tempdir."pages.html");
//Template einbinden
include($tempdir."main_bottom.html");
$tempdir = "templates/";
$query = "";
?>
|
<?PHP
/*
01-Artikelsystem V3 - Copyright 2006-2015 by Michael Lorer - 01-Scripts.de
Lizenz: Creative-Commons: Namensnennung-Keine kommerzielle Nutzung-Weitergabe unter gleichen Bedingungen 3.0 Deutschland
Weitere Lizenzinformationen unter: http://www.01-scripts.de/lizenz.php
Modul: 01article
Dateiinfo: Frontend-Ausgabe 01-Artikelsystem
#fv.321#
*/
//Hinweis zum Einbinden des Artikelsystems per include();
/*Folgender PHP-Code ntig:
<?PHP
$subfolder = "01scripts/";
$modul = "01article/";
include($subfolder."01module/".$modul."01article.php");
?>
*/
$frontp = 1;
$flag_acp = FALSE;
if(!isset($flag_utf8)) $flag_utf8 = FALSE;
if(!isset($flag_nocss)) $flag_nocss = FALSE;
if(!isset($flag_second)) $flag_second= FALSE;
@ini_set('session.use_trans_sid',0);
if(isset($subfolder) && !empty($subfolder)){
if(substr_count($subfolder, "/") < 1){ $subfolder .= "/"; }
}
elseif(isset($_GET['rss']) && ($_GET['rss'] == "show_rssfeed" || $_GET['rss'] == "show_commentrssfeed"))
$subfolder = "../../";
else
$subfolder = "";
// Globale Config-Datei einbinden
include_once($subfolder."01_config.php");
include_once($subfolder."01acp/system/headinclude.php");
if(!$flag_second) include_once($subfolder."01acp/system/functions.php");
$modulvz = $modul."/";
// Modul-Config-Dateien einbinden
include_once($moduldir.$modulvz."_headinclude.php");
include_once($moduldir.$modulvz."_functions.php");
// Variablen
$imagepf = $moduldir.$modulvz.$imagepf; // Pfad zum Bild-Verzeichnis
$tempdir = $moduldir.$modulvz.$tempdir; // Template-Verzeichnis
$filename = $_SERVER['SCRIPT_NAME']; // Variable enthlt die Adresse der Datei, auf der das Artikelsystem eingebunden wurde
$flag_comments_js = TRUE; // Kommentar-Feld per Default via JavaScript ausblenden?
// Language-File einbinden
include_once($tempdir."lang_vars.php");
// Weitere Variablen +Bitte nehmen Sie hier keine nderungen vor+
$sites = 0;
$qt = 0;
$svl2a = "";
$qt_query = "";
$flag_archiv = "";
$flag_IamStandard = FALSE;
// ggf. Zuweisung $show[] -> $_GET[]
if(!isset($_REQUEST[$names['catid']]) && isset($show['catid']) && !empty($show['catid'])) $_REQUEST[$names['catid']] = $show['catid'];
if(!isset($_REQUEST[$names['search']]) && isset($show['search']) && !empty($show['search'])) $_REQUEST[$names['search']] = $show['search'];
if(!isset($_REQUEST[$names['page']]) && isset($show['page']) && !empty($show['page'])) $_REQUEST[$names['page']] = $show['page'];
if(!isset($_GET[$names['artid']]) && isset($show['artid']) && !empty($show['artid'])) $_GET[$names['artid']] = $show['artid'];
// Notice: Undefined index: ... beheben & strip_tags auf bergebene Werte anwenden (+ Anti-XSS)
if(!isset($_REQUEST[$names['search']])) $_REQUEST[$names['search']] = "";
else $_REQUEST[$names['search']] = strip_tags($_REQUEST[$names['search']]);
if(!isset($_REQUEST[$names['page']])) $_REQUEST[$names['page']] = "";
else $_REQUEST[$names['page']] = strip_tags($_REQUEST[$names['page']]);
if(!isset($_REQUEST[$names['catid']])) $_REQUEST[$names['catid']] = "";
else $_REQUEST[$names['catid']] = strip_tags($_REQUEST[$names['catid']]);
if(!isset($_REQUEST[$names['cpage']])) $_REQUEST[$names['cpage']] = "";
else $_REQUEST[$names['cpage']] = strip_tags($_REQUEST[$names['cpage']]);
if(!isset($_REQUEST[$names['rss']])) $_REQUEST[$names['rss']] = "";
else $_REQUEST[$names['rss']] = strip_tags($_REQUEST[$names['rss']]);
if(!isset($_GET[$names['artid']])) $_GET[$names['artid']] = "";
else $_GET[$names['artid']] = strip_tags($_GET[$names['artid']]);
if(!isset($_GET[$names['cpage']])) $_GET[$names['cpage']] = "";
else $_GET[$names['cpage']] = strip_tags($_GET[$names['cpage']]);
if(!isset($_GET[$names['rss']])) $_GET[$names['rss']] = "";
else $_GET[$names['rss']] = strip_tags($_GET[$names['rss']]);
if(!isset($static)) $static = 0;
if(!isset($_POST['deaktiv_bbc'])) $_POST['deaktiv_bbc'] = 0;
else $_POST['deaktiv_bbc'] = strip_tags($_POST['deaktiv_bbc']);
if(!isset($_GET[$names['page']]) || isset($_GET[$names['page']]) && $_GET[$names['page']] != $_REQUEST[$names['page']]) $_GET[$names['page']] = $_REQUEST[$names['page']];
if(!isset($_POST['antispam'])) $_POST['antispam'] = "";
//Link-String generieren
$system_link = addParameter2Link(_01article_echo_ArticleLink($_GET[$names['artid']]),$names['search']."=".$_REQUEST[$names['search']]."&".$names['page']."=".$_REQUEST[$names['page']]."&".$names['catid']."=".$_REQUEST[$names['catid']]);
$system_link_index = parse_cleanerlinks(addParameter2Link($filename,$names['search']."=".$_REQUEST[$names['search']]."&".$names['page']."=".$_REQUEST[$names['page']]."&".$names['catid']."=".$_REQUEST[$names['catid']]));
$system_link_rss = $subfolder."01module/".$modul."/01article.php";
// Ausfhrung der weiteren Seite wird nach dem Aufruf der ntigen RSS-Funktionen durch exit; unterbrochen
if(isset($_GET[$names['rss']]) && ($_GET[$names['rss']] == "show_rssfeed" || $_GET[$names['rss']] == "show_commentrssfeed") &&
$settings['rss_aktiv'] == 1 && ($settings['artikelrssfeedaktiv'] == 1 || $settings['artikelkommentarfeed'] == 1)){
if(!isset($_GET['entries'])) $_GET['entries'] = "";
else $_GET['entries'] = strip_tags($_GET['entries']);
include_once($subfolder."01acp/system/includes/htmLawed.php");
header("Content-type: text/xml");
echo _01article_RSS($_GET[$names['rss']],$_GET['entries'],$_REQUEST[$names['catid']]);
exit;
}
elseif(isset($_GET[$names['rss']]) && ($_GET[$names['rss']] == "show_rssfeed" || $_GET[$names['rss']] == "show_commentrssfeed")){
echo "Fehler: Der RSS-Feed wurde deaktiviert!";
exit;
}
// CSS-Datei einbinden
if(isset($settings['extern_css']) && !empty($settings['extern_css']) && filter_var($settings['extern_css'], FILTER_VALIDATE_URL) !== FALSE && !$flag_nocss)
$echo_css = "<link rel=\"stylesheet\" type=\"text/css\" href=\"".$settings['extern_css']."\" />";
elseif(!$flag_nocss)
$echo_css = "<link rel=\"stylesheet\" type=\"text/css\" href=\"".$tempdir."style.css\" />";
else $echo_css = "";
// Alle Kategorien in einen mehrdimensionalen Array einlesen
$listcat = $mysqli->query("SELECT * FROM ".$mysql_tables['cats']." ORDER BY sortid,name");
while($rowcat = $listcat->fetch_assoc()){
$category[$rowcat['id']]['id'] = $rowcat['id'];
$category[$rowcat['id']]['name'] = htmlentities($rowcat['name'],$htmlent_flags,$htmlent_encoding_acp);
$category[$rowcat['id']]['catpic'] = $rowcat['catpic'];
}
// ggf. Archiv-Zeit berechnen
if(!empty($settings['archiv_time']) && $settings['archiv_time'] > 0 && is_numeric($settings['archiv_time']))
$qt = time()-($settings['archiv_time']*24*60*60);
// Alternative Abfrage, wenn nur ein Artikel / eine Seite angezeigt werden soll
if(isset($_GET[$names['artid']]) && !empty($_GET[$names['artid']]) && $_GET[$names['artid']] != "archiv" && $_GET[$names['artid']] > 0 && is_numeric($_GET[$names['artid']])){
$query = "SELECT * FROM ".$mysql_tables['artikel']." WHERE frei='1' AND hide='0' AND utimestamp <= '".time()."' AND (endtime >= '".time()."' OR endtime = '0') AND id = '".$mysqli->escape_string($_GET[$names['artid']])."' LIMIT 1";
$iderror = 1;
//Hits +1:
$mysqli->query("UPDATE ".$mysql_tables['artikel']." SET hits = hits+1 WHERE id = '".$mysqli->escape_string($_GET[$names['artid']])."' LIMIT 1");
}
// Archiv-Ansicht
elseif(isset($_GET[$names['artid']]) && $_GET[$names['artid']] == "archiv" && !empty($settings['archiv_time']) && $settings['archiv_time'] > 0 && is_numeric($settings['archiv_time'])){
$flag_archiv = "&".$names['artid']."=archiv";
$add2query_cat = _01article_CreateCatQuery($_REQUEST[$names['catid']]);
$query = "SELECT * FROM ".$mysql_tables['artikel']." WHERE frei='1' AND hide='0' AND static = '0' AND (utimestamp <= '".$qt."' OR (endtime <= '".time()."' AND endtime != '0')) AND (endtime <= '".time()."' OR endtime = '0') AND (".$add2query_cat.") ORDER BY utimestamp DESC";
$settings['articleperpage'] = ANZ_PP_ARCHIV;
makepages($query,$sites,$names['page'],$settings['articleperpage']);
$iderror = 1;
}
// Alle Artikel anzeigen
else{
if(!empty($settings['archiv_time']) && $settings['archiv_time'] > 0 && is_numeric($settings['archiv_time']))
$qt_query = "AND (utimestamp>'".$qt."' OR top = '1' OR endtime >= '".time()."') ";
else $qt_query = "";
if(isset($_REQUEST[$names['search']]) && !empty($_REQUEST[$names['search']]) && $settings['artikelsuche'] == 1){
if($flag_utf8)
$parsed_searchstring = $mysqli->escape_string(parse_uml(utf8_decode(str_replace("*","",$_REQUEST[$names['search']]))));
else
$parsed_searchstring = $mysqli->escape_string(parse_uml(str_replace("*","",$_REQUEST[$names['search']])));
$add2query_cat = _01article_CreateCatQuery($_REQUEST[$names['catid']]);
$add2query = "AND MATCH (titel,content,zusammenfassung) AGAINST ('".$parsed_searchstring."') >= ".FULLTEXT_INDEX_SEARCH_SCHWELLE." AND (".$add2query_cat.")";
$iderror = 2; // Flag fr Fehlermeldung in main_top
}
elseif(isset($_REQUEST[$names['catid']]) && !empty($_REQUEST[$names['catid']])){
$add2query_cat = _01article_CreateCatQuery($_REQUEST[$names['catid']]);
$add2query = $qt_query."AND (".$add2query_cat.") ORDER BY top DESC,utimestamp DESC";
$iderror = 3; // Flag fr Fehlermeldung in main_top
}
else{
$add2query = $qt_query."ORDER BY top DESC,utimestamp DESC";
$flag_IamStandard = true;
$iderror = 1; // Flag fr Fehlermeldung in main_top
}
$query = "SELECT * FROM ".$mysql_tables['artikel']." WHERE frei='1' AND hide='0' AND static='0' AND utimestamp <= '".time()."' AND (endtime >= '".time()."' OR endtime='0') ".$add2query;
makepages($query,$sites,$names['page'],$settings['articleperpage']);
}
// List > 0?
$list = $mysqli->query($query);
echo "<!-- 2559ad821dde361560dbf967c3406f51 -->";
// Wenn nichts angezeigt werden konnte neuer Versuch mit Standardabfrage
if($list->num_rows == 0 && !$flag_IamStandard){
$query = "SELECT * FROM ".$mysql_tables['artikel']." WHERE frei='1' AND hide='0' AND static='0' AND utimestamp <= '".time()."' AND (endtime >= '".time()."' OR endtime='0') ".$qt_query."ORDER BY top DESC,utimestamp DESC";
makepages($query,$sites,$names['page'],$settings['articleperpage']);
$list = $mysqli->query($query);
$_GET[$names['artid']] = "";
}
elseif($list->num_rows > 0){
if(isset($_REQUEST[$names['search']]) && !empty($_REQUEST[$names['search']]) && $settings['artikelsuche'] == 1)
$iderror = 4;
elseif(isset($_REQUEST[$names['catid']]) && !empty($_REQUEST[$names['catid']]))
$iderror = 5;
else
$iderror = 0; // Flag fr Fehlermeldung zurcksetzen, wenn mind. 1 Artikel angezeigt werden kann
}
// main_top einbinden
include($tempdir."main_top.html");
// ARCHIV
if(isset($_GET[$names['artid']]) && $_GET[$names['artid']] == "archiv" && !empty($settings['archiv_time']) && $settings['archiv_time'] > 0 && is_numeric($settings['archiv_time'])){
include($tempdir."archiv_top.html");
$round = 1;
while($row = $list->fetch_assoc()){
if($round == 1){
$archiv_year = date("Y",$row['utimestamp']);
$archiv_month = date("n",$row['utimestamp']);
include($tempdir."archiv_top_year.html");
include($tempdir."archiv_top_month.html");
}
if($archiv_year != date("Y",$row['utimestamp'])){
$archiv_year = date("Y",$row['utimestamp']);
include($tempdir."archiv_top_year.html");
}
if($archiv_month != date("n",$row['utimestamp'])){
$archiv_month = date("n",$row['utimestamp']);
include($tempdir."archiv_top_month.html");
}
$datum = date("d.m.y",$row['utimestamp']).", ".date("G:i",$row['utimestamp']);
$titel = $row['titel'];
$username_array = getUserdatafields($row['uid'],"username");
$autor = htmlentities($username_array['username'],$htmlent_flags,$htmlent_encoding_acp);
include($tempdir."archiv_bit.html");
$round++;
}
include($tempdir."archiv_bottom.html");
$iderror = 0;
}
// NORMALE AUSGABE
else{
while($row = $list->fetch_assoc()){
$datum = date("d.m.y",$row['utimestamp']);
$uhrzeit = date("G:i",$row['utimestamp']);
//Catid & Catimage auslesen
if($row['newscatid'] != "0"){
$c = 0;
$catimg = ""; $catname = "";
$newscatids_array = explode(",",substr($row['newscatid'],1,strlen($row['newscatid'])-2));
foreach($newscatids_array as $newscatid_s){
if(isset($category[$newscatid_s]['name'])){
if(isset($category[$newscatid_s]['catpic']) && $category[$newscatid_s]['catpic'] != "")
$catimg .= "<a href=\"".addParameter2Link($filename,$names['catid']."=".$newscatid_s)."\"><img src=\"".$catuploaddir.$category[$newscatid_s]['catpic']."\" alt=\"Kategorie: ".$category[$newscatid_s]['name']."\" title=\"Kategorie: ".$category[$newscatid_s]['name']."\" align=\"left\" /></a> ";
else
$catimg .= "";
if($c > 0) $catname .= ", ";
$catname .= "<a href=\"".addParameter2Link($filename,$names['catid']."=".$newscatid_s)."\" class=\"catlink\">".$category[$newscatid_s]['name']."</a>";
$c++;
}
}
}
else{ $catimg = ""; $catname = ""; }
$more = 0;
// Normalen, kompletten Haupttext anzeigen
if((isset($_GET[$names['artid']]) && !empty($_GET[$names['artid']]) ||
$settings['artikeleinleitung'] == 0 ||
$settings['artikeleinleitung'] == 2 && $row['autozusammen'] == 0 && empty($row['zusammenfassung'])) &&
(!isset($_REQUEST[$names['search']]) || isset($_REQUEST[$names['search']]) && empty($_REQUEST[$names['search']]) || $iderror == 2)){
$artikeltext = $row['content'];
$artikeltext = str_replace("../01pics/",$picuploaddir,$artikeltext);
$artikeltext = str_replace("../01files/",$attachmentuploaddir,$artikeltext);
if($settings['artikellightbox'] == 1) $artikeltext = str_replace("class=\"lightbox\"","class=\"lightbox\" rel=\"lightbox-art".$row['id']."\"",$artikeltext);
$artikeltext = preg_replace_callback("/\{Insert#(\d+)GalleryPicsFrom#(\d+)\}/","_01article_callback_GetGalThumbs4Article",$artikeltext);
}
// Zusammenfassung anzeigen
else{
if($row['autozusammen'] == 0 && !empty($row['zusammenfassung'])){
$artikeltext = $row['zusammenfassung'];
$artikeltext = str_replace("../01pics/",$picuploaddir,$artikeltext);
$artikeltext = str_replace("../01files/",$attachmentuploaddir,$artikeltext);
if($settings['artikellightbox'] == 1) $artikeltext = str_replace("class=\"lightbox\"","class=\"lightbox\" rel=\"lightbox-art".$row['id']."\"",$artikeltext);
}
else{
$artikeltext = "<p>".substr(strip_tags($row['content']),0,$settings['artikeleinleitungslaenge']).$lang['weiterlesen']."</p>";
if($settings['artikellightbox'] == 1) $artikeltext = str_replace("class=\"lightbox\"","class=\"lightbox\" rel=\"lightbox-art".$row['id']."\"",$artikeltext);
}
$artikeltext = preg_replace_callback("/\{Insert#(\d+)GalleryPicsFrom#(\d+)\}/","_01article_callback_GetGalThumbs4Article",$artikeltext);
// Weiterlesen-Link nur einbinden, wenn Text lnger als Zusammenfassung oder eigener Text eingegeben wurde
if($row['autozusammen'] == 0 && !empty($row['zusammenfassung']) ||
strlen($artikeltext) < strlen($row['content']))
$more = 1;
else $more = 0;
}
// Anzahl bisheriger Kommentare ermitteln
if($settings['comments'] == 1){
$comments = 0;
list($comments) = $mysqli->query("SELECT COUNT(*) FROM ".$mysql_tables['comments']." WHERE frei = '1' AND modul = '".$mysqli->escape_string($modul)."' AND postid = '".$row['id']."'")->fetch_array(MYSQLI_NUM);
}
// Weitere Variablen fr die Template-Ausgabe aufbereiten
$username_array = getUserdatafields($row['uid'],"username,01acp_signatur");
$username = htmlentities($username_array['username'],$htmlent_flags,$htmlent_encoding_acp);
if(!empty($username_array['signatur']) && $more == 0 && $row['hide_signature'] == 0)
$signatur = "<p class=\"signatur\">".nl2br(str_replace("&","&",$username_array['signatur']))."</p>";
if($flag_utf8) $signatur = utf8_encode($signatur);
else
$signatur = "";
$titel = $row['titel'];
$static = $row['static'];
$system_link_row = parse_cleanerlinks(addParameter2Link(_01article_echo_ArticleLink($row['id'],$row['titel'],$row['utimestamp']),$names['page']."=".$_REQUEST[$names['page']]."&".$names['catid']."=".$_REQUEST[$names['catid']]));
// Get serialized data
if($ser_fields){
$return_temp = unserialize($row['serialized_data']);
if(empty($return_temp)){
for($x=1;$x<=ANZ_SER_FIELDS;$x++){
$row['ser_field_'.$x] = "";
}
}
else{
for($x=1;$x<=ANZ_SER_FIELDS;$x++){
$row['ser_field_'.$x] = htmlspecialchars($return_temp['field_'.$x],$htmlent_flags,$htmlent_encoding_acp);
}
}
}
// artikel_self-Link
$artikeltext = str_replace("{artikel_self}",$system_link_row,$artikeltext);
// ggf. Links zum vorherigen / nchsten Eintrag generieren
if(isset($_GET[$names['artid']]) && !empty($_GET[$names['artid']]) && $_GET[$names['artid']] != "archiv" && $row['static'] == 0){
$add2query_cat = _01article_CreateCatQuery($_REQUEST[$names['catid']]);
$listnext = $mysqli->query("SELECT id,utimestamp,titel FROM ".$mysql_tables['artikel']." WHERE frei='1' AND hide='0' AND static='0' AND utimestamp > '".$row['utimestamp']."' AND utimestamp <= '".time()."' AND (endtime>='".time()."' OR endtime = '0') AND (".$add2query_cat.") ORDER BY utimestamp LIMIT 1");
$rownext = $listnext->fetch_assoc();
$next_link = parse_cleanerlinks(addParameter2Link(_01article_echo_ArticleLink($rownext['id'],$rownext['titel'],$rownext['utimestamp']),$names['page']."=".$_REQUEST[$names['page']]."&".$names['catid']."=".$_REQUEST[$names['catid']]."#01jumpartikel"));
$next_titel = $rownext['titel'];
$listprev = $mysqli->query("SELECT id,utimestamp,titel FROM ".$mysql_tables['artikel']." WHERE frei='1' AND hide='0' AND static='0' AND utimestamp < '".$row['utimestamp']."' AND (endtime>='".time()."' OR endtime = '0') AND (".$add2query_cat.") ORDER BY utimestamp DESC LIMIT 1");
$rowprev = $listprev->fetch_assoc();
$prev_link = parse_cleanerlinks(addParameter2Link(_01article_echo_ArticleLink($rowprev['id'],$rowprev['titel'],$rowprev['utimestamp']),$names['page']."=".$_REQUEST[$names['page']]."&".$names['catid']."=".$_REQUEST[$names['catid']]."#01jumpartikel"));
$prev_titel = $rowprev['titel'];
}
// Template einbinden
include($tempdir."artikel.html");
// KOMMENTAR-AUSGABE & FORMULAR, etc.
if(isset($_GET[$names['artid']]) && !empty($_GET[$names['artid']]) && $_GET[$names['artid']] > 0 &&
is_numeric($_GET[$names['artid']]) && $_GET[$names['artid']] != "archiv" &&
$settings['comments'] == 1 && $settings['artikelcomments'] >= 1 && $row['comments'] == 1){
// Anti-XSS
if(isset($_POST['send_comment'])) $_POST['send_comment'] = strip_tags($_POST['send_comment']);
if(isset($_POST['modul_comment'])) $_POST['modul_comment'] = strip_tags($_POST['modul_comment']);
if(isset($_POST['autor'])) $_POST['autor'] = filter_var($_POST['autor'],FILTER_SANITIZE_SPECIAL_CHARS);
if(isset($_POST['email'])) $_POST['email'] = strip_tags($_POST['email']);
if(isset($_POST['url'])) $_POST['url'] = strip_tags($_POST['url']);
if(isset($_POST['comment'])) $_POST['comment'] = strip_tags($_POST['comment']);
if(isset($_POST['antispam'])) $_POST['antispam'] = strip_tags($_POST['antispam']);
if(isset($_POST['deaktiv_bbc'])) $_POST['deaktiv_bbc'] = strip_tags($_POST['deaktiv_bbc']);
if(isset($_POST['uid'])) $_POST['uid'] = strip_tags($_POST['uid']);
$message = 0;
// Neuen Kommentar hinzufgen
if(isset($_POST['send_comment']) && $_POST['send_comment'] == 1 &&
isset($_POST['modul_comment']) && $_POST['modul_comment'] == $modul){
$message = insert_Comment($_POST['autor'],$_POST['email'],$_POST['url'],$_POST['comment'],$_POST['antispam'],$_POST['deaktiv_bbc'],$row['id'],$_POST['uid'],0,$_POST['link'],$_POST['time']);
}
//Template einbinden
include($tempdir."comments_head.html");
// KOMMENTARE AUSGEBEN
$nr = 1;
$comment_query = "SELECT * FROM ".$mysql_tables['comments']." WHERE modul='".$modul."' AND postid='".$row['id']."' AND frei='1' ORDER BY utimestamp ".$mysqli->escape_string($comment_desc)."";
// Seiten-Funktion
if($settings['comments_perpage'] > 0){
$comment_sc = $mysqli->query($comment_query)->num_rows;
$comment_sites = ceil($comment_sc/$settings['comments_perpage']); //=Anzahl an Seiten
if(isset($_GET[$names['cpage']]) && $_GET[$names['cpage']] == "last" && $comment_sites > 1){
$_GET[$names['cpage']] = $comment_sites;
$commentsstart = $comment_sites*$settings['comments_perpage']-$settings['comments_perpage'];
$comment_query .= " LIMIT ".$mysqli->escape_string($commentsstart).",".$mysqli->escape_string($settings['comments_perpage'])."";
$nr = $commentsstart+1;
}
elseif(isset($_GET[$names['cpage']]) && !empty($_GET[$names['cpage']]) && $_GET[$names['cpage']] <= $comment_sites && $comment_sites > 1){
$commentsstart = $_GET[$names['cpage']]*$settings['comments_perpage']-$settings['comments_perpage'];
$comment_query .= " LIMIT ".$mysqli->escape_string($commentsstart).",".$mysqli->escape_string($settings['comments_perpage'])."";
$nr = $commentsstart+1;
}
else
$comment_query .= " LIMIT ".$mysqli->escape_string($settings['comments_perpage'])."";
}
$clist = $mysqli->query($comment_query);
while($crow = $clist->fetch_assoc()){
// URL
if(!empty($crow['url']) && $crow['url'] != "http://"){
if(substr_count($crow['url'], "http://") < 1)
$url = "http://".$crow['url'];
else
$url = $crow['url'];
}
else $url = "";
// Weitere Variablen fr die Template-Ausgabe aufbereiten
$datum = date("d.m.y - G:i",$crow['utimestamp']);
$autorenname = $crow['autor'];
$comment_id = $crow['id'];
// BB-Code & Smilies
$comment = $crow['message'];
if($crow['bbc'] == 1 && $settings['comments_bbc'] == 1 && $crow['smilies'] == 1 && $settings['comments_smilies'] == 1)
$comment = bb_code_comment($comment,1,1,1);
elseif($crow['bbc'] == 1 && $settings['comments_bbc'] == 1 && ($crow['smilies'] == 0 || $settings['comments_smilies'] == 0))
$comment = bb_code_comment($comment,1,1,0);
elseif(($crow['bbc'] == 0 || $settings['comments_bbc'] == 0) && $crow['smilies'] == 1 && $settings['comments_smilies'] == 1)
$comment = bb_code_comment($comment,1,0,1);
else
$comment = nl2br($comment);
// Template ausgeben
include($tempdir."commentbit.html");
$nr++;
}
//Seiten (Kommentare) ausgeben
if($comment_sites > 1 && $settings['comments_perpage'] > 0){
if(isset($_GET[$names['cpage']]) && $_GET[$names['cpage']] > 1){
$c_sz = $_GET[$names['cpage']]-1;
if($c_sz > 1)
$c_szl1 = parse_cleanerlinks(addParameter2Link(_01article_echo_ArticleLink($_GET[$names['artid']]),$names['page']."=".$_REQUEST[$names['page']]."&".$names['cpage']."=1&".$names['search']."=".$_REQUEST[$names['search']]."&".$names['catid']."=".$_REQUEST[$names['catid']]."#01jumpcomments"));
$c_szl2 = parse_cleanerlinks(addParameter2Link(_01article_echo_ArticleLink($_GET[$names['artid']]),$names['page']."=".$_REQUEST[$names['page']]."&".$names['cpage']."=".$c_sz."&".$names['search']."=".$_REQUEST[$names['search']]."&".$names['catid']."=".$_REQUEST[$names['catid']]."#01jumpcomments"));
}
else{ $c_szl1 = ""; $c_szl2 = ""; $c_sz = 0; }
if(!isset($_GET[$names['cpage']]) || isset($_GET[$names['cpage']]) && empty($_GET[$names['cpage']]))
{
$comment_current = 1;
if($comment_sites > 1) $c_sv = 2;
}
else{
$comment_current = $_GET[$names['cpage']];
$c_sv = $_GET[$names['cpage']]+1;
}
if(isset($_GET[$names['cpage']]) && $_GET[$names['cpage']] < $comment_sites || !isset($_GET[$names['cpage']]) && $comment_sites > 1){
$c_svl1 = parse_cleanerlinks(addParameter2Link(_01article_echo_ArticleLink($_GET[$names['artid']]),$names['page']."=".$_REQUEST[$names['page']]."&".$names['cpage']."=".$c_sv."&".$names['search']."=".$_REQUEST[$names['search']]."&".$names['catid']."=".$_REQUEST[$names['catid']]."#01jumpcomments"));
if($c_sv != $comment_sites)
$c_svl2 = parse_cleanerlinks(addParameter2Link(_01article_echo_ArticleLink($_GET[$names['artid']]),$names['page']."=".$_REQUEST[$names['page']]."&".$names['cpage']."=".$comment_sites."&".$names['search']."=".$_REQUEST[$names['search']]."&".$names['catid']."=".$_REQUEST[$names['catid']]."#01jumpcomments"));
}
else{ $c_svl1 = ""; $c_svl2 = ""; }
}
//Template ausgeben
if($message > 2) $flag_comments_js = FALSE; // Formular nicht per JS ausblenden, wenn eine Fehlermeldung erzeugt wurde.
include($tempdir."comments_end.html");
//Unterschiedliche Sprungmarken nach Absenden des Kommentarformulars
if(!isset($jumpto_id)) $jumpto_id = "";
if($settings['commentfreischaltung'] == 0) $jumpto = "01comment".$jumpto_id; else $jumpto = "01jumpcomments";
if($comment_desc == "") $jumpto_csite = "last"; else $jumpto_csite = "1";
$system_link_form = parse_cleanerlinks(addParameter2Link(_01article_echo_ArticleLink($_GET[$names['artid']]),$names['page']."=".$_REQUEST[$names['page']]."&".$names['cpage']."=".$jumpto_csite."&".$names['search']."=".$_REQUEST[$names['search']]."&".$names['catid']."=".$_REQUEST[$names['catid']]."#01jumpcomments_add"));
if($settings['artikelcomments'] == 1){
$zahl = mt_rand(1, 9999999999999);
$uid = md5(time().$_SERVER['REMOTE_ADDR'].$zahl.$_GET[$names['artid']]);
//Template ausgeben
include($tempdir."comments_add.html");
}
elseif ($settings['artikelcomments'] == 2 && !empty($settings['Disqus_Username'])) {
include($tempdir."comments_disqus.html");
}
}
unset($catimg);
unset($catname);
}
}
// Ausgabe der Seiten
if($sites > 1){
$option_sites = "";
for($o=1;$o<=$sites;$o++){
$option_sites .= "<option>".$o."</option>\n";
}
if(isset($_REQUEST[$names['page']]) && $_REQUEST[$names['page']] > 1){
$sz = $_REQUEST[$names['page']]-1;
if($sz != 1)
$szl1 = parse_cleanerlinks(addParameter2Link($filename,$names['page']."=1&".$names['search']."=".$_REQUEST[$names['search']]."&".$names['catid']."=".$_REQUEST[$names['catid']].$flag_archiv."#01jumpartikel"));
else $szl1 = "";
$szl2 = parse_cleanerlinks(addParameter2Link($filename,$names['page']."=".$sz."&".$names['search']."=".$_REQUEST[$names['search']]."&".$names['catid']."=".$_REQUEST[$names['catid']].$flag_archiv."#01jumpartikel"));
}
else{ $szl1 = ""; $szl2 = ""; }
if(!isset($_REQUEST[$names['page']]) || isset($_REQUEST[$names['page']]) && empty($_REQUEST[$names['page']])){
$current = 1;
if($sites > 1){ $sv = 2; }
}
else{
$current = $_REQUEST[$names['page']];
$sv = $_REQUEST[$names['page']]+1;
}
if(isset($_REQUEST[$names['page']]) && $_REQUEST[$names['page']] < $sites || !isset($_REQUEST[$names['page']]) && $sites > 1){
$svl1 = parse_cleanerlinks(addParameter2Link($filename,$names['page']."=".$sv."&".$names['search']."=".$_REQUEST[$names['search']]."&".$names['catid']."=".$_REQUEST[$names['catid']].$flag_archiv."#01jumpartikel"));
if($sv != $sites)
$svl2 = parse_cleanerlinks(addParameter2Link($filename,$names['page']."=".$sites."&".$names['search']."=".$_REQUEST[$names['search']]."&".$names['catid']."=".$_REQUEST[$names['catid']].$flag_archiv."#01jumpartikel"));
}
else{
$svl1 = "";
$svl2 = "";
if(isset($_REQUEST[$names['page']]) && $_REQUEST[$names['page']] == $sites &&
!empty($settings['archiv_time']) && $settings['archiv_time'] > 0 && $_GET[$names['artid']] != "archiv")
$svl2a = "<a href=\"".parse_cleanerlinks(addParameter2Link($filename,$names['artid']."=archiv&".$names['catid']."=".$_REQUEST[$names['catid']]."#01jumpartikel"))."\">Archiv »</a>";
}
}
// Kategorien vorhanden? --> Ausgeben
if(isset($category) && count($category) > 0){
$listcats = "";
foreach($category as $cat){
// Sind Eintrge dieser Kategorie zugeordnet?
if($qt > 0)
list($newsvorhanden) = $mysqli->query("SELECT COUNT(*) FROM ".$mysql_tables['artikel']." WHERE frei='1' AND hide='0' AND static = '0' AND utimestamp <= '".time()."' AND utimestamp>'".$qt."' AND (endtime >= '".time()."' OR endtime='0') AND newscatid LIKE '%,".$cat['id'].",%'")->fetch_array(MYSQLI_NUM);
else
list($newsvorhanden) = $mysqli->query("SELECT COUNT(*) FROM ".$mysql_tables['artikel']." WHERE frei='1' AND hide='0' AND static = '0' AND utimestamp <= '".time()."' AND (endtime >= '".time()."' OR endtime='0') AND newscatid LIKE '%,".$cat['id'].",%'")->fetch_array(MYSQLI_NUM);
if($newsvorhanden > 0)
$listcats .= "<option value=\"".$cat['id']."\">".$cat['name']." (".$newsvorhanden.")</option>\n";
$newsvorhanden = 0;
}
}
//Template einbinden
include($tempdir."pages.html");
//Template einbinden
include($tempdir."main_bottom.html");
$tempdir = "templates/";
$query = "";
?>
|
ae849b347a58c2cb1be38d04bbe56fc883d5d84a
|
https://github.com/01-scripts/01-artikelsystem
|
editor.php
|
php
|
<?php
include "lib/headers.php";
include "lib/settings.php";
$t = $text['editor'];
?>
<!DOCTYPE html>
<html style="margin: 0" onmousedown="parent.ICEcoder.mouseDown = true; parent.ICEcoder.resetAutoLogoutTimer()" onmouseup="parent.ICEcoder.mouseDown = false; parent.ICEcoder.mouseDownInCM = false; parent.ICEcoder.resetAutoLogoutTimer(); if (!parent.ICEcoder.overCloseLink) {parent.ICEcoder.tabDragEnd()}" onmousemove="if (parent.ICEcoder) {parent.ICEcoder.getMouseXY(event, 'editor'); parent.ICEcoder.functionArgsTooltip(event, 'editor'); parent.ICEcoder.resetAutoLogoutTimer(); parent.ICEcoder.canResizeFilesW()}" ondrop="if (parent.ICEcoder) {parent.ICEcoder.getMouseXY(event, 'editor')}">
<head>
<title>ICEcoder <?php echo $ICEcoder["versionNo"];?> editor</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="robots" content="noindex, nofollow">
<link rel="stylesheet" href="assets/css/codemirror.css?microtime=<?php echo microtime(true);?>">
<link rel="stylesheet" href="assets/css/show-hint.css?microtime=<?php echo microtime(true);?>">
<link rel="stylesheet" href="assets/css/lint.css?microtime=<?php echo microtime(true);?>">
<!--
codemirror-compressed.js
- incls: codemirror
- modes: clike, coffeescript, css, erlang, go, htmlmixed, javascript, julia, lua, markdown, perl, php, python, ruby, sass, sql, xml, yaml
- addon: brace-fold, closebrackets, closetag, css-hint, foldcode, foldgutter, html-hint, javascript-hint, javascript-lint, lint, match-highlighter, matchbrackets, runmode, searchcursor, show-hint, simplescrollbars, sql-hint, trailingspace, xml-fold, xml-hint
//-->
<script src="assets/js/codemirror-compressed.js?microtime=<?php echo microtime(true);?>"></script>
<?php
$pluginFiles = [
"jshint/jshint-2.5.6.min.js",
"emmet/emmet.min.js",
"pesticide/pesticide.js",
"stats.js/stats.min.js",
"responsive-helper/responsive-helper.js"
];
for ($i = 0; $i < count($pluginFiles); $i++) {
if (true === file_exists(dirname(__FILE__) . "/plugins/" . $pluginFiles[$i])) {
echo '<script src="plugins/' . $pluginFiles[$i] . '?microtime=' . microtime(true) . '"></script>' . PHP_EOL;
}
}
?>
<link rel="stylesheet" href="<?php
echo dirname(basename(__DIR__)) . '/assets/css/theme/';
echo "default" === $ICEcoder["theme"] ? 'icecoder.css' : $ICEcoder["theme"] . '.css';
echo "?microtime=" . microtime(true);
// Light themes
if (false !== array_search($ICEcoder["theme"], ["base16-light", "chrome-devtools", "duotone-light", "eclipse", "eiffel", "elegant", "mdn-like", "idle", "iplastic", "ir_white", "johnny", "juicy", "neat", "neo", "solarized", "ttcn", "xq-light"])) {
$activeLineBG = "#ccc";
$activeLineNum = "#222";
// Dark themes
} elseif (false !== array_search($ICEcoder["theme"], ["3024-night", "all-hallow-eve", "black-pearl-ii", "blackboard", "colorforth", "django", "emacs-strict", "fade-to-grey", "fake", "glitterbomb", "isotope", "ir_black", "liquibyte", "monokai-fannonedition", "oceanic", "night", "spectacular", "sunburst", "the-matrix", "tomorrow-night-blue", "tomorrow-night-bright", "tomorrow-night-eighties", "vibrant-ink", "xq-dark", "zenburn"])) {
$activeLineBG = "#222";
$activeLineNum = "#ccc";
// Other themes
} else {
$activeLineBG = "#000";
$activeLineNum = "#ccc";
}
?>">
<script src="assets/js/mmd.js?microtime=<?php echo microtime(true);?>"></script>
<link rel="stylesheet" href="assets/css/foldgutter.css?microtime=<?php echo microtime(true);?>">
<link rel="stylesheet" href="assets/css/simplescrollbars.css?microtime=<?php echo microtime(true);?>">
<style type="text/css">
/* Make sure this next one remains the 1st item, updated with JS */
.CodeMirror {position: absolute; top: 0; width: 100%; font-size: <?php echo $ICEcoder["fontSize"];?>; transition: font-size 0.25s ease; line-height: 1.3; z-index: 1}
.CodeMirror-scroll {} /* was: height: auto; overflow: visible */
/* Make sure this next one remains the 3rd item, updated with JS */
.cm-s-activeLine {background: <?php echo $activeLineBG;?> !important}
.cm-matchhighlight, .CodeMirror-focused .cm-matchhighlight {color: #fff !important; background: #06c !important}
/* Make sure this next one remains the 5th item, updated with JS */
.cm-tab {border-left-width: <?php echo $ICEcoder["visibleTabs"] ? "1px" : "0";?>; margin-left: <?php echo $ICEcoder["visibleTabs"] ? "-1px" : "0";?>; border-left-style: solid; border-left-color: rgba(255,255,255,0.15)}
/* Make sure this next one remains the 6th item, updated with JS */
.cm-s-activeLine + .CodeMirror-gutter-wrapper > .CodeMirror-linenumber {color: <?php echo $activeLineNum;?> !important}
.cm-trailingspace {
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAACCAYAAAB/qH1jAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3QUXCToH00Y1UgAAACFJREFUCNdjPMDBUc/AwNDAAAFMTAwMDA0OP34wQgX/AQBYgwYEx4f9lQAAAABJRU5ErkJggg==);
background-position: bottom left;
background-repeat: repeat-x;
}
.code-zoomed-out {font-size: 2px}
.CodeMirror-foldmarker {font-family: arial; line-height: 0.3; color: #b00; cursor: pointer;
text-shadow: #fff 1px 1px 2px, #fff -1px -1px 2px, #fff 1px -1px 2px, #fff -1px 1px 2px;
}
.CodeMirror-foldgutter {display: inline-block; width: 13px}
.CodeMirror-foldgutter-open, .CodeMirror-foldgutter-folded {position: absolute; display: inline-block; width: 13px; height: 13px; font-size: 14px; text-align: center; cursor: pointer}
.CodeMirror-foldgutter-open {background: rgba(255,255,255,0.04); color: #666}
.CodeMirror-foldgutter-open:after {position: relative; top: -4px}
.CodeMirror-foldgutter-folded {background: #800; color: #ddd}
.CodeMirror-foldgutter-folded:after {position: relative; top: -4px}
h2 {color: rgba(0,198,255,0.7)}
.cm-s-diff {left: 50%}
</style>
<link rel="stylesheet" href="assets/css/editor.css?microtime=<?php echo microtime(true);?>">
<link rel="stylesheet" href="assets/css/file-types.css?microtime=<?php echo microtime(true);?>">
<link rel="stylesheet" href="assets/css/file-type-icons.css?microtime=<?php echo microtime(true);?>">
</head>
<body style="color: #fff; margin: 0" onkeydown="return parent.ICEcoder.interceptKeys('content', event);" onkeyup="parent.ICEcoder.resetKeys(event);" onblur="parent.ICEcoder.resetKeys(event);" oncontextmenu="return false">
<div class="dataMessage" id="dataMessage"></div>
<div class="dataItemsContainer">
<div class="dataItems" style="width: 300px; margin-right: 50px">
<h2><?php echo $t['server'];?></h2>
<span class="heading"><?php echo $t['Server name, OS...'];?></span><br>
<?php
$serverAddr = $_SERVER['SERVER_ADDR'] ?? "1";
if ("1" == $serverAddr || "::1" == $serverAddr) {
$serverAddr = "127.0.0.1";
}
echo
$_SERVER['SERVER_NAME'] . "   " .
$serverType . "   " .
$serverAddr . ":" . $_SERVER['SERVER_PORT'] . "<br>" .
"(" . $_SERVER['SERVER_SOFTWARE'] . ")";?><br><br>
<span class="heading"><?php echo $t['Root'];?></span><br>
<?php echo $docRoot;?><br><br>
<span class="heading"><?php echo $t['ICEcoder root'];?></span><br>
<div id="iceRootDisplay"><?php echo "" !== $iceRoot ? $iceRoot : "[Default]";?></div><br><br>
<span class="heading"><?php echo $t['PHP version'];?></span><br>
<?php echo phpversion();?><br><br>
<span class="heading"><?php echo $t['Date & time'];?></span><br>
<span id="serverDT"></span><br><br>
<h2><?php echo $t['your device'];?></h2>
<span class="heading"><?php echo $t['Browser'];?></span><br>
<?php echo xssClean($_SERVER['HTTP_USER_AGENT'], "html");?><br><br>
<span class="heading"><?php echo $t['Your IP'];?></span><br>
<?php echo getUserIP();?><br><br>
</div>
<div class="dataItems">
<h2><?php echo $t['files'];?></h2>
<span class="heading"><?php echo $t['Last 10 files...'];?></span><br>
<ul class="fileManager" id="last10Files" style="margin-top: 5px; margin-left: 0; line-height: 21px"><?php
if (empty($ICEcoder["last10Files"])) {
echo '<div style="display: inline-block; margin-left: -39px; margin-top: -4px">' . $t['none'] . '</div><br>';
} else {
for ($i = count($ICEcoder["last10Files"]) - 1; $i >= 0; $i--) {
$fileFolderName = str_replace("\\", "/", $ICEcoder["last10Files"][$i]);
// Get extension (prefix 'ext-' to prevent invalid classes from extensions that begin with numbers)
$ext = "ext-" . pathinfo($docRoot . $iceRoot . $fileFolderName, PATHINFO_EXTENSION);
echo '<li class="pft-file ' . strtolower($ext) . '" style="margin-left: -21px">';
echo '<a style="position: relative; top: -2px; left: 5px; cursor: pointer" onclick="parent.ICEcoder.openFile(\'' . str_replace($docRoot, "", str_replace("|", "/", $ICEcoder["last10Files"][$i])) . '\')">';
echo preg_replace("/^\//", "", str_replace($docRoot, "", str_replace("|", "/", $ICEcoder["last10Files"][$i])));
echo '</a></li>';
if ($i > 0) {
echo PHP_EOL;
};
}
}
;?></ul>
<?php
if ("" !== $_SESSION['username']) {
?>
<h2><?php echo $t['multi-user']; ?></h2>
<span class="heading"><?php echo $t['Username']; ?></span><br>
<?php echo $_SESSION['username'];?><br><br>
<?php
}
?>
<h2>ICEcoder</h2>
<span class="heading"><?php echo $t['version'];?></span><br>
<?php
// If we have a .git dir, get the Git short commit hash to display as a link
$gitCommitTextLink = "";
if (true === $systemClass->functionEnabled("shell_exec") && is_dir(dirname(__FILE__) . "/.git")) {
$gitCommit = trim(shell_exec('git log --pretty="%h" -n1 HEAD'));
$gitCommitTextLink = ' (Git commit: <a href="https://github.com/icecoder/ICEcoder/commit/' . $gitCommit . '" style="color: #eee; text-decoration: none" target="_blank">' . $gitCommit . '</a>)';
}
echo $ICEcoder["versionNo"] . $gitCommitTextLink;
?><br><br>
<span class="heading"><?php echo $t['codemirror version'];?></span><br>
<script>
document.write(CodeMirror.version);
</script>
<br><br>
</div>
<div style="clear: both"></div>
<script>
let nDT = <?php echo time() * 1000;?>;
setInterval(function(){
let s = (new Date(nDT += 1e3) + '').split(' '),
d = s[2] * 1,
t = s[4].split(':'),
p = t[0] > 11 ? 'pm' : 'am',
e = d % 20 === 1 | d > 30 ? 'st' : d % 20 === 2 ? 'nd' : d % 20 === 3 ? 'rd' : 'th';
t[0] = --t[0] % 12 + 1;
if (document.getElementById('serverDT')) {
document.getElementById('serverDT').innerHTML = [s[0], d + e, s[1], s[3], t.join(':') + p].join(' ');
}
}, 1000);
</script>
</div>
<script>
CodeMirror.keyMap.ICEcoder = {
"Tab": function(cm) {
return cm.somethingSelected()
? (parent.ICEcoder.indentAuto
? cm.execCommand("indentAuto") // Honor our own setting indentAuto
: cm.indentSelection("add") // Add indent (this is default handler in CodeMirror)
)
: CodeMirror.Pass // Falls through to default or Emmet plugin
},
"Shift-Tab": "indentLess",
"Ctrl-Space": "autocomplete",
"Ctrl-Up" : false,
"Ctrl-Down" : false,
"Ctrl-Backspace" : false,
"Esc" : false,
fallthrough: ["default"]
};
// CodeMirror does not honor indentWithTabs = false properly when handling Tab key
// It does this by design, so we need to make a workaround of our own
(function(){
// let's back up original insertTab function which actually puts
var originalInsertTabFunction = CodeMirror.commands.insertTab;
// and replace it with our own, which branches on whether our ICEcoder.indentType value is "tabs"
CodeMirror.commands.insertTab = function(cm){
if ("tabs" === parent.ICEcoder.indentType){
// if it is true, then we should still put there, let's use original function
return originalInsertTabFunction(cm);
} else {
// otherwise - let's call another handler, insertSoftTab which will do the job
return cm.execCommand("insertSoftTab");
}
}
}());
function createNewCMInstance(num) {
// Establish the filename for the tab
var fileName = parent.ICEcoder.openFiles[parent.ICEcoder.selectedTab - 1];
var indentWithTabs = "tabs" === parent.ICEcoder.indentType;
// Define our CodeMirror options
var cMOptions = {
mode: "application/x-httpd-php",
lineNumbers: parent.ICEcoder.lineNumbers,
gutters: ["CodeMirror-foldgutter", "CodeMirror-lint-markers", "CodeMirror-linenumbers"],
foldGutter: {gutter: "CodeMirror-foldgutter"},
foldOptions: {minFoldSize: 1},
lineWrapping: parent.ICEcoder.lineWrapping,
indentWithTabs: indentWithTabs,
indentUnit: parent.ICEcoder.indentSize,
tabSize: parent.ICEcoder.indentSize,
matchBrackets: parent.ICEcoder.matchBrackets,
electricChars: false,
autoCloseTags: parent.ICEcoder.autoCloseTags,
autoCloseBrackets: parent.ICEcoder.autoCloseBrackets,
highlightSelectionMatches: true,
scrollbarStyle: parent.ICEcoder.scrollbarStyle,
showTrailingSpace: parent.ICEcoder.showTrailingSpace,
lint: false,
keyMap: "ICEcoder"
};
// Start editor instances, main and diff
window['cM' + num] = CodeMirror(document.body, cMOptions);
window['cM' + num + 'diff'] = CodeMirror(document.body, cMOptions);
// Define actions for those...
createNewCMInstanceEvents(num, '');
createNewCMInstanceEvents(num, 'diff');
// Now create the active lines for them
parent.ICEcoder['cMActiveLinecM' + num] = window['cM' + num].addLineClass(0, "background", "cm-s-activeLine");
parent.ICEcoder['cMActiveLinecM' + num + 'diff'] = window['cM' + num + 'diff'].addLineClass(0, "background", "cm-s-activeLine");
};
function createNewCMInstanceEvents(num, pane) {
window['cM' + num + pane].on("focus", function(thisCM) {parent.ICEcoder.cMonFocus(thisCM, 'cM' + num + pane)});
window['cM' + num + pane].on("blur", function(thisCM) {parent.ICEcoder.cMonBlur(thisCM, 'cM' + num + pane)});
window['cM' + num + pane].on("keyup", function(thisCM, evt) {parent.ICEcoder.cMonKeyUp(thisCM, 'cM' + num + pane, evt)});
window['cM' + num + pane].on("cursorActivity", function(thisCM) {parent.ICEcoder.cMonCursorActivity(thisCM, 'cM' + num + pane)});
window['cM' + num + pane].on("beforeSelectionChange", function(thisCM, changeObj) {parent.ICEcoder . prevLine = thisCM.getCursor().line;});
window['cM' + num + pane].on("change", function(thisCM, changeObj) {parent.ICEcoder.cMonChange(thisCM, 'cM' + num + pane, changeObj, CodeMirror)});
window['cM' + num + pane].on("beforeChange", function(thisCM, changeObj) {parent.ICEcoder.cMonBeforeChange(thisCM, 'cM' + num + pane, changeObj, CodeMirror)});
window['cM' + num + pane].on("scroll", function(thisCM) {parent.ICEcoder.cMonScroll(thisCM, 'cM' + num + pane)});
window['cM' + num + pane].on("update", function(thisCM) {parent.ICEcoder.cMonUpdate(thisCM, 'cM' + num + pane)});
window['cM' + num + pane].on("inputRead", function(thisCM) {parent.ICEcoder.cMonInputRead(thisCM, 'cM' + num + pane)});
window['cM' + num + pane].on("gutterClick", function(thisCM, line, gutter, evt) {parent.ICEcoder.cMonGutterClick(thisCM, line, gutter, evt, 'cM' + num + pane)});
window['cM' + num + pane].on("mousedown", function(thisCM, evt) {parent.ICEcoder.cMonMouseDown(thisCM, 'cM' + num + pane, evt)});
window['cM' + num + pane].on("paste", function(thisCM, evt) {parent.ICEcoder.cMonPaste(thisCM, 'cM' + num + pane, evt, (evt.clipboardData || window.clipboardData))});
window['cM' + num + pane].on("contextmenu", function(thisCM, evt) {parent.ICEcoder.cMonContextMenu(thisCM, 'cM' + num + pane, evt)});
window['cM' + num + pane].on("dragover", function(thisCM) {parent.ICEcoder.cMonDragOver(thisCM, event, 'cM' + num + pane)});
window['cM' + num + pane].on("renderLine", function(thisCM, line, element) {parent.ICEcoder.cMonRenderLine(thisCM, 'cM' + num + pane, line, element)});
}
</script>
<div class="resultsBar" id="resultsBar"></div>
<script>
CodeMirror.commands.autocomplete = function(cM) {
let langType = parent.ICEcoder.caretLocType;
if (-1 < ["JavaScript", "CoffeeScript", "TypeScript", "SQL", "CSS", "HTML", "XML", "Content"].indexOf(langType)) {
if ("XML" === langType || "Content" === langType) {
langType = "HTML";
}
CodeMirror.showHint(cM, CodeMirror.hint[langType.toLowerCase()]);
}
}
// Switch the CodeMirror mode on demand
parent.ICEcoder.switchMode = function(mode) {
let cM, cMdiff, fileName, fileExt;
cM = parent.ICEcoder.getcMInstance();
cMdiff = parent.ICEcoder.getcMdiffInstance();
fileName = parent.ICEcoder.openFiles[parent.ICEcoder.selectedTab - 1];
if (cM && mode) {
if (mode != cM.getOption("mode")) {
cM.setOption("mode", mode);
cMdiff.setOption("mode", mode);
}
} else if (cM && fileName) {
<?php include(dirname(__FILE__) . "/assets/js/language-modes-partial.js");?>
if (mode != cM.getOption("mode")) {
cM.setOption("mode", mode);
cM.setOption("lint", ("js" === fileExt || "json" === fileExt) && parent.ICEcoder.codeAssist ? true : false);
cMdiff.setOption("mode", mode);
cMdiff.setOption("lint", ("js" === fileExt || "json" === fileExt) && parent.ICEcoder.codeAssist ? true : false);
}
}
}
</script>
</body>
</html>
|
<?php
include "lib/headers.php";
include "lib/settings.php";
$t = $text['editor'];
?>
<!DOCTYPE html>
<html style="margin: 0" onmousedown="parent.ICEcoder.mouseDown = true; parent.ICEcoder.resetAutoLogoutTimer()" onmouseup="parent.ICEcoder.mouseDown = false; parent.ICEcoder.mouseDownInCM = false; parent.ICEcoder.resetAutoLogoutTimer(); if (!parent.ICEcoder.overCloseLink) {parent.ICEcoder.tabDragEnd()}" onmousemove="if (parent.ICEcoder) {parent.ICEcoder.getMouseXY(event, 'editor'); parent.ICEcoder.functionArgsTooltip(event, 'editor'); parent.ICEcoder.resetAutoLogoutTimer(); parent.ICEcoder.canResizeFilesW()}" ondrop="if (parent.ICEcoder) {parent.ICEcoder.getMouseXY(event, 'editor')}">
<head>
<title>ICEcoder <?php echo $ICEcoder["versionNo"];?> editor</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="robots" content="noindex, nofollow">
<link rel="stylesheet" href="assets/css/codemirror.css?microtime=<?php echo microtime(true);?>">
<link rel="stylesheet" href="assets/css/show-hint.css?microtime=<?php echo microtime(true);?>">
<link rel="stylesheet" href="assets/css/lint.css?microtime=<?php echo microtime(true);?>">
<!--
codemirror-compressed.js
- incls: codemirror
- modes: clike, coffeescript, css, erlang, go, htmlmixed, javascript, julia, lua, markdown, perl, php, python, ruby, sass, sql, xml, yaml
- addon: brace-fold, closebrackets, closetag, css-hint, foldcode, foldgutter, html-hint, javascript-hint, javascript-lint, lint, match-highlighter, matchbrackets, runmode, searchcursor, show-hint, simplescrollbars, sql-hint, trailingspace, xml-fold, xml-hint
//-->
<script src="assets/js/codemirror-compressed.js?microtime=<?php echo microtime(true);?>"></script>
<?php
$pluginFiles = [
"jshint/jshint-2.5.6.min.js",
"emmet/emmet.min.js",
"pesticide/pesticide.js",
"stats.js/stats.min.js",
"responsive-helper/responsive-helper.js"
];
for ($i = 0; $i < count($pluginFiles); $i++) {
if (true === file_exists(dirname(__FILE__) . "/plugins/" . $pluginFiles[$i])) {
echo '<script src="plugins/' . $pluginFiles[$i] . '?microtime=' . microtime(true) . '"></script>' . PHP_EOL;
}
}
?>
<link rel="stylesheet" href="<?php
echo dirname(basename(__DIR__)) . '/assets/css/theme/';
echo "default" === $ICEcoder["theme"] ? 'icecoder.css' : $ICEcoder["theme"] . '.css';
echo "?microtime=" . microtime(true);
// Light themes
if (false !== array_search($ICEcoder["theme"], ["base16-light", "chrome-devtools", "duotone-light", "eclipse", "eiffel", "elegant", "mdn-like", "idle", "iplastic", "ir_white", "johnny", "juicy", "neat", "neo", "solarized", "ttcn", "xq-light"])) {
$activeLineBG = "#ccc";
$activeLineNum = "#222";
// Dark themes
} elseif (false !== array_search($ICEcoder["theme"], ["3024-night", "all-hallow-eve", "black-pearl-ii", "blackboard", "colorforth", "django", "emacs-strict", "fade-to-grey", "fake", "glitterbomb", "isotope", "ir_black", "liquibyte", "monokai-fannonedition", "oceanic", "night", "spectacular", "sunburst", "the-matrix", "tomorrow-night-blue", "tomorrow-night-bright", "tomorrow-night-eighties", "vibrant-ink", "xq-dark", "zenburn"])) {
$activeLineBG = "#222";
$activeLineNum = "#ccc";
// Other themes
} else {
$activeLineBG = "#000";
$activeLineNum = "#ccc";
}
?>">
<script src="assets/js/mmd.js?microtime=<?php echo microtime(true);?>"></script>
<link rel="stylesheet" href="assets/css/foldgutter.css?microtime=<?php echo microtime(true);?>">
<link rel="stylesheet" href="assets/css/simplescrollbars.css?microtime=<?php echo microtime(true);?>">
<style type="text/css">
/* Make sure this next one remains the 1st item, updated with JS */
.CodeMirror {position: absolute; top: 0; width: 100%; font-size: <?php echo $ICEcoder["fontSize"];?>; transition: font-size 0.25s ease; line-height: 1.3; z-index: 1}
.CodeMirror-scroll {} /* was: height: auto; overflow: visible */
/* Make sure this next one remains the 3rd item, updated with JS */
.cm-s-activeLine {background: <?php echo $activeLineBG;?> !important}
.cm-matchhighlight, .CodeMirror-focused .cm-matchhighlight {color: #fff !important; background: #06c !important}
/* Make sure this next one remains the 5th item, updated with JS */
.cm-tab {border-left-width: <?php echo $ICEcoder["visibleTabs"] ? "1px" : "0";?>; margin-left: <?php echo $ICEcoder["visibleTabs"] ? "-1px" : "0";?>; border-left-style: solid; border-left-color: rgba(255,255,255,0.15)}
/* Make sure this next one remains the 6th item, updated with JS */
.cm-s-activeLine + .CodeMirror-gutter-wrapper > .CodeMirror-linenumber {color: <?php echo $activeLineNum;?> !important}
.cm-trailingspace {
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAACCAYAAAB/qH1jAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3QUXCToH00Y1UgAAACFJREFUCNdjPMDBUc/AwNDAAAFMTAwMDA0OP34wQgX/AQBYgwYEx4f9lQAAAABJRU5ErkJggg==);
background-position: bottom left;
background-repeat: repeat-x;
}
.code-zoomed-out {font-size: 2px}
.CodeMirror-foldmarker {font-family: arial; line-height: 0.3; color: #b00; cursor: pointer;
text-shadow: #fff 1px 1px 2px, #fff -1px -1px 2px, #fff 1px -1px 2px, #fff -1px 1px 2px;
}
.CodeMirror-foldgutter {display: inline-block; width: 13px}
.CodeMirror-foldgutter-open, .CodeMirror-foldgutter-folded {position: absolute; display: inline-block; width: 13px; height: 13px; font-size: 14px; text-align: center; cursor: pointer}
.CodeMirror-foldgutter-open {background: rgba(255,255,255,0.04); color: #666}
.CodeMirror-foldgutter-open:after {position: relative; top: -4px}
.CodeMirror-foldgutter-folded {background: #800; color: #ddd}
.CodeMirror-foldgutter-folded:after {position: relative; top: -4px}
h2 {color: rgba(0,198,255,0.7)}
.cm-s-diff {left: 50%}
</style>
<link rel="stylesheet" href="assets/css/editor.css?microtime=<?php echo microtime(true);?>">
<link rel="stylesheet" href="assets/css/file-types.css?microtime=<?php echo microtime(true);?>">
<link rel="stylesheet" href="assets/css/file-type-icons.css?microtime=<?php echo microtime(true);?>">
</head>
<body style="color: #fff; margin: 0" onkeydown="return parent.ICEcoder.interceptKeys('content', event);" onkeyup="parent.ICEcoder.resetKeys(event);" onblur="parent.ICEcoder.resetKeys(event);" oncontextmenu="return false">
<div class="dataMessage" id="dataMessage"></div>
<div class="dataItemsContainer">
<div class="dataItems" style="width: 300px; margin-right: 50px">
<h2><?php echo $t['server'];?></h2>
<span class="heading"><?php echo $t['Server name, OS...'];?></span><br>
<?php
$serverAddr = $_SERVER['SERVER_ADDR'] ?? "1";
if ("1" == $serverAddr || "::1" == $serverAddr) {
$serverAddr = "127.0.0.1";
}
echo
$_SERVER['SERVER_NAME'] . "   " .
$serverType . "   " .
$serverAddr . ":" . $_SERVER['SERVER_PORT'] . "<br>" .
"(" . $_SERVER['SERVER_SOFTWARE'] . ")";?><br><br>
<span class="heading"><?php echo $t['Root'];?></span><br>
<?php echo $docRoot;?><br><br>
<span class="heading"><?php echo $t['ICEcoder root'];?></span><br>
<div id="iceRootDisplay"><?php echo "" !== $iceRoot ? $iceRoot : "[Default]";?></div><br><br>
<span class="heading"><?php echo $t['PHP version'];?></span><br>
<?php echo phpversion();?><br><br>
<span class="heading"><?php echo $t['Date & time'];?></span><br>
<span id="serverDT"></span><br><br>
<h2><?php echo $t['your device'];?></h2>
<span class="heading"><?php echo $t['Browser'];?></span><br>
<?php echo xssClean($_SERVER['HTTP_USER_AGENT'], "html");?><br><br>
<span class="heading"><?php echo $t['Your IP'];?></span><br>
<?php echo getUserIP();?><br><br>
</div>
<div class="dataItems">
<h2><?php echo $t['files'];?></h2>
<span class="heading"><?php echo $t['Last 10 files...'];?></span><br>
<ul class="fileManager" id="last10Files" style="margin-top: 5px; margin-left: 0; line-height: 21px"><?php
if (empty($ICEcoder["last10Files"])) {
echo '<div style="display: inline-block; margin-left: -39px; margin-top: -4px">' . $t['none'] . '</div><br>';
} else {
for ($i = count($ICEcoder["last10Files"]) - 1; $i >= 0; $i--) {
$fileFolderName = str_replace("\\", "/", $ICEcoder["last10Files"][$i]);
// Get extension (prefix 'ext-' to prevent invalid classes from extensions that begin with numbers)
$ext = "ext-" . pathinfo($docRoot . $iceRoot . $fileFolderName, PATHINFO_EXTENSION);
echo '<li class="pft-file ' . strtolower($ext) . '" style="margin-left: -21px">';
echo '<a style="position: relative; top: -2px; left: 5px; cursor: pointer" onclick="parent.ICEcoder.openFile(\'' . str_replace($docRoot, "", str_replace("|", "/", $ICEcoder["last10Files"][$i])) . '\')">';
echo preg_replace("/^\//", "", str_replace($docRoot, "", str_replace("|", "/", $ICEcoder["last10Files"][$i])));
echo '</a></li>';
if ($i > 0) {
echo PHP_EOL;
};
}
}
;?></ul>
<?php
if ("" !== $_SESSION['username']) {
?>
<h2><?php echo $t['multi-user']; ?></h2>
<span class="heading"><?php echo $t['Username']; ?></span><br>
<?php echo xssClean($_SESSION['username'], "html");?><br><br>
<?php
}
?>
<h2>ICEcoder</h2>
<span class="heading"><?php echo $t['version'];?></span><br>
<?php
// If we have a .git dir, get the Git short commit hash to display as a link
$gitCommitTextLink = "";
if (true === $systemClass->functionEnabled("shell_exec") && is_dir(dirname(__FILE__) . "/.git")) {
$gitCommit = trim(shell_exec('git log --pretty="%h" -n1 HEAD'));
$gitCommitTextLink = ' (Git commit: <a href="https://github.com/icecoder/ICEcoder/commit/' . $gitCommit . '" style="color: #eee; text-decoration: none" target="_blank">' . $gitCommit . '</a>)';
}
echo $ICEcoder["versionNo"] . $gitCommitTextLink;
?><br><br>
<span class="heading"><?php echo $t['codemirror version'];?></span><br>
<script>
document.write(CodeMirror.version);
</script>
<br><br>
</div>
<div style="clear: both"></div>
<script>
let nDT = <?php echo time() * 1000;?>;
setInterval(function(){
let s = (new Date(nDT += 1e3) + '').split(' '),
d = s[2] * 1,
t = s[4].split(':'),
p = t[0] > 11 ? 'pm' : 'am',
e = d % 20 === 1 | d > 30 ? 'st' : d % 20 === 2 ? 'nd' : d % 20 === 3 ? 'rd' : 'th';
t[0] = --t[0] % 12 + 1;
if (document.getElementById('serverDT')) {
document.getElementById('serverDT').innerHTML = [s[0], d + e, s[1], s[3], t.join(':') + p].join(' ');
}
}, 1000);
</script>
</div>
<script>
CodeMirror.keyMap.ICEcoder = {
"Tab": function(cm) {
return cm.somethingSelected()
? (parent.ICEcoder.indentAuto
? cm.execCommand("indentAuto") // Honor our own setting indentAuto
: cm.indentSelection("add") // Add indent (this is default handler in CodeMirror)
)
: CodeMirror.Pass // Falls through to default or Emmet plugin
},
"Shift-Tab": "indentLess",
"Ctrl-Space": "autocomplete",
"Ctrl-Up" : false,
"Ctrl-Down" : false,
"Ctrl-Backspace" : false,
"Esc" : false,
fallthrough: ["default"]
};
// CodeMirror does not honor indentWithTabs = false properly when handling Tab key
// It does this by design, so we need to make a workaround of our own
(function(){
// let's back up original insertTab function which actually puts
var originalInsertTabFunction = CodeMirror.commands.insertTab;
// and replace it with our own, which branches on whether our ICEcoder.indentType value is "tabs"
CodeMirror.commands.insertTab = function(cm){
if ("tabs" === parent.ICEcoder.indentType){
// if it is true, then we should still put there, let's use original function
return originalInsertTabFunction(cm);
} else {
// otherwise - let's call another handler, insertSoftTab which will do the job
return cm.execCommand("insertSoftTab");
}
}
}());
function createNewCMInstance(num) {
// Establish the filename for the tab
var fileName = parent.ICEcoder.openFiles[parent.ICEcoder.selectedTab - 1];
var indentWithTabs = "tabs" === parent.ICEcoder.indentType;
// Define our CodeMirror options
var cMOptions = {
mode: "application/x-httpd-php",
lineNumbers: parent.ICEcoder.lineNumbers,
gutters: ["CodeMirror-foldgutter", "CodeMirror-lint-markers", "CodeMirror-linenumbers"],
foldGutter: {gutter: "CodeMirror-foldgutter"},
foldOptions: {minFoldSize: 1},
lineWrapping: parent.ICEcoder.lineWrapping,
indentWithTabs: indentWithTabs,
indentUnit: parent.ICEcoder.indentSize,
tabSize: parent.ICEcoder.indentSize,
matchBrackets: parent.ICEcoder.matchBrackets,
electricChars: false,
autoCloseTags: parent.ICEcoder.autoCloseTags,
autoCloseBrackets: parent.ICEcoder.autoCloseBrackets,
highlightSelectionMatches: true,
scrollbarStyle: parent.ICEcoder.scrollbarStyle,
showTrailingSpace: parent.ICEcoder.showTrailingSpace,
lint: false,
keyMap: "ICEcoder"
};
// Start editor instances, main and diff
window['cM' + num] = CodeMirror(document.body, cMOptions);
window['cM' + num + 'diff'] = CodeMirror(document.body, cMOptions);
// Define actions for those...
createNewCMInstanceEvents(num, '');
createNewCMInstanceEvents(num, 'diff');
// Now create the active lines for them
parent.ICEcoder['cMActiveLinecM' + num] = window['cM' + num].addLineClass(0, "background", "cm-s-activeLine");
parent.ICEcoder['cMActiveLinecM' + num + 'diff'] = window['cM' + num + 'diff'].addLineClass(0, "background", "cm-s-activeLine");
};
function createNewCMInstanceEvents(num, pane) {
window['cM' + num + pane].on("focus", function(thisCM) {parent.ICEcoder.cMonFocus(thisCM, 'cM' + num + pane)});
window['cM' + num + pane].on("blur", function(thisCM) {parent.ICEcoder.cMonBlur(thisCM, 'cM' + num + pane)});
window['cM' + num + pane].on("keyup", function(thisCM, evt) {parent.ICEcoder.cMonKeyUp(thisCM, 'cM' + num + pane, evt)});
window['cM' + num + pane].on("cursorActivity", function(thisCM) {parent.ICEcoder.cMonCursorActivity(thisCM, 'cM' + num + pane)});
window['cM' + num + pane].on("beforeSelectionChange", function(thisCM, changeObj) {parent.ICEcoder . prevLine = thisCM.getCursor().line;});
window['cM' + num + pane].on("change", function(thisCM, changeObj) {parent.ICEcoder.cMonChange(thisCM, 'cM' + num + pane, changeObj, CodeMirror)});
window['cM' + num + pane].on("beforeChange", function(thisCM, changeObj) {parent.ICEcoder.cMonBeforeChange(thisCM, 'cM' + num + pane, changeObj, CodeMirror)});
window['cM' + num + pane].on("scroll", function(thisCM) {parent.ICEcoder.cMonScroll(thisCM, 'cM' + num + pane)});
window['cM' + num + pane].on("update", function(thisCM) {parent.ICEcoder.cMonUpdate(thisCM, 'cM' + num + pane)});
window['cM' + num + pane].on("inputRead", function(thisCM) {parent.ICEcoder.cMonInputRead(thisCM, 'cM' + num + pane)});
window['cM' + num + pane].on("gutterClick", function(thisCM, line, gutter, evt) {parent.ICEcoder.cMonGutterClick(thisCM, line, gutter, evt, 'cM' + num + pane)});
window['cM' + num + pane].on("mousedown", function(thisCM, evt) {parent.ICEcoder.cMonMouseDown(thisCM, 'cM' + num + pane, evt)});
window['cM' + num + pane].on("paste", function(thisCM, evt) {parent.ICEcoder.cMonPaste(thisCM, 'cM' + num + pane, evt, (evt.clipboardData || window.clipboardData))});
window['cM' + num + pane].on("contextmenu", function(thisCM, evt) {parent.ICEcoder.cMonContextMenu(thisCM, 'cM' + num + pane, evt)});
window['cM' + num + pane].on("dragover", function(thisCM) {parent.ICEcoder.cMonDragOver(thisCM, event, 'cM' + num + pane)});
window['cM' + num + pane].on("renderLine", function(thisCM, line, element) {parent.ICEcoder.cMonRenderLine(thisCM, 'cM' + num + pane, line, element)});
}
</script>
<div class="resultsBar" id="resultsBar"></div>
<script>
CodeMirror.commands.autocomplete = function(cM) {
let langType = parent.ICEcoder.caretLocType;
if (-1 < ["JavaScript", "CoffeeScript", "TypeScript", "SQL", "CSS", "HTML", "XML", "Content"].indexOf(langType)) {
if ("XML" === langType || "Content" === langType) {
langType = "HTML";
}
CodeMirror.showHint(cM, CodeMirror.hint[langType.toLowerCase()]);
}
}
// Switch the CodeMirror mode on demand
parent.ICEcoder.switchMode = function(mode) {
let cM, cMdiff, fileName, fileExt;
cM = parent.ICEcoder.getcMInstance();
cMdiff = parent.ICEcoder.getcMdiffInstance();
fileName = parent.ICEcoder.openFiles[parent.ICEcoder.selectedTab - 1];
if (cM && mode) {
if (mode != cM.getOption("mode")) {
cM.setOption("mode", mode);
cMdiff.setOption("mode", mode);
}
} else if (cM && fileName) {
<?php include(dirname(__FILE__) . "/assets/js/language-modes-partial.js");?>
if (mode != cM.getOption("mode")) {
cM.setOption("mode", mode);
cM.setOption("lint", ("js" === fileExt || "json" === fileExt) && parent.ICEcoder.codeAssist ? true : false);
cMdiff.setOption("mode", mode);
cMdiff.setOption("lint", ("js" === fileExt || "json" === fileExt) && parent.ICEcoder.codeAssist ? true : false);
}
}
}
</script>
</body>
</html>
|
51cf24b2a39138e6a7b5739ef59eb38cd7c39763
|
https://github.com/icecoder/icecoder
|
language_import.php
|
php
|
<script>
mw.require("files.js");
</script>
<script>
var uploader = mw.files.uploader({
filetypes: ".xlsx, .xls",
multiple: false,
element: mw.$("#mw_uploader")
});
_mw_log_reload_int = false;
$(document).ready(function () {
$(uploader).on("FileUploaded", function (obj, data) {
$('#mw_uploader').fadeIn();
$('#upload_file_info').hide();
mw.notification.success("Moving uploaded file...");
postData = {}
postData.src = data.src;
var replace_values = $('#replace_valuesCheck1:checked').val();
if(replace_values){
postData.replace_values = 1;
}
$.post("<?php echo route('admin.language.import'); ?>", postData,
function(msg) {
if (msg.success) {
mw.reload_module('.js-language-edit-browse-<?php echo $_POST['namespaceMD5'];?>');
}
mw.notification.msg(msg);
});
});
$(uploader).on('progress', function (up, file) {
$('#mw_uploader').hide();
$('#upload_file_info').show();
mw.$("#upload_file_info").html("<b>Uploading file " + file.percent + "%</b><br /><br />");
});
$(uploader).on('error', function (up, file) {
mw.notification.error("The template must be zip.");
});
});
</script>
<div class="my-2">
<label class="control-label"><?php _e('Upload Your Language File');?></label>
<small class="text-muted d-block mb-3"><?php _e('If you have a .xlsx translated file you can import it by uploading it here.');?></small>
<div class="custom-control custom-checkbox">
<input type="checkbox" name="replace_values" value="1" class="custom-control-input" id="replace_valuesCheck1" >
<label class="custom-control-label" for="replace_valuesCheck1"><?php _e('Replace language values');?></label>
</div>
<span id="upload_file_info" style="font-size:14px;"></span>
<span id="mw_uploader" class="mw-ui-btn mw-ui-btn-info">
<i class="mw-icon-upload"></i>
<span><?php _e("Upload file"); ?></span>
</span>
</div>
|
<script>
mw.require("files.js");
</script>
<script>
var uploader = mw.files.uploader({
filetypes: ".xlsx, .xls",
multiple: false,
element: mw.$("#mw_uploader")
});
_mw_log_reload_int = false;
$(document).ready(function () {
$(uploader).on("FileUploaded", function (obj, data) {
$('#mw_uploader').fadeIn();
$('#upload_file_info').hide();
mw.notification.success("Moving uploaded file...");
postData = {}
postData.src = data.src;
var replace_values = $('#replace_valuesCheck1:checked').val();
if(replace_values){
postData.replace_values = 1;
}
$.post("<?php echo route('admin.language.import'); ?>", postData,
function(msg) {
if (msg.success) {
mw.reload_module('.js-language-edit-browse-<?php echo xss_clean($_POST['namespaceMD5']);?>');
}
mw.notification.msg(msg);
});
});
$(uploader).on('progress', function (up, file) {
$('#mw_uploader').hide();
$('#upload_file_info').show();
mw.$("#upload_file_info").html("<b>Uploading file " + file.percent + "%</b><br /><br />");
});
$(uploader).on('error', function (up, file) {
mw.notification.error("The template must be zip.");
});
});
</script>
<div class="my-2">
<label class="control-label"><?php _e('Upload Your Language File');?></label>
<small class="text-muted d-block mb-3"><?php _e('If you have a .xlsx translated file you can import it by uploading it here.');?></small>
<div class="custom-control custom-checkbox">
<input type="checkbox" name="replace_values" value="1" class="custom-control-input" id="replace_valuesCheck1" >
<label class="custom-control-label" for="replace_valuesCheck1"><?php _e('Replace language values');?></label>
</div>
<span id="upload_file_info" style="font-size:14px;"></span>
<span id="mw_uploader" class="mw-ui-btn mw-ui-btn-info">
<i class="mw-icon-upload"></i>
<span><?php _e("Upload file"); ?></span>
</span>
</div>
|
df8add930ecfa7f5b18c67c3f748c137fe890906
|
https://github.com/microweber/microweber
|
init_task.h
|
objective-c
|
#ifndef _LINUX__INIT_TASK_H
#define _LINUX__INIT_TASK_H
#include <linux/rcupdate.h>
#include <linux/irqflags.h>
#include <linux/utsname.h>
#include <linux/lockdep.h>
#include <linux/ftrace.h>
#include <linux/ipc.h>
#include <linux/pid_namespace.h>
#include <linux/user_namespace.h>
#include <linux/securebits.h>
#include <net/net_namespace.h>
extern struct files_struct init_files;
extern struct fs_struct init_fs;
#define INIT_SIGNALS(sig) { \
.nr_threads = 1, \
.wait_chldexit = __WAIT_QUEUE_HEAD_INITIALIZER(sig.wait_chldexit),\
.shared_pending = { \
.list = LIST_HEAD_INIT(sig.shared_pending.list), \
.signal = {{0}}}, \
.posix_timers = LIST_HEAD_INIT(sig.posix_timers), \
.cpu_timers = INIT_CPU_TIMERS(sig.cpu_timers), \
.rlim = INIT_RLIMITS, \
.cputimer = { \
.cputime = INIT_CPUTIME, \
.running = 0, \
.lock = __SPIN_LOCK_UNLOCKED(sig.cputimer.lock), \
}, \
}
extern struct nsproxy init_nsproxy;
#define INIT_SIGHAND(sighand) { \
.count = ATOMIC_INIT(1), \
.action = { { { .sa_handler = NULL, } }, }, \
.siglock = __SPIN_LOCK_UNLOCKED(sighand.siglock), \
.signalfd_wqh = __WAIT_QUEUE_HEAD_INITIALIZER(sighand.signalfd_wqh), \
}
extern struct group_info init_groups;
#define INIT_STRUCT_PID { \
.count = ATOMIC_INIT(1), \
.tasks = { \
{ .first = &init_task.pids[PIDTYPE_PID].node }, \
{ .first = &init_task.pids[PIDTYPE_PGID].node }, \
{ .first = &init_task.pids[PIDTYPE_SID].node }, \
}, \
.level = 0, \
.numbers = { { \
.nr = 0, \
.ns = &init_pid_ns, \
.pid_chain = { .next = NULL, .pprev = NULL }, \
}, } \
}
#define INIT_PID_LINK(type) \
{ \
.node = { \
.next = NULL, \
.pprev = &init_struct_pid.tasks[type].first, \
}, \
.pid = &init_struct_pid, \
}
#ifdef CONFIG_AUDITSYSCALL
#define INIT_IDS \
.loginuid = -1, \
.sessionid = -1,
#else
#define INIT_IDS
#endif
/*
* Because of the reduced scope of CAP_SETPCAP when filesystem
* capabilities are in effect, it is safe to allow CAP_SETPCAP to
* be available in the default configuration.
*/
# define CAP_INIT_BSET CAP_FULL_SET
#ifdef CONFIG_TREE_PREEMPT_RCU
#define INIT_TASK_RCU_PREEMPT(tsk) \
.rcu_read_lock_nesting = 0, \
.rcu_read_unlock_special = 0, \
.rcu_blocked_node = NULL, \
.rcu_node_entry = LIST_HEAD_INIT(tsk.rcu_node_entry),
#else
#define INIT_TASK_RCU_PREEMPT(tsk)
#endif
extern struct cred init_cred;
#ifdef CONFIG_PERF_EVENTS
# define INIT_PERF_EVENTS(tsk) \
.perf_event_mutex = \
__MUTEX_INITIALIZER(tsk.perf_event_mutex), \
.perf_event_list = LIST_HEAD_INIT(tsk.perf_event_list),
#else
# define INIT_PERF_EVENTS(tsk)
#endif
/*
* INIT_TASK is used to set up the first task table, touch at
* your own risk!. Base=0, limit=0x1fffff (=2MB)
*/
#define INIT_TASK(tsk) \
{ \
.state = 0, \
.stack = &init_thread_info, \
.usage = ATOMIC_INIT(2), \
.flags = PF_KTHREAD, \
.lock_depth = -1, \
.prio = MAX_PRIO-20, \
.static_prio = MAX_PRIO-20, \
.normal_prio = MAX_PRIO-20, \
.policy = SCHED_NORMAL, \
.cpus_allowed = CPU_MASK_ALL, \
.mm = NULL, \
.active_mm = &init_mm, \
.se = { \
.group_node = LIST_HEAD_INIT(tsk.se.group_node), \
}, \
.rt = { \
.run_list = LIST_HEAD_INIT(tsk.rt.run_list), \
.time_slice = HZ, \
.nr_cpus_allowed = NR_CPUS, \
}, \
.tasks = LIST_HEAD_INIT(tsk.tasks), \
.pushable_tasks = PLIST_NODE_INIT(tsk.pushable_tasks, MAX_PRIO), \
.ptraced = LIST_HEAD_INIT(tsk.ptraced), \
.ptrace_entry = LIST_HEAD_INIT(tsk.ptrace_entry), \
.real_parent = &tsk, \
.parent = &tsk, \
.children = LIST_HEAD_INIT(tsk.children), \
.sibling = LIST_HEAD_INIT(tsk.sibling), \
.group_leader = &tsk, \
.real_cred = &init_cred, \
.cred = &init_cred, \
.cred_guard_mutex = \
__MUTEX_INITIALIZER(tsk.cred_guard_mutex), \
.comm = "swapper", \
.thread = INIT_THREAD, \
.fs = &init_fs, \
.files = &init_files, \
.signal = &init_signals, \
.sighand = &init_sighand, \
.nsproxy = &init_nsproxy, \
.pending = { \
.list = LIST_HEAD_INIT(tsk.pending.list), \
.signal = {{0}}}, \
.blocked = {{0}}, \
.alloc_lock = __SPIN_LOCK_UNLOCKED(tsk.alloc_lock), \
.journal_info = NULL, \
.cpu_timers = INIT_CPU_TIMERS(tsk.cpu_timers), \
.fs_excl = ATOMIC_INIT(0), \
.pi_lock = __RAW_SPIN_LOCK_UNLOCKED(tsk.pi_lock), \
.timer_slack_ns = 50000, /* 50 usec default slack */ \
.pids = { \
[PIDTYPE_PID] = INIT_PID_LINK(PIDTYPE_PID), \
[PIDTYPE_PGID] = INIT_PID_LINK(PIDTYPE_PGID), \
[PIDTYPE_SID] = INIT_PID_LINK(PIDTYPE_SID), \
}, \
.dirties = INIT_PROP_LOCAL_SINGLE(dirties), \
INIT_IDS \
INIT_PERF_EVENTS(tsk) \
INIT_TRACE_IRQFLAGS \
INIT_LOCKDEP \
INIT_FTRACE_GRAPH \
INIT_TRACE_RECURSION \
INIT_TASK_RCU_PREEMPT(tsk) \
}
#define INIT_CPU_TIMERS(cpu_timers) \
{ \
LIST_HEAD_INIT(cpu_timers[0]), \
LIST_HEAD_INIT(cpu_timers[1]), \
LIST_HEAD_INIT(cpu_timers[2]), \
}
/* Attach to the init_task data structure for proper alignment */
#define __init_task_data __attribute__((__section__(".data.init_task")))
#endif
|
#ifndef _LINUX__INIT_TASK_H
#define _LINUX__INIT_TASK_H
#include <linux/rcupdate.h>
#include <linux/irqflags.h>
#include <linux/utsname.h>
#include <linux/lockdep.h>
#include <linux/ftrace.h>
#include <linux/ipc.h>
#include <linux/pid_namespace.h>
#include <linux/user_namespace.h>
#include <linux/securebits.h>
#include <net/net_namespace.h>
extern struct files_struct init_files;
extern struct fs_struct init_fs;
#define INIT_SIGNALS(sig) { \
.nr_threads = 1, \
.wait_chldexit = __WAIT_QUEUE_HEAD_INITIALIZER(sig.wait_chldexit),\
.shared_pending = { \
.list = LIST_HEAD_INIT(sig.shared_pending.list), \
.signal = {{0}}}, \
.posix_timers = LIST_HEAD_INIT(sig.posix_timers), \
.cpu_timers = INIT_CPU_TIMERS(sig.cpu_timers), \
.rlim = INIT_RLIMITS, \
.cputimer = { \
.cputime = INIT_CPUTIME, \
.running = 0, \
.lock = __SPIN_LOCK_UNLOCKED(sig.cputimer.lock), \
}, \
}
extern struct nsproxy init_nsproxy;
#define INIT_SIGHAND(sighand) { \
.count = ATOMIC_INIT(1), \
.action = { { { .sa_handler = NULL, } }, }, \
.siglock = __SPIN_LOCK_UNLOCKED(sighand.siglock), \
.signalfd_wqh = __WAIT_QUEUE_HEAD_INITIALIZER(sighand.signalfd_wqh), \
}
extern struct group_info init_groups;
#define INIT_STRUCT_PID { \
.count = ATOMIC_INIT(1), \
.tasks = { \
{ .first = &init_task.pids[PIDTYPE_PID].node }, \
{ .first = &init_task.pids[PIDTYPE_PGID].node }, \
{ .first = &init_task.pids[PIDTYPE_SID].node }, \
}, \
.level = 0, \
.numbers = { { \
.nr = 0, \
.ns = &init_pid_ns, \
.pid_chain = { .next = NULL, .pprev = NULL }, \
}, } \
}
#define INIT_PID_LINK(type) \
{ \
.node = { \
.next = NULL, \
.pprev = &init_struct_pid.tasks[type].first, \
}, \
.pid = &init_struct_pid, \
}
#ifdef CONFIG_AUDITSYSCALL
#define INIT_IDS \
.loginuid = -1, \
.sessionid = -1,
#else
#define INIT_IDS
#endif
/*
* Because of the reduced scope of CAP_SETPCAP when filesystem
* capabilities are in effect, it is safe to allow CAP_SETPCAP to
* be available in the default configuration.
*/
# define CAP_INIT_BSET CAP_FULL_SET
#ifdef CONFIG_TREE_PREEMPT_RCU
#define INIT_TASK_RCU_PREEMPT(tsk) \
.rcu_read_lock_nesting = 0, \
.rcu_read_unlock_special = 0, \
.rcu_blocked_node = NULL, \
.rcu_node_entry = LIST_HEAD_INIT(tsk.rcu_node_entry),
#else
#define INIT_TASK_RCU_PREEMPT(tsk)
#endif
extern struct cred init_cred;
#ifdef CONFIG_PERF_EVENTS
# define INIT_PERF_EVENTS(tsk) \
.perf_event_mutex = \
__MUTEX_INITIALIZER(tsk.perf_event_mutex), \
.perf_event_list = LIST_HEAD_INIT(tsk.perf_event_list),
#else
# define INIT_PERF_EVENTS(tsk)
#endif
/*
* INIT_TASK is used to set up the first task table, touch at
* your own risk!. Base=0, limit=0x1fffff (=2MB)
*/
#define INIT_TASK(tsk) \
{ \
.state = 0, \
.stack = &init_thread_info, \
.usage = ATOMIC_INIT(2), \
.flags = PF_KTHREAD, \
.lock_depth = -1, \
.prio = MAX_PRIO-20, \
.static_prio = MAX_PRIO-20, \
.normal_prio = MAX_PRIO-20, \
.policy = SCHED_NORMAL, \
.cpus_allowed = CPU_MASK_ALL, \
.mm = NULL, \
.active_mm = &init_mm, \
.se = { \
.group_node = LIST_HEAD_INIT(tsk.se.group_node), \
}, \
.rt = { \
.run_list = LIST_HEAD_INIT(tsk.rt.run_list), \
.time_slice = HZ, \
.nr_cpus_allowed = NR_CPUS, \
}, \
.tasks = LIST_HEAD_INIT(tsk.tasks), \
.pushable_tasks = PLIST_NODE_INIT(tsk.pushable_tasks, MAX_PRIO), \
.ptraced = LIST_HEAD_INIT(tsk.ptraced), \
.ptrace_entry = LIST_HEAD_INIT(tsk.ptrace_entry), \
.real_parent = &tsk, \
.parent = &tsk, \
.children = LIST_HEAD_INIT(tsk.children), \
.sibling = LIST_HEAD_INIT(tsk.sibling), \
.group_leader = &tsk, \
.real_cred = &init_cred, \
.cred = &init_cred, \
.cred_guard_mutex = \
__MUTEX_INITIALIZER(tsk.cred_guard_mutex), \
.comm = "swapper", \
.thread = INIT_THREAD, \
.fs = &init_fs, \
.files = &init_files, \
.signal = &init_signals, \
.sighand = &init_sighand, \
.nsproxy = &init_nsproxy, \
.pending = { \
.list = LIST_HEAD_INIT(tsk.pending.list), \
.signal = {{0}}}, \
.blocked = {{0}}, \
.alloc_lock = __SPIN_LOCK_UNLOCKED(tsk.alloc_lock), \
.journal_info = NULL, \
.cpu_timers = INIT_CPU_TIMERS(tsk.cpu_timers), \
.fs_excl = ATOMIC_INIT(0), \
.pi_lock = __RAW_SPIN_LOCK_UNLOCKED(tsk.pi_lock), \
.timer_slack_ns = 50000, /* 50 usec default slack */ \
.pids = { \
[PIDTYPE_PID] = INIT_PID_LINK(PIDTYPE_PID), \
[PIDTYPE_PGID] = INIT_PID_LINK(PIDTYPE_PGID), \
[PIDTYPE_SID] = INIT_PID_LINK(PIDTYPE_SID), \
}, \
.thread_group = LIST_HEAD_INIT(tsk.thread_group), \
.dirties = INIT_PROP_LOCAL_SINGLE(dirties), \
INIT_IDS \
INIT_PERF_EVENTS(tsk) \
INIT_TRACE_IRQFLAGS \
INIT_LOCKDEP \
INIT_FTRACE_GRAPH \
INIT_TRACE_RECURSION \
INIT_TASK_RCU_PREEMPT(tsk) \
}
#define INIT_CPU_TIMERS(cpu_timers) \
{ \
LIST_HEAD_INIT(cpu_timers[0]), \
LIST_HEAD_INIT(cpu_timers[1]), \
LIST_HEAD_INIT(cpu_timers[2]), \
}
/* Attach to the init_task data structure for proper alignment */
#define __init_task_data __attribute__((__section__(".data.init_task")))
#endif
|
fa2755e20ab0c7215d99c2dc7c262e98a09b01df
|
https://github.com/torvalds/linux
|
faq.php
|
php
|
<?php
include_once('./_common.php');
//dbconfig파일에 $g5['faq_table'] , $g5['faq_master_table'] 배열변수가 있는지 체크
if( !isset($g5['faq_table']) || !isset($g5['faq_master_table']) ){
die('<meta charset="utf-8">관리자 모드에서 게시판관리->FAQ관리를 먼저 확인해 주세요.');
}
// FAQ MASTER
$faq_master_list = array();
$sql = " select * from {$g5['faq_master_table']} order by fm_order,fm_id ";
$result = sql_query($sql);
while ($row=sql_fetch_array($result))
{
$key = $row['fm_id'];
if (!isset($fm_id)) $fm_id = $key;
$faq_master_list[$key] = $row;
}
if (isset($fm_id) && $fm_id){
$qstr .= '&fm_id=' . $fm_id; // 마스터faq key_id
}
$fm = $faq_master_list[$fm_id];
if (!$fm['fm_id'])
alert('등록된 내용이 없습니다.');
$g5['title'] = $fm['fm_subject'];
$skin_file = $faq_skin_path.'/list.skin.php';
include_once('./_head.php');
if(is_file($skin_file)) {
$admin_href = '';
$himg_src = '';
$timg_src = '';
if($is_admin)
$admin_href = G5_ADMIN_URL.'/faqmasterform.php?w=u&fm_id='.$fm_id;
if(!G5_IS_MOBILE) {
$himg = G5_DATA_PATH.'/faq/'.$fm_id.'_h';
if (is_file($himg)){
$himg_src = G5_DATA_URL.'/faq/'.$fm_id.'_h';
}
$timg = G5_DATA_PATH.'/faq/'.$fm_id.'_t';
if (is_file($timg)){
$timg_src = G5_DATA_URL.'/faq/'.$fm_id.'_t';
}
}
$category_href = G5_BBS_URL.'/faq.php';
$category_stx = '';
$faq_list = array();
$stx = trim($stx);
$sql_search = '';
if($stx) {
$sql_search = " and ( INSTR(fa_subject, '$stx') > 0 or INSTR(fa_content, '$stx') > 0 ) ";
}
if ($page < 1) { $page = 1; } // 페이지가 없으면 첫 페이지 (1 페이지)
$page_rows = G5_IS_MOBILE ? $config['cf_mobile_page_rows'] : $config['cf_page_rows'];
$sql = " select count(*) as cnt
from {$g5['faq_table']}
where fm_id = '$fm_id'
$sql_search ";
$total = sql_fetch($sql);
$total_count = $total['cnt'];
$total_page = ceil($total_count / $page_rows); // 전체 페이지 계산
$from_record = ($page - 1) * $page_rows; // 시작 열을 구함
$sql = " select *
from {$g5['faq_table']}
where fm_id = '$fm_id'
$sql_search
order by fa_order , fa_id
limit $from_record, $page_rows ";
$result = sql_query($sql);
for ($i=0;$row=sql_fetch_array($result);$i++){
$faq_list[] = $row;
if($stx) {
$faq_list[$i]['fa_subject'] = search_font($stx, conv_content($faq_list[$i]['fa_subject'], 1));
$faq_list[$i]['fa_content'] = search_font($stx, conv_content($faq_list[$i]['fa_content'], 1));
}
}
include_once($skin_file);
} else {
echo '<p>'.str_replace(G5_PATH.'/', '', $skin_file).'이 존재하지 않습니다.</p>';
}
include_once('./_tail.php');
|
<?php
include_once('./_common.php');
//dbconfig파일에 $g5['faq_table'] , $g5['faq_master_table'] 배열변수가 있는지 체크
if( !isset($g5['faq_table']) || !isset($g5['faq_master_table']) ){
die('<meta charset="utf-8">관리자 모드에서 게시판관리->FAQ관리를 먼저 확인해 주세요.');
}
// FAQ MASTER
$faq_master_list = array();
$sql = " select * from {$g5['faq_master_table']} order by fm_order,fm_id ";
$result = sql_query($sql);
while ($row=sql_fetch_array($result))
{
$key = $row['fm_id'];
if (!isset($fm_id)) $fm_id = $key;
$faq_master_list[$key] = $row;
}
if (isset($fm_id) && $fm_id){
$fm_id = (int) $fm_id;
$qstr .= '&fm_id=' . $fm_id; // 마스터faq key_id
}
$fm = $faq_master_list[$fm_id];
if (!$fm['fm_id'])
alert('등록된 내용이 없습니다.');
$g5['title'] = $fm['fm_subject'];
$skin_file = $faq_skin_path.'/list.skin.php';
include_once('./_head.php');
if(is_file($skin_file)) {
$admin_href = '';
$himg_src = '';
$timg_src = '';
if($is_admin)
$admin_href = G5_ADMIN_URL.'/faqmasterform.php?w=u&fm_id='.$fm_id;
if(!G5_IS_MOBILE) {
$himg = G5_DATA_PATH.'/faq/'.$fm_id.'_h';
if (is_file($himg)){
$himg_src = G5_DATA_URL.'/faq/'.$fm_id.'_h';
}
$timg = G5_DATA_PATH.'/faq/'.$fm_id.'_t';
if (is_file($timg)){
$timg_src = G5_DATA_URL.'/faq/'.$fm_id.'_t';
}
}
$category_href = G5_BBS_URL.'/faq.php';
$category_stx = '';
$faq_list = array();
$stx = trim($stx);
$sql_search = '';
if($stx) {
$sql_search = " and ( INSTR(fa_subject, '$stx') > 0 or INSTR(fa_content, '$stx') > 0 ) ";
}
if ($page < 1) { $page = 1; } // 페이지가 없으면 첫 페이지 (1 페이지)
$page_rows = G5_IS_MOBILE ? $config['cf_mobile_page_rows'] : $config['cf_page_rows'];
$sql = " select count(*) as cnt
from {$g5['faq_table']}
where fm_id = '$fm_id'
$sql_search ";
$total = sql_fetch($sql);
$total_count = $total['cnt'];
$total_page = ceil($total_count / $page_rows); // 전체 페이지 계산
$from_record = ($page - 1) * $page_rows; // 시작 열을 구함
$sql = " select *
from {$g5['faq_table']}
where fm_id = '$fm_id'
$sql_search
order by fa_order , fa_id
limit $from_record, $page_rows ";
$result = sql_query($sql);
for ($i=0;$row=sql_fetch_array($result);$i++){
$faq_list[] = $row;
if($stx) {
$faq_list[$i]['fa_subject'] = search_font($stx, conv_content($faq_list[$i]['fa_subject'], 1));
$faq_list[$i]['fa_content'] = search_font($stx, conv_content($faq_list[$i]['fa_content'], 1));
}
}
include_once($skin_file);
} else {
echo '<p>'.str_replace(G5_PATH.'/', '', $skin_file).'이 존재하지 않습니다.</p>';
}
include_once('./_tail.php');
|
ba062ca5b62809106d5a2f7df942ffcb44ecb5a9
|
https://github.com/gnuboard/gnuboard5
|
conf.py
|
python
|
# -*- coding: utf-8 -*-
#
# fastecdsa documentation build configuration file, created by
# sphinx-quickstart on Thu Dec 15 20:02:52 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
from datetime import datetime
import os
import sys
from unittest import mock
sys.path.insert(0, os.path.abspath('.'))
sys.path.insert(0, os.path.abspath('../'))
MOCK_MODULES = ['fastecdsa._ecdsa', 'fastecdsa.curvemath']
for mod_name in MOCK_MODULES:
sys.modules[mod_name] = mock.Mock()
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['sphinx.ext.mathjax', 'sphinx.ext.autodoc']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = ['.rst', '.md']
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'fastecdsa'
copyright = '{}, Anton Kueltz'.format(datetime.now().year)
author = 'Anton Kueltz'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '2.1'
# The full version, including alpha/beta/rc tags.
release = '2.1.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
# html_theme = 'alabaster'
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'fastecdsadoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'fastecdsa.tex', 'fastecdsa Documentation',
'Anton Kueltz', 'manual'),
]
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'fastecdsa', 'fastecdsa Documentation',
[author], 1)
]
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'fastecdsa', 'fastecdsa Documentation',
author, 'fastecdsa', 'One line description of project.',
'Miscellaneous'),
]
|
# -*- coding: utf-8 -*-
#
# fastecdsa documentation build configuration file, created by
# sphinx-quickstart on Thu Dec 15 20:02:52 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
from datetime import datetime
import os
import sys
from unittest import mock
sys.path.insert(0, os.path.abspath('.'))
sys.path.insert(0, os.path.abspath('../'))
MOCK_MODULES = ['fastecdsa._ecdsa', 'fastecdsa.curvemath']
for mod_name in MOCK_MODULES:
sys.modules[mod_name] = mock.Mock()
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['sphinx.ext.mathjax', 'sphinx.ext.autodoc']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = ['.rst', '.md']
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'fastecdsa'
copyright = '{}, Anton Kueltz'.format(datetime.now().year)
author = 'Anton Kueltz'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '2.1'
# The full version, including alpha/beta/rc tags.
release = '2.1.2'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
# html_theme = 'alabaster'
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'fastecdsadoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'fastecdsa.tex', 'fastecdsa Documentation',
'Anton Kueltz', 'manual'),
]
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'fastecdsa', 'fastecdsa Documentation',
[author], 1)
]
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'fastecdsa', 'fastecdsa Documentation',
author, 'fastecdsa', 'One line description of project.',
'Miscellaneous'),
]
|
7b64e3efaa806b4daaf73bb5172af3581812f8de
|
https://github.com/antonkueltz/fastecdsa
|
bug_change_status_page.php
|
php
|
<?php
# MantisBT - A PHP based bugtracking system
# MantisBT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# MantisBT 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 MantisBT. If not, see <http://www.gnu.org/licenses/>.
/**
* Handling of Bug Status change
* @package MantisBT
* @copyright Copyright 2000 - 2002 Kenzaburo Ito - kenito@300baud.org
* @copyright Copyright 2002 MantisBT Team - mantisbt-dev@lists.sourceforge.net
* @link http://www.mantisbt.org
*
* @uses core.php
* @uses access_api.php
* @uses authentication_api.php
* @uses bug_api.php
* @uses config_api.php
* @uses constant_inc.php
* @uses custom_field_api.php
* @uses date_api.php
* @uses event_api.php
* @uses form_api.php
* @uses gpc_api.php
* @uses helper_api.php
* @uses html_api.php
* @uses lang_api.php
* @uses print_api.php
* @uses relationship_api.php
* @uses sponsorship_api.php
* @uses version_api.php
*/
$g_allow_browser_cache = 1;
require_once( 'core.php' );
require_api( 'access_api.php' );
require_api( 'authentication_api.php' );
require_api( 'bug_api.php' );
require_api( 'config_api.php' );
require_api( 'constant_inc.php' );
require_api( 'custom_field_api.php' );
require_api( 'date_api.php' );
require_api( 'event_api.php' );
require_api( 'form_api.php' );
require_api( 'gpc_api.php' );
require_api( 'helper_api.php' );
require_api( 'html_api.php' );
require_api( 'lang_api.php' );
require_api( 'print_api.php' );
require_api( 'relationship_api.php' );
require_api( 'sponsorship_api.php' );
require_api( 'version_api.php' );
$f_bug_id = gpc_get_int( 'id' );
$t_bug = bug_get( $f_bug_id );
$t_file = __FILE__;
$t_mantis_dir = dirname( __FILE__ ) . DIRECTORY_SEPARATOR;
$t_show_page_header = false;
$t_force_readonly = true;
$t_fields_config_option = 'bug_change_status_page_fields';
if( $t_bug->project_id != helper_get_current_project() ) {
# in case the current project is not the same project of the bug we are viewing...
# ... override the current project. This to avoid problems with categories and handlers lists etc.
$g_project_override = $t_bug->project_id;
}
$f_new_status = gpc_get_int( 'new_status' );
$f_change_type = gpc_get_string( 'change_type', BUG_UPDATE_TYPE_CHANGE_STATUS );
$t_reopen = config_get( 'bug_reopen_status', null, null, $t_bug->project_id );
$t_resolved = config_get( 'bug_resolved_status_threshold', null, null, $t_bug->project_id );
$t_closed = config_get( 'bug_closed_status_threshold', null, null, $t_bug->project_id );
$t_current_user_id = auth_get_current_user_id();
# Ensure user has proper access level before proceeding
if( $f_new_status == $t_reopen && $f_change_type == BUG_UPDATE_TYPE_REOPEN ) {
access_ensure_can_reopen_bug( $t_bug, $t_current_user_id );
} else if( $f_new_status == $t_closed ) {
access_ensure_can_close_bug( $t_bug, $t_current_user_id );
} else if( bug_is_readonly( $f_bug_id )
|| !access_has_bug_level( access_get_status_threshold( $f_new_status, $t_bug->project_id ), $f_bug_id, $t_current_user_id ) ) {
access_denied();
}
$t_can_update_due_date = access_has_bug_level( config_get( 'due_date_update_threshold' ), $f_bug_id );
if( $t_can_update_due_date ) {
require_js( 'jscalendar/calendar.js' );
require_js( 'jscalendar/lang/calendar-en.js' );
require_js( 'jscalendar/calendar-setup.js' );
require_css( 'calendar-blue.css' );
}
# get new issue handler if set, otherwise default to original handler
$f_handler_id = gpc_get_int( 'handler_id', $t_bug->handler_id );
if( config_get( 'bug_assigned_status' ) == $f_new_status ) {
$t_bug_sponsored = config_get( 'enable_sponsorship' )
&& sponsorship_get_amount( sponsorship_get_all_ids( $f_bug_id ) ) > 0;
if( $t_bug_sponsored && !access_has_bug_level( config_get( 'assign_sponsored_bugs_threshold' ), $f_bug_id ) ) {
trigger_error( ERROR_SPONSORSHIP_ASSIGNER_ACCESS_LEVEL_TOO_LOW, ERROR );
}
if( $f_handler_id != NO_USER ) {
if( !access_has_bug_level( config_get( 'handle_bug_threshold' ), $f_bug_id, $f_handler_id ) ) {
trigger_error( ERROR_HANDLER_ACCESS_TOO_LOW, ERROR );
}
if( $t_bug_sponsored && !access_has_bug_level( config_get( 'handle_sponsored_bugs_threshold' ), $f_bug_id, $f_handler_id ) ) {
trigger_error( ERROR_SPONSORSHIP_HANDLER_ACCESS_LEVEL_TOO_LOW, ERROR );
}
}
}
$t_status_label = str_replace( ' ', '_', MantisEnum::getLabel( config_get( 'status_enum_string' ), $f_new_status ) );
html_page_top( bug_format_summary( $f_bug_id, SUMMARY_CAPTION ) );
print_recently_visited();
?>
<br />
<div id="bug-change-status-div" class="form-container">
<h2><?php echo lang_get( $t_status_label . '_bug_title' ); ?></h2>
<?php
if( $f_new_status >= $t_resolved ) {
if( relationship_can_resolve_bug( $f_bug_id ) == false ) {
echo '<div class="footer">';
echo lang_get( 'relationship_warning_blocking_bugs_not_resolved_2' );
echo '</div>';
}
}
?>
<form id="bug-change-status-form" name="bug_change_status_form" method="post" action="bug_update.php">
<fieldset>
<?php echo form_security_field( 'bug_update' ) ?>
<input type="hidden" name="bug_id" value="<?php echo $f_bug_id ?>" />
<input type="hidden" name="status" value="<?php echo $f_new_status ?>" />
<input type="hidden" name="last_updated" value="<?php echo $t_bug->last_updated ?>" />
<input type="hidden" name="action_type" value="<?php echo $f_change_type; ?>" />
<?php
$t_current_resolution = $t_bug->resolution;
$t_bug_is_open = $t_current_resolution < $t_resolved;
if( $f_new_status >= $t_resolved && ( $f_new_status < $t_closed || $t_bug_is_open ) ) {
?>
<!-- Resolution -->
<div class="field-container">
<label for="resolution">
<span><?php echo lang_get( 'resolution' ) ?></span>
</label>
<span class="select">
<select name="resolution">
<?php
$t_resolution = $t_bug_is_open ? config_get( 'bug_resolution_fixed_threshold' ) : $t_current_resolution;
$t_relationships = relationship_get_all_src( $f_bug_id );
foreach( $t_relationships as $t_relationship ) {
if( $t_relationship->type == BUG_DUPLICATE ) {
$t_resolution = config_get( 'bug_duplicate_resolution' );
break;
}
}
print_enum_string_option_list( 'resolution', $t_resolution );
?>
</select>
</span>
<span class="label-style"></span>
</div>
<?php
if( $t_resolution != config_get( 'bug_duplicate_resolution' ) ) {
?>
<!-- Duplicate ID -->
<div class="field-container">
<label for="duplicate_id">
<span><?php echo lang_get( 'duplicate_id' ) ?></span>
</label>
<span class="input">
<input type="text" name="duplicate_id" maxlength="10" />
</span>
<span class="label-style"></span>
</div>
<?php
}
}
if( access_has_bug_level( config_get( 'update_bug_assign_threshold', config_get( 'update_bug_threshold' ) ), $f_bug_id ) ) {
$t_suggested_handler_id = $t_bug->handler_id;
if( $t_suggested_handler_id == NO_USER && access_has_bug_level( config_get( 'handle_bug_threshold' ), $f_bug_id ) ) {
$t_suggested_handler_id = $t_current_user_id;
}
?>
<!-- Assigned To -->
<div class="field-container">
<label for="handler_id">
<span><?php echo lang_get( 'assigned_to' ) ?></span>
</label>
<span class="select">
<select name="handler_id">
<option value="0"></option>
<?php print_assign_to_option_list( $t_suggested_handler_id, $t_bug->project_id ) ?>
</select>
</span>
<span class="label-style"></span>
</div>
<?php
}
if( $t_can_update_due_date ) {
$t_date_to_display = '';
if( !date_is_null( $t_bug->due_date ) ) {
$t_date_to_display = date( config_get( 'calendar_date_format' ), $t_bug->due_date );
}
?>
<!-- Due date -->
<div class="field-container">
<label for="due_date">
<span><?php echo lang_get( 'due_date' ) ?></span>
</label>
<span class="input">
<input type="text" id="due_date" name="due_date"
class="datetime" size="20" maxlength="16"
<?php helper_get_tab_index() ?>
value="<?php echo $t_date_to_display ?>" />
</span>
<span class="label-style"></span>
</div>
<?php
}
?>
<!-- Custom Fields -->
<?php
/**
* @todo thraxisp - I undid part of the change for #5068 for #5527
* We really need to say what fields are shown in which statusses. For now,
* this page will show required custom fields in update mode, or
* display or required fields on resolve or close
*/
$t_custom_status_label = 'update'; # Don't show custom fields by default
if( ( $f_new_status >= $t_resolved ) && ( $f_new_status < $t_closed ) ) {
$t_custom_status_label = 'resolved';
}
if( $t_closed == $f_new_status ) {
$t_custom_status_label = 'closed';
}
$t_related_custom_field_ids = custom_field_get_linked_ids( $t_bug->project_id );
foreach( $t_related_custom_field_ids as $t_id ) {
$t_def = custom_field_get_definition( $t_id );
$t_display = $t_def['display_' . $t_custom_status_label];
$t_require = $t_def['require_' . $t_custom_status_label];
if( ( 'update' == $t_custom_status_label ) && ( !$t_require ) ) {
continue;
}
if( in_array( $t_custom_status_label, array( 'resolved', 'closed' ) ) && !( $t_display || $t_require ) ) {
continue;
}
$t_has_write_access = custom_field_has_write_access( $t_id, $f_bug_id );
$t_class_required = $t_require && $t_has_write_access ? 'class="required"' : '';
?>
<div class="field-container">
<label <?php echo $t_class_required ?> for="due_date">
<span><?php echo lang_get_defaulted( $t_def['name'] ) ?></span>
</label>
<span class="input">
<?php
if( $t_has_write_access ) {
print_custom_field_input( $t_def, $f_bug_id );
} elseif( custom_field_has_read_access( $t_id, $f_bug_id ) ) {
print_custom_field_value( $t_def, $t_id, $f_bug_id );
}
?>
</span>
<span class="label-style"></span>
</div>
<?php
} # foreach( $t_related_custom_field_ids as $t_id )
if( ( $f_new_status >= $t_resolved ) ) {
if( version_should_show_product_version( $t_bug->project_id )
&& !bug_is_readonly( $f_bug_id )
&& access_has_bug_level( config_get( 'update_bug_threshold' ), $f_bug_id )
) {
?>
<!-- Fixed in Version -->
<div class="field-container">
<label for="due_date">
<span><?php echo lang_get( 'fixed_in_version' ) ?></span>
</label>
<span class="select">
<select name="fixed_in_version">
<?php print_version_option_list( $t_bug->fixed_in_version, $t_bug->project_id, VERSION_ALL ) ?>
</select>
</span>
<span class="label-style"></span>
</div>
<?php
}
}
event_signal( 'EVENT_UPDATE_BUG_STATUS_FORM', array( $f_bug_id, $f_new_status ) );
if( $f_change_type == BUG_UPDATE_TYPE_REOPEN ) {
?>
<!-- Bug was re-opened -->
<?php
printf( ' <input type="hidden" name="resolution" value="%s" />' . "\n", config_get( 'bug_reopen_resolution' ) );
}
?>
<!-- Bugnote -->
<div class="field-container">
<label for="bugnote_text">
<span><?php echo lang_get( 'add_bugnote_title' ) ?></span>
</label>
<span class="textarea">
<textarea name="bugnote_text" cols="80" rows="10"></textarea>
</span>
<span class="label-style"></span>
</div>
<?php
if( access_has_bug_level( config_get( 'private_bugnote_threshold' ), $f_bug_id ) ) {
$t_default_bugnote_view_status = config_get( 'default_bugnote_view_status' );
?>
<!-- View status -->
<div class="field-container">
<label for="private">
<span><?php echo lang_get( 'view_status' ) ?></span>
</label>
<span class="checkbox">
<?php
if( access_has_bug_level( config_get( 'set_view_status_threshold' ), $f_bug_id ) ) {
?>
<input type="checkbox" name="private"
<?php check_checked( $t_default_bugnote_view_status, VS_PRIVATE ); ?> />
<?php
echo lang_get( 'private' );
} else {
echo get_enum_element( 'project_view_state', $t_default_bugnote_view_status );
}
?>
</span>
<span class="label-style"></span>
</div>
<?php
}
if( config_get( 'time_tracking_enabled' )
&& access_has_bug_level( config_get( 'private_bugnote_threshold' ), $f_bug_id )
&& access_has_bug_level( config_get( 'time_tracking_edit_threshold' ), $f_bug_id )
) {
?>
<!-- Time tracking -->
<div class="field-container">
<label for="time_tracking">
<span><?php echo lang_get( 'time_tracking' ) ?></span>
</label>
<span class="input">
<input type="text" name="time_tracking" size="5" placeholder="hh:mm" />
</span>
<span class="label-style"></span>
</div>
<?php
}
event_signal( 'EVENT_BUGNOTE_ADD_FORM', array( $f_bug_id ) );
?>
<!-- Submit Button -->
<span class="submit-button">
<input type="submit" class="button" value="<?php echo lang_get( $t_status_label . '_bug_button' ) ?>" />
</span>
</fieldset>
</form>
</div>
<br>
<?php
define( 'BUG_VIEW_INC_ALLOW', true );
include( dirname( __FILE__ ) . '/bug_view_inc.php' );
|
<?php
# MantisBT - A PHP based bugtracking system
# MantisBT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# MantisBT 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 MantisBT. If not, see <http://www.gnu.org/licenses/>.
/**
* Handling of Bug Status change
* @package MantisBT
* @copyright Copyright 2000 - 2002 Kenzaburo Ito - kenito@300baud.org
* @copyright Copyright 2002 MantisBT Team - mantisbt-dev@lists.sourceforge.net
* @link http://www.mantisbt.org
*
* @uses core.php
* @uses access_api.php
* @uses authentication_api.php
* @uses bug_api.php
* @uses config_api.php
* @uses constant_inc.php
* @uses custom_field_api.php
* @uses date_api.php
* @uses event_api.php
* @uses form_api.php
* @uses gpc_api.php
* @uses helper_api.php
* @uses html_api.php
* @uses lang_api.php
* @uses print_api.php
* @uses relationship_api.php
* @uses sponsorship_api.php
* @uses version_api.php
*/
$g_allow_browser_cache = 1;
require_once( 'core.php' );
require_api( 'access_api.php' );
require_api( 'authentication_api.php' );
require_api( 'bug_api.php' );
require_api( 'config_api.php' );
require_api( 'constant_inc.php' );
require_api( 'custom_field_api.php' );
require_api( 'date_api.php' );
require_api( 'event_api.php' );
require_api( 'form_api.php' );
require_api( 'gpc_api.php' );
require_api( 'helper_api.php' );
require_api( 'html_api.php' );
require_api( 'lang_api.php' );
require_api( 'print_api.php' );
require_api( 'relationship_api.php' );
require_api( 'sponsorship_api.php' );
require_api( 'version_api.php' );
$f_bug_id = gpc_get_int( 'id' );
$t_bug = bug_get( $f_bug_id );
$t_file = __FILE__;
$t_mantis_dir = dirname( __FILE__ ) . DIRECTORY_SEPARATOR;
$t_show_page_header = false;
$t_force_readonly = true;
$t_fields_config_option = 'bug_change_status_page_fields';
if( $t_bug->project_id != helper_get_current_project() ) {
# in case the current project is not the same project of the bug we are viewing...
# ... override the current project. This to avoid problems with categories and handlers lists etc.
$g_project_override = $t_bug->project_id;
}
$f_new_status = gpc_get_int( 'new_status' );
$f_change_type = gpc_get_string( 'change_type', BUG_UPDATE_TYPE_CHANGE_STATUS );
$t_reopen = config_get( 'bug_reopen_status', null, null, $t_bug->project_id );
$t_resolved = config_get( 'bug_resolved_status_threshold', null, null, $t_bug->project_id );
$t_closed = config_get( 'bug_closed_status_threshold', null, null, $t_bug->project_id );
$t_current_user_id = auth_get_current_user_id();
# Ensure user has proper access level before proceeding
if( $f_new_status == $t_reopen && $f_change_type == BUG_UPDATE_TYPE_REOPEN ) {
access_ensure_can_reopen_bug( $t_bug, $t_current_user_id );
} else if( $f_new_status == $t_closed ) {
access_ensure_can_close_bug( $t_bug, $t_current_user_id );
} else if( bug_is_readonly( $f_bug_id )
|| !access_has_bug_level( access_get_status_threshold( $f_new_status, $t_bug->project_id ), $f_bug_id, $t_current_user_id ) ) {
access_denied();
}
$t_can_update_due_date = access_has_bug_level( config_get( 'due_date_update_threshold' ), $f_bug_id );
if( $t_can_update_due_date ) {
require_js( 'jscalendar/calendar.js' );
require_js( 'jscalendar/lang/calendar-en.js' );
require_js( 'jscalendar/calendar-setup.js' );
require_css( 'calendar-blue.css' );
}
# get new issue handler if set, otherwise default to original handler
$f_handler_id = gpc_get_int( 'handler_id', $t_bug->handler_id );
if( config_get( 'bug_assigned_status' ) == $f_new_status ) {
$t_bug_sponsored = config_get( 'enable_sponsorship' )
&& sponsorship_get_amount( sponsorship_get_all_ids( $f_bug_id ) ) > 0;
if( $t_bug_sponsored && !access_has_bug_level( config_get( 'assign_sponsored_bugs_threshold' ), $f_bug_id ) ) {
trigger_error( ERROR_SPONSORSHIP_ASSIGNER_ACCESS_LEVEL_TOO_LOW, ERROR );
}
if( $f_handler_id != NO_USER ) {
if( !access_has_bug_level( config_get( 'handle_bug_threshold' ), $f_bug_id, $f_handler_id ) ) {
trigger_error( ERROR_HANDLER_ACCESS_TOO_LOW, ERROR );
}
if( $t_bug_sponsored && !access_has_bug_level( config_get( 'handle_sponsored_bugs_threshold' ), $f_bug_id, $f_handler_id ) ) {
trigger_error( ERROR_SPONSORSHIP_HANDLER_ACCESS_LEVEL_TOO_LOW, ERROR );
}
}
}
$t_status_label = str_replace( ' ', '_', MantisEnum::getLabel( config_get( 'status_enum_string' ), $f_new_status ) );
html_page_top( bug_format_summary( $f_bug_id, SUMMARY_CAPTION ) );
print_recently_visited();
?>
<br />
<div id="bug-change-status-div" class="form-container">
<h2><?php echo lang_get( $t_status_label . '_bug_title' ); ?></h2>
<?php
if( $f_new_status >= $t_resolved ) {
if( relationship_can_resolve_bug( $f_bug_id ) == false ) {
echo '<div class="footer">';
echo lang_get( 'relationship_warning_blocking_bugs_not_resolved_2' );
echo '</div>';
}
}
?>
<form id="bug-change-status-form" name="bug_change_status_form" method="post" action="bug_update.php">
<fieldset>
<?php echo form_security_field( 'bug_update' ) ?>
<input type="hidden" name="bug_id" value="<?php echo $f_bug_id ?>" />
<input type="hidden" name="status" value="<?php echo $f_new_status ?>" />
<input type="hidden" name="last_updated" value="<?php echo $t_bug->last_updated ?>" />
<input type="hidden" name="action_type" value="<?php echo string_attribute( $f_change_type ); ?>" />
<?php
$t_current_resolution = $t_bug->resolution;
$t_bug_is_open = $t_current_resolution < $t_resolved;
if( $f_new_status >= $t_resolved && ( $f_new_status < $t_closed || $t_bug_is_open ) ) {
?>
<!-- Resolution -->
<div class="field-container">
<label for="resolution">
<span><?php echo lang_get( 'resolution' ) ?></span>
</label>
<span class="select">
<select name="resolution">
<?php
$t_resolution = $t_bug_is_open ? config_get( 'bug_resolution_fixed_threshold' ) : $t_current_resolution;
$t_relationships = relationship_get_all_src( $f_bug_id );
foreach( $t_relationships as $t_relationship ) {
if( $t_relationship->type == BUG_DUPLICATE ) {
$t_resolution = config_get( 'bug_duplicate_resolution' );
break;
}
}
print_enum_string_option_list( 'resolution', $t_resolution );
?>
</select>
</span>
<span class="label-style"></span>
</div>
<?php
if( $t_resolution != config_get( 'bug_duplicate_resolution' ) ) {
?>
<!-- Duplicate ID -->
<div class="field-container">
<label for="duplicate_id">
<span><?php echo lang_get( 'duplicate_id' ) ?></span>
</label>
<span class="input">
<input type="text" name="duplicate_id" maxlength="10" />
</span>
<span class="label-style"></span>
</div>
<?php
}
}
if( access_has_bug_level( config_get( 'update_bug_assign_threshold', config_get( 'update_bug_threshold' ) ), $f_bug_id ) ) {
$t_suggested_handler_id = $t_bug->handler_id;
if( $t_suggested_handler_id == NO_USER && access_has_bug_level( config_get( 'handle_bug_threshold' ), $f_bug_id ) ) {
$t_suggested_handler_id = $t_current_user_id;
}
?>
<!-- Assigned To -->
<div class="field-container">
<label for="handler_id">
<span><?php echo lang_get( 'assigned_to' ) ?></span>
</label>
<span class="select">
<select name="handler_id">
<option value="0"></option>
<?php print_assign_to_option_list( $t_suggested_handler_id, $t_bug->project_id ) ?>
</select>
</span>
<span class="label-style"></span>
</div>
<?php
}
if( $t_can_update_due_date ) {
$t_date_to_display = '';
if( !date_is_null( $t_bug->due_date ) ) {
$t_date_to_display = date( config_get( 'calendar_date_format' ), $t_bug->due_date );
}
?>
<!-- Due date -->
<div class="field-container">
<label for="due_date">
<span><?php echo lang_get( 'due_date' ) ?></span>
</label>
<span class="input">
<input type="text" id="due_date" name="due_date"
class="datetime" size="20" maxlength="16"
<?php helper_get_tab_index() ?>
value="<?php echo $t_date_to_display ?>" />
</span>
<span class="label-style"></span>
</div>
<?php
}
?>
<!-- Custom Fields -->
<?php
/**
* @todo thraxisp - I undid part of the change for #5068 for #5527
* We really need to say what fields are shown in which statusses. For now,
* this page will show required custom fields in update mode, or
* display or required fields on resolve or close
*/
$t_custom_status_label = 'update'; # Don't show custom fields by default
if( ( $f_new_status >= $t_resolved ) && ( $f_new_status < $t_closed ) ) {
$t_custom_status_label = 'resolved';
}
if( $t_closed == $f_new_status ) {
$t_custom_status_label = 'closed';
}
$t_related_custom_field_ids = custom_field_get_linked_ids( $t_bug->project_id );
foreach( $t_related_custom_field_ids as $t_id ) {
$t_def = custom_field_get_definition( $t_id );
$t_display = $t_def['display_' . $t_custom_status_label];
$t_require = $t_def['require_' . $t_custom_status_label];
if( ( 'update' == $t_custom_status_label ) && ( !$t_require ) ) {
continue;
}
if( in_array( $t_custom_status_label, array( 'resolved', 'closed' ) ) && !( $t_display || $t_require ) ) {
continue;
}
$t_has_write_access = custom_field_has_write_access( $t_id, $f_bug_id );
$t_class_required = $t_require && $t_has_write_access ? 'class="required"' : '';
?>
<div class="field-container">
<label <?php echo $t_class_required ?> for="due_date">
<span><?php echo lang_get_defaulted( $t_def['name'] ) ?></span>
</label>
<span class="input">
<?php
if( $t_has_write_access ) {
print_custom_field_input( $t_def, $f_bug_id );
} elseif( custom_field_has_read_access( $t_id, $f_bug_id ) ) {
print_custom_field_value( $t_def, $t_id, $f_bug_id );
}
?>
</span>
<span class="label-style"></span>
</div>
<?php
} # foreach( $t_related_custom_field_ids as $t_id )
if( ( $f_new_status >= $t_resolved ) ) {
if( version_should_show_product_version( $t_bug->project_id )
&& !bug_is_readonly( $f_bug_id )
&& access_has_bug_level( config_get( 'update_bug_threshold' ), $f_bug_id )
) {
?>
<!-- Fixed in Version -->
<div class="field-container">
<label for="due_date">
<span><?php echo lang_get( 'fixed_in_version' ) ?></span>
</label>
<span class="select">
<select name="fixed_in_version">
<?php print_version_option_list( $t_bug->fixed_in_version, $t_bug->project_id, VERSION_ALL ) ?>
</select>
</span>
<span class="label-style"></span>
</div>
<?php
}
}
event_signal( 'EVENT_UPDATE_BUG_STATUS_FORM', array( $f_bug_id, $f_new_status ) );
if( $f_change_type == BUG_UPDATE_TYPE_REOPEN ) {
?>
<!-- Bug was re-opened -->
<?php
printf( ' <input type="hidden" name="resolution" value="%s" />' . "\n", config_get( 'bug_reopen_resolution' ) );
}
?>
<!-- Bugnote -->
<div class="field-container">
<label for="bugnote_text">
<span><?php echo lang_get( 'add_bugnote_title' ) ?></span>
</label>
<span class="textarea">
<textarea name="bugnote_text" cols="80" rows="10"></textarea>
</span>
<span class="label-style"></span>
</div>
<?php
if( access_has_bug_level( config_get( 'private_bugnote_threshold' ), $f_bug_id ) ) {
$t_default_bugnote_view_status = config_get( 'default_bugnote_view_status' );
?>
<!-- View status -->
<div class="field-container">
<label for="private">
<span><?php echo lang_get( 'view_status' ) ?></span>
</label>
<span class="checkbox">
<?php
if( access_has_bug_level( config_get( 'set_view_status_threshold' ), $f_bug_id ) ) {
?>
<input type="checkbox" name="private"
<?php check_checked( $t_default_bugnote_view_status, VS_PRIVATE ); ?> />
<?php
echo lang_get( 'private' );
} else {
echo get_enum_element( 'project_view_state', $t_default_bugnote_view_status );
}
?>
</span>
<span class="label-style"></span>
</div>
<?php
}
if( config_get( 'time_tracking_enabled' )
&& access_has_bug_level( config_get( 'private_bugnote_threshold' ), $f_bug_id )
&& access_has_bug_level( config_get( 'time_tracking_edit_threshold' ), $f_bug_id )
) {
?>
<!-- Time tracking -->
<div class="field-container">
<label for="time_tracking">
<span><?php echo lang_get( 'time_tracking' ) ?></span>
</label>
<span class="input">
<input type="text" name="time_tracking" size="5" placeholder="hh:mm" />
</span>
<span class="label-style"></span>
</div>
<?php
}
event_signal( 'EVENT_BUGNOTE_ADD_FORM', array( $f_bug_id ) );
?>
<!-- Submit Button -->
<span class="submit-button">
<input type="submit" class="button" value="<?php echo lang_get( $t_status_label . '_bug_button' ) ?>" />
</span>
</fieldset>
</form>
</div>
<br>
<?php
define( 'BUG_VIEW_INC_ALLOW', true );
include( dirname( __FILE__ ) . '/bug_view_inc.php' );
|
a2d90ecabf3bcf3aa22ed9dbbecfd3d37902956f
|
https://github.com/mantisbt/mantisbt
|
UploadFileCheck.php
|
php
|
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
* SuiteCRM is an extension to SugarCRM Community Edition developed by Salesagility Ltd.
* Copyright (C) 2011 - 2014 Salesagility Ltd.
*
* This program 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 SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* 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 or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code 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 "Powered by
* SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not
* reasonably feasible for technical reasons, the Appropriate Legal Notices must
* display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM".
********************************************************************************/
require_once('include/JSON.php');
require_once('include/entryPoint.php');
require_once 'include/upload_file.php';
global $sugar_config;
$supportedExtensions = array('jpg', 'png', 'jpeg');
$json = getJSONobj();
$rmdir=true;
$returnArray = array();
if($json->decode(html_entity_decode($_REQUEST['forQuotes']))){
$returnArray['forQuotes']="quotes";
}else{
$returnArray['forQuotes']="company";
}
$upload_ok = false;
$upload_path = 'tmp_logo_' . $returnArray['forQuotes'] . '_upload';
if(isset($_FILES['file_1'])){
$upload = new UploadFile('file_1');
if($upload->confirm_upload()) {
$upload_dir = 'upload://' . $upload_path;
UploadStream::ensureDir($upload_dir);
$file_name = $upload_dir."/".$upload->get_stored_file_name();
if($upload->final_move($file_name)) {
$upload_ok = true;
}
}
}
if(!$upload_ok) {
$returnArray['data']='not_recognize';
echo $json->encode($returnArray);
sugar_cleanup();
exit();
}
if(file_exists($file_name) && is_file($file_name)) {
$encoded_file_name = rawurlencode($upload->get_stored_file_name());
$returnArray['path'] = $upload_path . '/' . $encoded_file_name;
$returnArray['url']= 'cache/images/'.$encoded_file_name;
if(!verify_uploaded_image($file_name, $returnArray['forQuotes'] == 'quotes')) {
$returnArray['data']='other';
$returnArray['path'] = '';
} else {
$img_size = getimagesize($file_name);
$filetype = $img_size['mime'];
$test=$img_size[0]/$img_size[1];
if (($test>10 || $test<1) && $returnArray['forQuotes'] == 'company'){
$rmdir=false;
$returnArray['data']='size';
}
if (($test>20 || $test<3)&& $returnArray['forQuotes'] == 'quotes')
$returnArray['data']='size';
copy($file_name, sugar_cached('images/'.$upload->get_stored_file_name()));
}
if(!empty($returnArray['data'])){
echo $json->encode($returnArray);
}else{
$rmdir=false;
$returnArray['data']='ok';
echo $json->encode($returnArray);
}
}else{
$returnArray['data']='file_error';
echo $json->encode($returnArray);
}
sugar_cleanup();
exit();
|
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
* SuiteCRM is an extension to SugarCRM Community Edition developed by Salesagility Ltd.
* Copyright (C) 2011 - 2014 Salesagility Ltd.
*
* This program 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 SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* 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 or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code 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 "Powered by
* SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not
* reasonably feasible for technical reasons, the Appropriate Legal Notices must
* display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM".
********************************************************************************/
require_once('include/JSON.php');
require_once('include/entryPoint.php');
require_once 'include/upload_file.php';
global $sugar_config;
$supportedExtensions = array('jpg', 'png', 'jpeg');
$json = getJSONobj();
$rmdir=true;
$returnArray = array();
if($json->decode(html_entity_decode($_REQUEST['forQuotes']))){
$returnArray['forQuotes']="quotes";
}else{
$returnArray['forQuotes']="company";
}
$upload_ok = false;
$upload_path = 'tmp_logo_' . $returnArray['forQuotes'] . '_upload';
if(isset($_FILES['file_1'])){
$upload = new UploadFile('file_1');
if($upload->confirm_upload()) {
$upload_dir = 'upload://' . $upload_path;
UploadStream::ensureDir($upload_dir);
$file_name = $upload_dir."/".$upload->get_stored_file_name();
if($upload->final_move($file_name)) {
$upload_ok = true;
}
}
}
if(!$upload_ok) {
$returnArray['data']='not_recognize';
echo $json->encode($returnArray);
sugar_cleanup();
exit();
}
if(file_exists($file_name) && is_file($file_name)) {
$encoded_file_name = rawurlencode($upload->get_stored_file_name());
$returnArray['path'] = $upload_path . '/' . $encoded_file_name;
$returnArray['url']= 'cache/images/'.$encoded_file_name;
if(!verify_uploaded_image($file_name, $returnArray['forQuotes'] == 'quotes')) {
$returnArray['data']='other';
$returnArray['path'] = '';
unlink($file_name);
} else {
$img_size = getimagesize($file_name);
$filetype = $img_size['mime'];
$test=$img_size[0]/$img_size[1];
if (($test>10 || $test<1) && $returnArray['forQuotes'] == 'company'){
$rmdir=false;
$returnArray['data']='size';
}
if (($test>20 || $test<3)&& $returnArray['forQuotes'] == 'quotes')
$returnArray['data']='size';
copy($file_name, sugar_cached('images/'.$upload->get_stored_file_name()));
}
if(!empty($returnArray['data'])){
echo $json->encode($returnArray);
}else{
$rmdir=false;
$returnArray['data']='ok';
echo $json->encode($returnArray);
}
}else{
$returnArray['data']='file_error';
echo $json->encode($returnArray);
}
sugar_cleanup();
exit();
|
b1b3fd61c7697ad2073cd253d31c9462929e7bb5
|
https://github.com/salesagility/suitecrm
|
template.php
|
php
|
<?php defined('SYSPATH') OR die('No direct access allowed.'); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="refresh" content="<?php echo $this->config->conf['refresh'] ?>; url=<?php echo $_SERVER['REQUEST_URI'] ?>" />
<title><?php if (isset($this->title)) echo html::specialchars($this->title) ?></title>
<?php echo html::stylesheet('media/css/common.css') ?>
<?php echo html::stylesheet('media/css/imgareaselect-default.css') ?>
<?php echo html::stylesheet('media/css/ui-'.$this->theme.'/jquery-ui.css') ?>
<?php echo html::link('media/images/favicon.ico','icon','image/ico') ?>
<?php echo html::script('media/js/jquery-min.js')?>
<?php echo html::script('media/js/jquery.imgareaselect.min.js')?>
<?php echo html::script('media/js/jquery-ui.min.js')?>
<?php echo html::script('media/js/jquery-ui-timepicker-addon.js')?>
<script type="text/javascript">
jQuery.noConflict();
jQuery(window).load(
function() {
jQuery('div.graph').each(function(){
var img_width = jQuery(this).next('img').width();
var rrd_width = parseInt(jQuery(this).css('width'));
var left = img_width - rrd_width - <?php echo $this->config->conf['right_zoom_offset'] ?>;
jQuery(this).css('left', left);
jQuery(this).css('cursor', 'e-resize');
jQuery(this).attr('title', 'Click to zoom in');
});
jQuery('img.goto').css('visibility', 'visible');
jQuery('div.graph').imgAreaSelect({ handles: false, autoHide: true,
fadeSpeed: 500, onSelectEnd: redirect, minHeight: '<?php echo $this->config->conf['graph_height'] ?>' });
function redirect(img, selection) {
if (!selection.width || !selection.height)
return;
var graph_width = parseInt(jQuery(img).css('width'));
var link = jQuery(img).attr('id');
var ostart = Math.abs(jQuery(img).attr('start'));
var oend = Math.abs(jQuery(img).attr('end'));
var delta = (oend - ostart);
if( delta < 600 )
delta = 600;
var sec_per_px = parseInt( delta / graph_width);
var start = ostart + Math.ceil( selection.x1 * sec_per_px );
var end = ostart + ( selection.x2 * sec_per_px );
window.location = link + '&start=' + start + '&end=' + end ;
}
var sfilter = "<?php echo $this->session->get('sfilter') ?>";
var spfilter = "<?php echo $this->session->get('spfilter') ?>";
var pfilter = "<?php echo $this->session->get('pfilter') ?>";
if(jQuery("#service-filter").length) {
console.log("send keyup")
jQuery("#service-filter").keyup()
}
if(jQuery("#special-filter").length) {
jQuery("#special-filter").keyup()
}
if(jQuery("#page-filter").length) {
jQuery("#page-filter").keyup()
}
});
jQuery(document).ready(function(){
var path = "<?php echo url::base(TRUE)."/"?>";
jQuery("img").fadeIn(1500);
jQuery("#basket_action_add a").live("click", function(){
var item = (this.id)
jQuery.ajax({
type: "POST",
url: path + "ajax/basket/add",
data: { item: item },
success: function(msg){
jQuery("#basket_items").html(msg);
window.location.reload()
}
});
});
jQuery("#basket-clear").live("click", function(){
jQuery.ajax({
type: "POST",
url: path + "ajax/basket/clear",
success: function(msg){
window.location.reload()
}
});
});
jQuery("#basket-show").live("click", function(){
window.location.href = path + 'page/basket'
});
jQuery(".basket_action_remove a").live("click", function(){
var item = (this.id)
jQuery.ajax({
type: "POST",
url: path + "ajax/basket/remove/",
data: { item: item },
success: function(msg){
jQuery("#basket_items").html(msg);
window.location.reload()
}
});
});
jQuery("#basket_items" ).sortable({
update: function(event, ui) {
var items = jQuery(this).sortable('toArray').toString();
jQuery.ajax({
type: "POST",
url: path + "ajax/basket/sort",
data: { items: items },
success: function(msg){
window.location.reload()
}
});
}
});
jQuery("#basket_items" ).disableSelection();
jQuery("#remove_timerange_session").click(function(){
jQuery.ajax({
type: "GET",
url: path + "ajax/remove/timerange",
success: function(){
location.reload();
}
});
});
jQuery("#service-filter").keyup(function () {
var sfilter = jQuery("#service-filter").val();
if(sfilter != "") {
jQuery("#service-filter").css('background-color','#ff9999');
}else{
jQuery("#service-filter").css('background-color','white');
}
jQuery.ajax({
type: "POST",
url: path + "ajax/filter/set-sfilter",
data: { sfilter: sfilter }
});
jQuery("#services span[id^='service']").each(function () {
if (jQuery(this).attr('id').search(new RegExp("service-.*" + sfilter,"i")) == 0) {
jQuery(this).show();
} else {
jQuery(this).hide();
}
});
});
jQuery("#special-filter").keyup(function () {
var spfilter = jQuery("#special-filter").val();
if(spfilter != "") {
jQuery("#special-filter").css('background-color','#ff9999');
}else{
jQuery("#special-filter").css('background-color','white');
}
jQuery.ajax({
type: "POST",
url: path + "ajax/filter/set-spfilter",
data: { spfilter: spfilter }
});
jQuery("#special-templates span[id^='special']").each(function () {
if (jQuery(this).attr('id').search(new RegExp("special-.*" + spfilter,"i")) == 0) {
jQuery(this).show();
} else {
jQuery(this).hide();
};
});
});
jQuery("#page-filter").keyup(function () {
var pfilter = jQuery("#page-filter").val();
if(pfilter != "") {
jQuery("#page-filter").css('background-color','#ff9999');
}else{
jQuery("#page-filter").css('background-color','white');
}
jQuery.ajax({
type: "POST",
url: path + "ajax/filter/set-pfilter",
data: { pfilter: pfilter }
});
jQuery("#pages span[id^='page']").each(function () {
if (jQuery(this).attr('id').search(new RegExp("page-.*" + pfilter,"i")) == 0) {
jQuery(this).show();
} else {
jQuery(this).hide();
};
});
});
});
<?php if (!empty($zoom_header)) {
echo $zoom_header;
} ?>
</script>
</head>
<body>
<?php if (!empty($graph)) {
echo $graph;
} ?>
<?php if (!empty($debug)) {
echo $debug;
} ?>
<?php if (!empty($color)) {
echo $color;
} ?>
<?php if (!empty($zoom)) {
echo $zoom;
} ?>
<?php if (!empty($page)) {
echo $page;
} ?>
<?php if (!empty($docs)) {
echo $docs;
} ?>
</body>
</html>
|
<?php defined('SYSPATH') OR die('No direct access allowed.'); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="refresh" content="<?php echo $this->config->conf['refresh'] ?>" />
<title><?php if (isset($this->title)) echo html::specialchars($this->title) ?></title>
<?php echo html::stylesheet('media/css/common.css') ?>
<?php echo html::stylesheet('media/css/imgareaselect-default.css') ?>
<?php echo html::stylesheet('media/css/ui-'.$this->theme.'/jquery-ui.css') ?>
<?php echo html::link('media/images/favicon.ico','icon','image/ico') ?>
<?php echo html::script('media/js/jquery-min.js')?>
<?php echo html::script('media/js/jquery.imgareaselect.min.js')?>
<?php echo html::script('media/js/jquery-ui.min.js')?>
<?php echo html::script('media/js/jquery-ui-timepicker-addon.js')?>
<script type="text/javascript">
jQuery.noConflict();
jQuery(window).load(
function() {
jQuery('div.graph').each(function(){
var img_width = jQuery(this).next('img').width();
var rrd_width = parseInt(jQuery(this).css('width'));
var left = img_width - rrd_width - <?php echo $this->config->conf['right_zoom_offset'] ?>;
jQuery(this).css('left', left);
jQuery(this).css('cursor', 'e-resize');
jQuery(this).attr('title', 'Click to zoom in');
});
jQuery('img.goto').css('visibility', 'visible');
jQuery('div.graph').imgAreaSelect({ handles: false, autoHide: true,
fadeSpeed: 500, onSelectEnd: redirect, minHeight: '<?php echo $this->config->conf['graph_height'] ?>' });
function redirect(img, selection) {
if (!selection.width || !selection.height)
return;
var graph_width = parseInt(jQuery(img).css('width'));
var link = jQuery(img).attr('id');
var ostart = Math.abs(jQuery(img).attr('start'));
var oend = Math.abs(jQuery(img).attr('end'));
var delta = (oend - ostart);
if( delta < 600 )
delta = 600;
var sec_per_px = parseInt( delta / graph_width);
var start = ostart + Math.ceil( selection.x1 * sec_per_px );
var end = ostart + ( selection.x2 * sec_per_px );
window.location = link + '&start=' + start + '&end=' + end ;
}
var sfilter = "<?php echo $this->session->get('sfilter') ?>";
var spfilter = "<?php echo $this->session->get('spfilter') ?>";
var pfilter = "<?php echo $this->session->get('pfilter') ?>";
if(jQuery("#service-filter").length) {
console.log("send keyup")
jQuery("#service-filter").keyup()
}
if(jQuery("#special-filter").length) {
jQuery("#special-filter").keyup()
}
if(jQuery("#page-filter").length) {
jQuery("#page-filter").keyup()
}
});
jQuery(document).ready(function(){
var path = "<?php echo url::base(TRUE)."/"?>";
jQuery("img").fadeIn(1500);
jQuery("#basket_action_add a").live("click", function(){
var item = (this.id)
jQuery.ajax({
type: "POST",
url: path + "ajax/basket/add",
data: { item: item },
success: function(msg){
jQuery("#basket_items").html(msg);
window.location.reload()
}
});
});
jQuery("#basket-clear").live("click", function(){
jQuery.ajax({
type: "POST",
url: path + "ajax/basket/clear",
success: function(msg){
window.location.reload()
}
});
});
jQuery("#basket-show").live("click", function(){
window.location.href = path + 'page/basket'
});
jQuery(".basket_action_remove a").live("click", function(){
var item = (this.id)
jQuery.ajax({
type: "POST",
url: path + "ajax/basket/remove/",
data: { item: item },
success: function(msg){
jQuery("#basket_items").html(msg);
window.location.reload()
}
});
});
jQuery("#basket_items" ).sortable({
update: function(event, ui) {
var items = jQuery(this).sortable('toArray').toString();
jQuery.ajax({
type: "POST",
url: path + "ajax/basket/sort",
data: { items: items },
success: function(msg){
window.location.reload()
}
});
}
});
jQuery("#basket_items" ).disableSelection();
jQuery("#remove_timerange_session").click(function(){
jQuery.ajax({
type: "GET",
url: path + "ajax/remove/timerange",
success: function(){
location.reload();
}
});
});
jQuery("#service-filter").keyup(function () {
var sfilter = jQuery("#service-filter").val();
if(sfilter != "") {
jQuery("#service-filter").css('background-color','#ff9999');
}else{
jQuery("#service-filter").css('background-color','white');
}
jQuery.ajax({
type: "POST",
url: path + "ajax/filter/set-sfilter",
data: { sfilter: sfilter }
});
jQuery("#services span[id^='service']").each(function () {
if (jQuery(this).attr('id').search(new RegExp("service-.*" + sfilter,"i")) == 0) {
jQuery(this).show();
} else {
jQuery(this).hide();
}
});
});
jQuery("#special-filter").keyup(function () {
var spfilter = jQuery("#special-filter").val();
if(spfilter != "") {
jQuery("#special-filter").css('background-color','#ff9999');
}else{
jQuery("#special-filter").css('background-color','white');
}
jQuery.ajax({
type: "POST",
url: path + "ajax/filter/set-spfilter",
data: { spfilter: spfilter }
});
jQuery("#special-templates span[id^='special']").each(function () {
if (jQuery(this).attr('id').search(new RegExp("special-.*" + spfilter,"i")) == 0) {
jQuery(this).show();
} else {
jQuery(this).hide();
};
});
});
jQuery("#page-filter").keyup(function () {
var pfilter = jQuery("#page-filter").val();
if(pfilter != "") {
jQuery("#page-filter").css('background-color','#ff9999');
}else{
jQuery("#page-filter").css('background-color','white');
}
jQuery.ajax({
type: "POST",
url: path + "ajax/filter/set-pfilter",
data: { pfilter: pfilter }
});
jQuery("#pages span[id^='page']").each(function () {
if (jQuery(this).attr('id').search(new RegExp("page-.*" + pfilter,"i")) == 0) {
jQuery(this).show();
} else {
jQuery(this).hide();
};
});
});
});
<?php if (!empty($zoom_header)) {
echo $zoom_header;
} ?>
</script>
</head>
<body>
<?php if (!empty($graph)) {
echo $graph;
} ?>
<?php if (!empty($debug)) {
echo $debug;
} ?>
<?php if (!empty($color)) {
echo $color;
} ?>
<?php if (!empty($zoom)) {
echo $zoom;
} ?>
<?php if (!empty($page)) {
echo $page;
} ?>
<?php if (!empty($docs)) {
echo $docs;
} ?>
</body>
</html>
|
cb925073edeeb97eb4ce61a86cdafccc9b87f9bb
|
https://github.com/lingej/pnp4nagios
|
send.php
|
php
|
<?php
/*
------------------------------------------------------------------------
Barcode
Copyright (C) 2009-2016 by the Barcode plugin Development Team.
https://forge.indepnet.net/projects/barscode
------------------------------------------------------------------------
LICENSE
This file is part of barcode plugin project.
Plugin Barcode 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.
Plugin Barcode 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 Plugin Barcode. If not, see <http://www.gnu.org/licenses/>.
------------------------------------------------------------------------
@package Plugin Barcode
@author David Durieux
@co-author
@copyright Copyright (c) 2009-2016 Barcode plugin Development team
@license AGPL License 3.0 or (at your option) any later version
http://www.gnu.org/licenses/agpl-3.0-standalone.html
@link https://forge.indepnet.net/projects/barscode
@since 2009
------------------------------------------------------------------------
*/
include ('../../../inc/includes.php');
if (!defined("GLPI_PLUGIN_DOC_DIR")) {
define("GLPI_PLUGIN_DOC_DIR", GLPI_ROOT . "/files/_plugins");
}
$docDir = GLPI_PLUGIN_DOC_DIR.'/barcode';
if (isset($_GET['file'])) {
$filename = $_GET['file'];
// Security test : document in $docDir
if (strstr($filename, "../") || strstr($filename, "..\\")) {
echo "Security attack !!!";
Toolbox::logDebug("[Plugin barcode][security][sendfile] ".
$_SESSION["glpiname"]." try to get a non standard file : ".$filename);
}
$file = $docDir.'/'.$filename;
if (!file_exists($file)) {
echo "Error file $filename does not exist"; //TODO : traduire
} else {
// Now send the file with header() magic
header("Expires: Mon, 26 Nov 1962 00:00:00 GMT");
header('Pragma: private'); /// IE BUG + SSL
//header('Pragma: no-cache');
header('Cache-control: private, must-revalidate'); /// IE BUG + SSL
header("Content-disposition: filename=\"$filename\"");
header("Content-type: application/pdf");
$f=fopen($file, "r");
if (!$f) {
echo "Error opening file $filename";
} else {
$fsize=filesize($file);
if ($fsize) {
echo fread($f, filesize($file));
} else {
echo 'error';
}
}
}
}
|
<?php
/*
------------------------------------------------------------------------
Barcode
Copyright (C) 2009-2016 by the Barcode plugin Development Team.
https://forge.indepnet.net/projects/barscode
------------------------------------------------------------------------
LICENSE
This file is part of barcode plugin project.
Plugin Barcode 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.
Plugin Barcode 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 Plugin Barcode. If not, see <http://www.gnu.org/licenses/>.
------------------------------------------------------------------------
@package Plugin Barcode
@author David Durieux
@co-author
@copyright Copyright (c) 2009-2016 Barcode plugin Development team
@license AGPL License 3.0 or (at your option) any later version
http://www.gnu.org/licenses/agpl-3.0-standalone.html
@link https://forge.indepnet.net/projects/barscode
@since 2009
------------------------------------------------------------------------
*/
include ('../../../inc/includes.php');
if (!defined("GLPI_PLUGIN_DOC_DIR")) {
define("GLPI_PLUGIN_DOC_DIR", GLPI_ROOT . "/files/_plugins");
}
$docDir = GLPI_PLUGIN_DOC_DIR.'/barcode';
if (isset($_GET['file'])) {
$filename = $_GET['file'];
// Security test : document in $docDir
if (strstr($filename, "../") || strstr($filename, "..\\")) {
echo "Security attack !!!";
Toolbox::logDebug("[Plugin barcode][security][sendfile] ".
$_SESSION["glpiname"]." try to get a non standard file : ".$filename);
exit;
}
$file = $docDir.'/'.$filename;
if (!file_exists($file)) {
echo "Error file $filename does not exist"; //TODO : traduire
} else {
// Now send the file with header() magic
header("Expires: Mon, 26 Nov 1962 00:00:00 GMT");
header('Pragma: private'); /// IE BUG + SSL
//header('Pragma: no-cache');
header('Cache-control: private, must-revalidate'); /// IE BUG + SSL
header("Content-disposition: filename=\"$filename\"");
header("Content-type: application/pdf");
$f=fopen($file, "r");
if (!$f) {
echo "Error opening file $filename";
} else {
$fsize=filesize($file);
if ($fsize) {
echo fread($f, filesize($file));
} else {
echo 'error';
}
}
}
}
|
428c3d9adfb446e8492b1c2b7affb3d34072ff46
|
https://github.com/pluginsglpi/barcode
|
plugin.php
|
php
|
<?php
// +-----------------------------------------------------------------------+
// | Piwigo - a PHP based photo gallery |
// +-----------------------------------------------------------------------+
// | Copyright(C) 2008-2016 Piwigo Team http://piwigo.org |
// | Copyright(C) 2003-2008 PhpWebGallery Team http://phpwebgallery.net |
// | Copyright(C) 2002-2003 Pierrick LE GALL http://le-gall.net/pierrick |
// +-----------------------------------------------------------------------+
// | This program is free software; you can redistribute it and/or modify |
// | it under the terms of the GNU General Public License as published by |
// | the Free Software Foundation |
// | |
// | This program is distributed in the hope that it will be useful, but |
// | WITHOUT ANY WARRANTY; without even the implied warranty of |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
// | General Public License for more details. |
// | |
// | You should have received a copy of the GNU General Public License |
// | along with this program; if not, write to the Free Software |
// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
// | USA. |
// +-----------------------------------------------------------------------+
if( !defined("PHPWG_ROOT_PATH") )
{
die ("Hacking attempt!");
}
include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
check_status(ACCESS_ADMINISTRATOR);
$sections = explode('/', $_GET['section'] );
for ($i=0; $i<count($sections); $i++)
{
if (empty($sections[$i]) or $sections[$i]=='..')
{
unset($sections[$i]);
$i--;
}
}
if (count($sections)<2)
{
die('Invalid plugin URL');
}
$plugin_id = $sections[0];
if (!preg_match('/^[\w-]+$/', $plugin_id))
{
die('Invalid plugin identifier');
}
if ( !isset($pwg_loaded_plugins[$plugin_id]) )
{
die('Invalid URL - plugin '.$plugin_id.' not active');
}
$filename = PHPWG_PLUGINS_PATH.implode('/', $sections);
if (is_file($filename))
{
include_once($filename);
}
else
{
die('Missing file '.$filename);
}
?>
|
<?php
// +-----------------------------------------------------------------------+
// | Piwigo - a PHP based photo gallery |
// +-----------------------------------------------------------------------+
// | Copyright(C) 2008-2016 Piwigo Team http://piwigo.org |
// | Copyright(C) 2003-2008 PhpWebGallery Team http://phpwebgallery.net |
// | Copyright(C) 2002-2003 Pierrick LE GALL http://le-gall.net/pierrick |
// +-----------------------------------------------------------------------+
// | This program is free software; you can redistribute it and/or modify |
// | it under the terms of the GNU General Public License as published by |
// | the Free Software Foundation |
// | |
// | This program is distributed in the hope that it will be useful, but |
// | WITHOUT ANY WARRANTY; without even the implied warranty of |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
// | General Public License for more details. |
// | |
// | You should have received a copy of the GNU General Public License |
// | along with this program; if not, write to the Free Software |
// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
// | USA. |
// +-----------------------------------------------------------------------+
if( !defined("PHPWG_ROOT_PATH") )
{
die ("Hacking attempt!");
}
include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
check_status(ACCESS_ADMINISTRATOR);
$sections = explode('/', $_GET['section'] );
for ($i=0; $i<count($sections); $i++)
{
if (empty($sections[$i]) or $sections[$i]=='..')
{
unset($sections[$i]);
$i--;
}
}
if (count($sections)<2)
{
die('Invalid plugin URL');
}
$plugin_id = $sections[0];
if (!preg_match('/^[\w-]+$/', $plugin_id))
{
die('Invalid plugin identifier');
}
if ( !isset($pwg_loaded_plugins[$plugin_id]) )
{
die('Invalid URL - plugin '.$plugin_id.' not active');
}
$filename = PHPWG_PLUGINS_PATH.implode('/', $sections);
if (is_file($filename))
{
include_once($filename);
}
else
{
die('Missing file '.htmlentities($filename));
}
?>
|
7df3830c81716b959a2d0d3a0d8216b860ae0dc7
|
https://github.com/piwigo/piwigo
|
odm-init.php
|
php
|
<?php
/*
init.php - bootloader to initialize variables
* If the config.php file is not found then an error
* will be displayed asking the visitor to set up the
* config.php file.
*
* Will also search for config.php in the OpenDocMan parent
* directory to allow the OpendocMan directory to remain
* untouched.
Copyright (C) 2011 Stephen Lawrence Jr.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
/*
* Connect to Database
*/
$GLOBALS['connection'] = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die ("Unable to connect: " . mysql_error());
$db = mysql_select_db(DB_NAME, $GLOBALS['connection']);
$dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8";
try {
$pdo = new PDO($dsn, DB_USER, DB_PASS);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$GLOBALS['pdo'] = $pdo;
ob_start();
include('includes/FirePHPCore/fb.php');
/*
/*
* Load the Settings class
*/
require_once ( 'Settings_class.php');
$settings = new Settings();
$settings->load();
/*
* Common functions
*/
require_once( 'functions.php' );
/*
* Load the allowed file types list
*/
require_once ( 'FileTypes_class.php' );
$filetypes = new FileTypes_class();
$filetypes->load();
// Set the revision directory. (relative to $dataDir)
$CONFIG['revisionDir'] = $GLOBALS['CONFIG']['dataDir'] . 'revisionDir/';
// Set the revision directory. (relative to $dataDir)
$CONFIG['archiveDir'] = $GLOBALS['CONFIG']['dataDir'] . 'archiveDir/';
$_GET = sanitizeme($_GET);
$_REQUEST = sanitizeme($_REQUEST);
$_POST = sanitizeme($_POST);
$_SERVER = sanitizeme($_SERVER);
|
<?php
/*
init.php - bootloader to initialize variables
* If the config.php file is not found then an error
* will be displayed asking the visitor to set up the
* config.php file.
*
* Will also search for config.php in the OpenDocMan parent
* directory to allow the OpendocMan directory to remain
* untouched.
Copyright (C) 2011 Stephen Lawrence Jr.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
/*
* Connect to Database
*/
$GLOBALS['connection'] = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die ("Unable to connect: " . mysql_error());
$db = mysql_select_db(DB_NAME, $GLOBALS['connection']);
$dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8";
try {
$pdo = new PDO($dsn, DB_USER, DB_PASS);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$GLOBALS['pdo'] = $pdo;
ob_start();
include('includes/FirePHPCore/fb.php');
/*
/*
* Load the Settings class
*/
require_once ( 'Settings_class.php');
$settings = new Settings();
$settings->load();
/*
* Common functions
*/
require_once( 'functions.php' );
/*
* Load the allowed file types list
*/
require_once ( 'FileTypes_class.php' );
$filetypes = new FileTypes_class();
$filetypes->load();
// Set the revision directory. (relative to $dataDir)
$CONFIG['revisionDir'] = $GLOBALS['CONFIG']['dataDir'] . 'revisionDir/';
// Set the revision directory. (relative to $dataDir)
$CONFIG['archiveDir'] = $GLOBALS['CONFIG']['dataDir'] . 'archiveDir/';
$_GET = sanitizeme($_GET);
$_REQUEST = sanitizeme($_REQUEST);
$_POST = sanitizeme($_POST);
$_SERVER = sanitizeme($_SERVER);
$_FILES = sanitizeme($_FILES);
|
d202ef3def8674be61a3e4ccbe28beba4953b7ce
|
https://github.com/opendocman/opendocman
|
index.php
|
php
|
<?php
session_start();
define('NO_AUTH_REQUIRED',true);
$TAB = 'RESET PASSWORD';
if (isset($_SESSION['user'])) {
header("Location: /list/user");
}
// Main include
include($_SERVER['DOCUMENT_ROOT']."/inc/main.php");
if ((!empty($_POST['user'])) && (empty($_POST['code']))) {
$v_user = escapeshellarg($_POST['user']);
$user = $_POST['user'];
$cmd="/usr/bin/sudo /usr/local/vesta/bin/v-list-user";
exec ($cmd." ".$v_user." json", $output, $return_var);
if ( $return_var == 0 ) {
$data = json_decode(implode('', $output), true);
$rkey = $data[$user]['RKEY'];
$fname = $data[$user]['FNAME'];
$lname = $data[$user]['LNAME'];
$contact = $data[$user]['CONTACT'];
$to = $data[$user]['CONTACT'];
$subject = __('MAIL_RESET_SUBJECT',date("Y-m-d H:i:s"));
$hostname = exec('hostname');
$from = __('MAIL_FROM',$hostname);
if (!empty($fname)) {
$mailtext = __('GREETINGS_GORDON_FREEMAN',$fname,$lname);
} else {
$mailtext = __('GREETINGS');
}
$mailtext .= __('PASSWORD_RESET_REQUEST',$_SERVER['HTTP_HOST'],$user,$rkey,$_SERVER['HTTP_HOST'],$user,$rkey);
if (!empty($rkey)) send_email($to, $subject, $mailtext, $from);
unset($output);
}
header("Location: /reset/?action=code&user=".$_POST['user']);
exit;
}
if ((!empty($_POST['user'])) && (!empty($_POST['code'])) && (!empty($_POST['password'])) ) {
if ( $_POST['password'] == $_POST['password_confirm'] ) {
$v_user = escapeshellarg($_POST['user']);
$user = $_POST['user'];
$cmd="/usr/bin/sudo /usr/local/vesta/bin/v-list-user";
exec ($cmd." ".$v_user." json", $output, $return_var);
if ( $return_var == 0 ) {
$data = json_decode(implode('', $output), true);
$rkey = $data[$user]['RKEY'];
if (hash_equals($rkey, $_POST['code'])) {
$v_password = tempnam("/tmp","vst");
$fp = fopen($v_password, "w");
fwrite($fp, $_POST['password']."\n");
fclose($fp);
$cmd="/usr/bin/sudo /usr/local/vesta/bin/v-change-user-password";
exec ($cmd." ".$v_user." ".$v_password, $output, $return_var);
unlink($v_password);
if ( $return_var > 0 ) {
$ERROR = "<a class=\"error\">".__('An internal error occurred')."</a>";
} else {
$_SESSION['user'] = $_POST['user'];
header("Location: /");
exit;
}
} else {
$ERROR = "<a class=\"error\">".__('Invalid username or code')."</a>";
}
} else {
$ERROR = "<a class=\"error\">".__('Invalid username or code')."</a>";
}
} else {
$ERROR = "<a class=\"error\">".__('Passwords not match')."</a>";
}
}
// Detect language
if (empty($_SESSION['language'])) $_SESSION['language'] = detect_user_language();
if (empty($_GET['action'])) {
require_once '../templates/header.html';
require_once '../templates/reset_1.html';
} else {
require_once '../templates/header.html';
if ($_GET['action'] == 'code' ) {
require_once '../templates/reset_2.html';
}
if (($_GET['action'] == 'confirm' ) && (!empty($_GET['code']))) {
require_once '../templates/reset_3.html';
}
}
?>
|
<?php
session_start();
define('NO_AUTH_REQUIRED',true);
$TAB = 'RESET PASSWORD';
if (isset($_SESSION['user'])) {
header("Location: /list/user");
}
// Main include
include($_SERVER['DOCUMENT_ROOT']."/inc/main.php");
if ((!empty($_POST['user'])) && (empty($_POST['code']))) {
$v_user = escapeshellarg($_POST['user']);
$user = $_POST['user'];
$cmd="/usr/bin/sudo /usr/local/vesta/bin/v-list-user";
exec ($cmd." ".$v_user." json", $output, $return_var);
if ( $return_var == 0 ) {
$data = json_decode(implode('', $output), true);
$rkey = $data[$user]['RKEY'];
$fname = $data[$user]['FNAME'];
$lname = $data[$user]['LNAME'];
$contact = $data[$user]['CONTACT'];
$to = $data[$user]['CONTACT'];
$subject = __('MAIL_RESET_SUBJECT',date("Y-m-d H:i:s"));
$hostname = exec('hostname');
$from = __('MAIL_FROM',$hostname);
if (!empty($fname)) {
$mailtext = __('GREETINGS_GORDON_FREEMAN',$fname,$lname);
} else {
$mailtext = __('GREETINGS');
}
$mailtext .= __('PASSWORD_RESET_REQUEST',$hostname,$user,$rkey,$hostname,$user,$rkey);
if (!empty($rkey)) send_email($to, $subject, $mailtext, $from);
unset($output);
}
header("Location: /reset/?action=code&user=".$_POST['user']);
exit;
}
if ((!empty($_POST['user'])) && (!empty($_POST['code'])) && (!empty($_POST['password'])) ) {
if ( $_POST['password'] == $_POST['password_confirm'] ) {
$v_user = escapeshellarg($_POST['user']);
$user = $_POST['user'];
$cmd="/usr/bin/sudo /usr/local/vesta/bin/v-list-user";
exec ($cmd." ".$v_user." json", $output, $return_var);
if ( $return_var == 0 ) {
$data = json_decode(implode('', $output), true);
$rkey = $data[$user]['RKEY'];
if (hash_equals($rkey, $_POST['code'])) {
$v_password = tempnam("/tmp","vst");
$fp = fopen($v_password, "w");
fwrite($fp, $_POST['password']."\n");
fclose($fp);
$cmd="/usr/bin/sudo /usr/local/vesta/bin/v-change-user-password";
exec ($cmd." ".$v_user." ".$v_password, $output, $return_var);
unlink($v_password);
if ( $return_var > 0 ) {
$ERROR = "<a class=\"error\">".__('An internal error occurred')."</a>";
} else {
$_SESSION['user'] = $_POST['user'];
header("Location: /");
exit;
}
} else {
$ERROR = "<a class=\"error\">".__('Invalid username or code')."</a>";
}
} else {
$ERROR = "<a class=\"error\">".__('Invalid username or code')."</a>";
}
} else {
$ERROR = "<a class=\"error\">".__('Passwords not match')."</a>";
}
}
// Detect language
if (empty($_SESSION['language'])) $_SESSION['language'] = detect_user_language();
if (empty($_GET['action'])) {
require_once '../templates/header.html';
require_once '../templates/reset_1.html';
} else {
require_once '../templates/header.html';
if ($_GET['action'] == 'code' ) {
require_once '../templates/reset_2.html';
}
if (($_GET['action'] == 'confirm' ) && (!empty($_GET['code']))) {
require_once '../templates/reset_3.html';
}
}
?>
|
c3c4de43d6701560f604ca7996f717b08e3d7d1d
|
https://github.com/serghey-rodin/vesta
|
ssl.h
|
objective-c
|
/* ssl/ssl.h */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
* Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/* ====================================================================
* Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
* ECC cipher suite support in OpenSSL originally developed by
* SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
*/
/* ====================================================================
* Copyright 2005 Nokia. All rights reserved.
*
* The portions of the attached software ("Contribution") is developed by
* Nokia Corporation and is licensed pursuant to the OpenSSL open source
* license.
*
* The Contribution, originally written by Mika Kousa and Pasi Eronen of
* Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
* support (see RFC 4279) to OpenSSL.
*
* No patent licenses or other rights except those expressly stated in
* the OpenSSL open source license shall be deemed granted or received
* expressly, by implication, estoppel, or otherwise.
*
* No assurances are provided by Nokia that the Contribution does not
* infringe the patent or other intellectual property rights of any third
* party or that the license provides you with all the necessary rights
* to make use of the Contribution.
*
* THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
* ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
* SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
* OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
* OTHERWISE.
*/
#ifndef HEADER_SSL_H
# define HEADER_SSL_H
# include <openssl/e_os2.h>
# ifndef OPENSSL_NO_COMP
# include <openssl/comp.h>
# endif
# ifndef OPENSSL_NO_BIO
# include <openssl/bio.h>
# endif
# ifndef OPENSSL_NO_DEPRECATED
# ifndef OPENSSL_NO_X509
# include <openssl/x509.h>
# endif
# include <openssl/crypto.h>
# include <openssl/lhash.h>
# include <openssl/buffer.h>
# endif
# include <openssl/pem.h>
# include <openssl/hmac.h>
# include <openssl/kssl.h>
# include <openssl/safestack.h>
# include <openssl/symhacks.h>
#ifdef __cplusplus
extern "C" {
#endif
/* SSLeay version number for ASN.1 encoding of the session information */
/*-
* Version 0 - initial version
* Version 1 - added the optional peer certificate
*/
# define SSL_SESSION_ASN1_VERSION 0x0001
/* text strings for the ciphers */
# define SSL_TXT_NULL_WITH_MD5 SSL2_TXT_NULL_WITH_MD5
# define SSL_TXT_RC4_128_WITH_MD5 SSL2_TXT_RC4_128_WITH_MD5
# define SSL_TXT_RC4_128_EXPORT40_WITH_MD5 SSL2_TXT_RC4_128_EXPORT40_WITH_MD5
# define SSL_TXT_RC2_128_CBC_WITH_MD5 SSL2_TXT_RC2_128_CBC_WITH_MD5
# define SSL_TXT_RC2_128_CBC_EXPORT40_WITH_MD5 SSL2_TXT_RC2_128_CBC_EXPORT40_WITH_MD5
# define SSL_TXT_IDEA_128_CBC_WITH_MD5 SSL2_TXT_IDEA_128_CBC_WITH_MD5
# define SSL_TXT_DES_64_CBC_WITH_MD5 SSL2_TXT_DES_64_CBC_WITH_MD5
# define SSL_TXT_DES_64_CBC_WITH_SHA SSL2_TXT_DES_64_CBC_WITH_SHA
# define SSL_TXT_DES_192_EDE3_CBC_WITH_MD5 SSL2_TXT_DES_192_EDE3_CBC_WITH_MD5
# define SSL_TXT_DES_192_EDE3_CBC_WITH_SHA SSL2_TXT_DES_192_EDE3_CBC_WITH_SHA
/*
* VRS Additional Kerberos5 entries
*/
# define SSL_TXT_KRB5_DES_64_CBC_SHA SSL3_TXT_KRB5_DES_64_CBC_SHA
# define SSL_TXT_KRB5_DES_192_CBC3_SHA SSL3_TXT_KRB5_DES_192_CBC3_SHA
# define SSL_TXT_KRB5_RC4_128_SHA SSL3_TXT_KRB5_RC4_128_SHA
# define SSL_TXT_KRB5_IDEA_128_CBC_SHA SSL3_TXT_KRB5_IDEA_128_CBC_SHA
# define SSL_TXT_KRB5_DES_64_CBC_MD5 SSL3_TXT_KRB5_DES_64_CBC_MD5
# define SSL_TXT_KRB5_DES_192_CBC3_MD5 SSL3_TXT_KRB5_DES_192_CBC3_MD5
# define SSL_TXT_KRB5_RC4_128_MD5 SSL3_TXT_KRB5_RC4_128_MD5
# define SSL_TXT_KRB5_IDEA_128_CBC_MD5 SSL3_TXT_KRB5_IDEA_128_CBC_MD5
# define SSL_TXT_KRB5_DES_40_CBC_SHA SSL3_TXT_KRB5_DES_40_CBC_SHA
# define SSL_TXT_KRB5_RC2_40_CBC_SHA SSL3_TXT_KRB5_RC2_40_CBC_SHA
# define SSL_TXT_KRB5_RC4_40_SHA SSL3_TXT_KRB5_RC4_40_SHA
# define SSL_TXT_KRB5_DES_40_CBC_MD5 SSL3_TXT_KRB5_DES_40_CBC_MD5
# define SSL_TXT_KRB5_RC2_40_CBC_MD5 SSL3_TXT_KRB5_RC2_40_CBC_MD5
# define SSL_TXT_KRB5_RC4_40_MD5 SSL3_TXT_KRB5_RC4_40_MD5
# define SSL_TXT_KRB5_DES_40_CBC_SHA SSL3_TXT_KRB5_DES_40_CBC_SHA
# define SSL_TXT_KRB5_DES_40_CBC_MD5 SSL3_TXT_KRB5_DES_40_CBC_MD5
# define SSL_TXT_KRB5_DES_64_CBC_SHA SSL3_TXT_KRB5_DES_64_CBC_SHA
# define SSL_TXT_KRB5_DES_64_CBC_MD5 SSL3_TXT_KRB5_DES_64_CBC_MD5
# define SSL_TXT_KRB5_DES_192_CBC3_SHA SSL3_TXT_KRB5_DES_192_CBC3_SHA
# define SSL_TXT_KRB5_DES_192_CBC3_MD5 SSL3_TXT_KRB5_DES_192_CBC3_MD5
# define SSL_MAX_KRB5_PRINCIPAL_LENGTH 256
# define SSL_MAX_SSL_SESSION_ID_LENGTH 32
# define SSL_MAX_SID_CTX_LENGTH 32
# define SSL_MIN_RSA_MODULUS_LENGTH_IN_BYTES (512/8)
# define SSL_MAX_KEY_ARG_LENGTH 8
# define SSL_MAX_MASTER_KEY_LENGTH 48
/* These are used to specify which ciphers to use and not to use */
# define SSL_TXT_EXP40 "EXPORT40"
# define SSL_TXT_EXP56 "EXPORT56"
# define SSL_TXT_LOW "LOW"
# define SSL_TXT_MEDIUM "MEDIUM"
# define SSL_TXT_HIGH "HIGH"
# define SSL_TXT_FIPS "FIPS"
# define SSL_TXT_kFZA "kFZA"/* unused! */
# define SSL_TXT_aFZA "aFZA"/* unused! */
# define SSL_TXT_eFZA "eFZA"/* unused! */
# define SSL_TXT_FZA "FZA"/* unused! */
# define SSL_TXT_aNULL "aNULL"
# define SSL_TXT_eNULL "eNULL"
# define SSL_TXT_NULL "NULL"
# define SSL_TXT_kRSA "kRSA"
# define SSL_TXT_kDHr "kDHr"
# define SSL_TXT_kDHd "kDHd"
# define SSL_TXT_kDH "kDH"
# define SSL_TXT_kEDH "kEDH"
# define SSL_TXT_kDHE "kDHE"/* alias for kEDH */
# define SSL_TXT_kKRB5 "kKRB5"
# define SSL_TXT_kECDHr "kECDHr"
# define SSL_TXT_kECDHe "kECDHe"
# define SSL_TXT_kECDH "kECDH"
# define SSL_TXT_kEECDH "kEECDH"
# define SSL_TXT_kECDHE "kECDHE"/* alias for kEECDH */
# define SSL_TXT_kPSK "kPSK"
# define SSL_TXT_kGOST "kGOST"
# define SSL_TXT_kSRP "kSRP"
# define SSL_TXT_aRSA "aRSA"
# define SSL_TXT_aDSS "aDSS"
# define SSL_TXT_aDH "aDH"
# define SSL_TXT_aECDH "aECDH"
# define SSL_TXT_aKRB5 "aKRB5"
# define SSL_TXT_aECDSA "aECDSA"
# define SSL_TXT_aPSK "aPSK"
# define SSL_TXT_aGOST94 "aGOST94"
# define SSL_TXT_aGOST01 "aGOST01"
# define SSL_TXT_aGOST "aGOST"
# define SSL_TXT_aSRP "aSRP"
# define SSL_TXT_DSS "DSS"
# define SSL_TXT_DH "DH"
# define SSL_TXT_EDH "EDH"/* same as "kEDH:-ADH" */
# define SSL_TXT_DHE "DHE"/* alias for EDH */
# define SSL_TXT_ADH "ADH"
# define SSL_TXT_RSA "RSA"
# define SSL_TXT_ECDH "ECDH"
# define SSL_TXT_EECDH "EECDH"/* same as "kEECDH:-AECDH" */
# define SSL_TXT_ECDHE "ECDHE"/* alias for ECDHE" */
# define SSL_TXT_AECDH "AECDH"
# define SSL_TXT_ECDSA "ECDSA"
# define SSL_TXT_KRB5 "KRB5"
# define SSL_TXT_PSK "PSK"
# define SSL_TXT_SRP "SRP"
# define SSL_TXT_DES "DES"
# define SSL_TXT_3DES "3DES"
# define SSL_TXT_RC4 "RC4"
# define SSL_TXT_RC2 "RC2"
# define SSL_TXT_IDEA "IDEA"
# define SSL_TXT_SEED "SEED"
# define SSL_TXT_AES128 "AES128"
# define SSL_TXT_AES256 "AES256"
# define SSL_TXT_AES "AES"
# define SSL_TXT_AES_GCM "AESGCM"
# define SSL_TXT_CAMELLIA128 "CAMELLIA128"
# define SSL_TXT_CAMELLIA256 "CAMELLIA256"
# define SSL_TXT_CAMELLIA "CAMELLIA"
# define SSL_TXT_MD5 "MD5"
# define SSL_TXT_SHA1 "SHA1"
# define SSL_TXT_SHA "SHA"/* same as "SHA1" */
# define SSL_TXT_GOST94 "GOST94"
# define SSL_TXT_GOST89MAC "GOST89MAC"
# define SSL_TXT_SHA256 "SHA256"
# define SSL_TXT_SHA384 "SHA384"
# define SSL_TXT_SSLV2 "SSLv2"
# define SSL_TXT_SSLV3 "SSLv3"
# define SSL_TXT_TLSV1 "TLSv1"
# define SSL_TXT_TLSV1_1 "TLSv1.1"
# define SSL_TXT_TLSV1_2 "TLSv1.2"
# define SSL_TXT_EXP "EXP"
# define SSL_TXT_EXPORT "EXPORT"
# define SSL_TXT_ALL "ALL"
/*-
* COMPLEMENTOF* definitions. These identifiers are used to (de-select)
* ciphers normally not being used.
* Example: "RC4" will activate all ciphers using RC4 including ciphers
* without authentication, which would normally disabled by DEFAULT (due
* the "!ADH" being part of default). Therefore "RC4:!COMPLEMENTOFDEFAULT"
* will make sure that it is also disabled in the specific selection.
* COMPLEMENTOF* identifiers are portable between version, as adjustments
* to the default cipher setup will also be included here.
*
* COMPLEMENTOFDEFAULT does not experience the same special treatment that
* DEFAULT gets, as only selection is being done and no sorting as needed
* for DEFAULT.
*/
# define SSL_TXT_CMPALL "COMPLEMENTOFALL"
# define SSL_TXT_CMPDEF "COMPLEMENTOFDEFAULT"
/*
* The following cipher list is used by default. It also is substituted when
* an application-defined cipher list string starts with 'DEFAULT'.
*/
# define SSL_DEFAULT_CIPHER_LIST "ALL:!EXPORT:!LOW:!aNULL:!eNULL:!SSLv2"
/*
* As of OpenSSL 1.0.0, ssl_create_cipher_list() in ssl/ssl_ciph.c always
* starts with a reasonable order, and all we have to do for DEFAULT is
* throwing out anonymous and unencrypted ciphersuites! (The latter are not
* actually enabled by ALL, but "ALL:RSA" would enable some of them.)
*/
/* Used in SSL_set_shutdown()/SSL_get_shutdown(); */
# define SSL_SENT_SHUTDOWN 1
# define SSL_RECEIVED_SHUTDOWN 2
#ifdef __cplusplus
}
#endif
#ifdef __cplusplus
extern "C" {
#endif
# if (defined(OPENSSL_NO_RSA) || defined(OPENSSL_NO_MD5)) && !defined(OPENSSL_NO_SSL2)
# define OPENSSL_NO_SSL2
# endif
# define SSL_FILETYPE_ASN1 X509_FILETYPE_ASN1
# define SSL_FILETYPE_PEM X509_FILETYPE_PEM
/*
* This is needed to stop compilers complaining about the 'struct ssl_st *'
* function parameters used to prototype callbacks in SSL_CTX.
*/
typedef struct ssl_st *ssl_crock_st;
typedef struct tls_session_ticket_ext_st TLS_SESSION_TICKET_EXT;
typedef struct ssl_method_st SSL_METHOD;
typedef struct ssl_cipher_st SSL_CIPHER;
typedef struct ssl_session_st SSL_SESSION;
typedef struct tls_sigalgs_st TLS_SIGALGS;
typedef struct ssl_conf_ctx_st SSL_CONF_CTX;
DECLARE_STACK_OF(SSL_CIPHER)
/* SRTP protection profiles for use with the use_srtp extension (RFC 5764)*/
typedef struct srtp_protection_profile_st {
const char *name;
unsigned long id;
} SRTP_PROTECTION_PROFILE;
DECLARE_STACK_OF(SRTP_PROTECTION_PROFILE)
typedef int (*tls_session_ticket_ext_cb_fn) (SSL *s,
const unsigned char *data,
int len, void *arg);
typedef int (*tls_session_secret_cb_fn) (SSL *s, void *secret,
int *secret_len,
STACK_OF(SSL_CIPHER) *peer_ciphers,
SSL_CIPHER **cipher, void *arg);
# ifndef OPENSSL_NO_TLSEXT
/* Typedefs for handling custom extensions */
typedef int (*custom_ext_add_cb) (SSL *s, unsigned int ext_type,
const unsigned char **out,
size_t *outlen, int *al, void *add_arg);
typedef void (*custom_ext_free_cb) (SSL *s, unsigned int ext_type,
const unsigned char *out, void *add_arg);
typedef int (*custom_ext_parse_cb) (SSL *s, unsigned int ext_type,
const unsigned char *in,
size_t inlen, int *al, void *parse_arg);
# endif
# ifndef OPENSSL_NO_SSL_INTERN
/* used to hold info on the particular ciphers used */
struct ssl_cipher_st {
int valid;
const char *name; /* text name */
unsigned long id; /* id, 4 bytes, first is version */
/*
* changed in 0.9.9: these four used to be portions of a single value
* 'algorithms'
*/
unsigned long algorithm_mkey; /* key exchange algorithm */
unsigned long algorithm_auth; /* server authentication */
unsigned long algorithm_enc; /* symmetric encryption */
unsigned long algorithm_mac; /* symmetric authentication */
unsigned long algorithm_ssl; /* (major) protocol version */
unsigned long algo_strength; /* strength and export flags */
unsigned long algorithm2; /* Extra flags */
int strength_bits; /* Number of bits really used */
int alg_bits; /* Number of bits for algorithm */
};
/* Used to hold functions for SSLv2 or SSLv3/TLSv1 functions */
struct ssl_method_st {
int version;
int (*ssl_new) (SSL *s);
void (*ssl_clear) (SSL *s);
void (*ssl_free) (SSL *s);
int (*ssl_accept) (SSL *s);
int (*ssl_connect) (SSL *s);
int (*ssl_read) (SSL *s, void *buf, int len);
int (*ssl_peek) (SSL *s, void *buf, int len);
int (*ssl_write) (SSL *s, const void *buf, int len);
int (*ssl_shutdown) (SSL *s);
int (*ssl_renegotiate) (SSL *s);
int (*ssl_renegotiate_check) (SSL *s);
long (*ssl_get_message) (SSL *s, int st1, int stn, int mt, long
max, int *ok);
int (*ssl_read_bytes) (SSL *s, int type, unsigned char *buf, int len,
int peek);
int (*ssl_write_bytes) (SSL *s, int type, const void *buf_, int len);
int (*ssl_dispatch_alert) (SSL *s);
long (*ssl_ctrl) (SSL *s, int cmd, long larg, void *parg);
long (*ssl_ctx_ctrl) (SSL_CTX *ctx, int cmd, long larg, void *parg);
const SSL_CIPHER *(*get_cipher_by_char) (const unsigned char *ptr);
int (*put_cipher_by_char) (const SSL_CIPHER *cipher, unsigned char *ptr);
int (*ssl_pending) (const SSL *s);
int (*num_ciphers) (void);
const SSL_CIPHER *(*get_cipher) (unsigned ncipher);
const struct ssl_method_st *(*get_ssl_method) (int version);
long (*get_timeout) (void);
struct ssl3_enc_method *ssl3_enc; /* Extra SSLv3/TLS stuff */
int (*ssl_version) (void);
long (*ssl_callback_ctrl) (SSL *s, int cb_id, void (*fp) (void));
long (*ssl_ctx_callback_ctrl) (SSL_CTX *s, int cb_id, void (*fp) (void));
};
/*-
* Lets make this into an ASN.1 type structure as follows
* SSL_SESSION_ID ::= SEQUENCE {
* version INTEGER, -- structure version number
* SSLversion INTEGER, -- SSL version number
* Cipher OCTET STRING, -- the 3 byte cipher ID
* Session_ID OCTET STRING, -- the Session ID
* Master_key OCTET STRING, -- the master key
* KRB5_principal OCTET STRING -- optional Kerberos principal
* Key_Arg [ 0 ] IMPLICIT OCTET STRING, -- the optional Key argument
* Time [ 1 ] EXPLICIT INTEGER, -- optional Start Time
* Timeout [ 2 ] EXPLICIT INTEGER, -- optional Timeout ins seconds
* Peer [ 3 ] EXPLICIT X509, -- optional Peer Certificate
* Session_ID_context [ 4 ] EXPLICIT OCTET STRING, -- the Session ID context
* Verify_result [ 5 ] EXPLICIT INTEGER, -- X509_V_... code for `Peer'
* HostName [ 6 ] EXPLICIT OCTET STRING, -- optional HostName from servername TLS extension
* PSK_identity_hint [ 7 ] EXPLICIT OCTET STRING, -- optional PSK identity hint
* PSK_identity [ 8 ] EXPLICIT OCTET STRING, -- optional PSK identity
* Ticket_lifetime_hint [9] EXPLICIT INTEGER, -- server's lifetime hint for session ticket
* Ticket [10] EXPLICIT OCTET STRING, -- session ticket (clients only)
* Compression_meth [11] EXPLICIT OCTET STRING, -- optional compression method
* SRP_username [ 12 ] EXPLICIT OCTET STRING -- optional SRP username
* }
* Look in ssl/ssl_asn1.c for more details
* I'm using EXPLICIT tags so I can read the damn things using asn1parse :-).
*/
struct ssl_session_st {
int ssl_version; /* what ssl version session info is being
* kept in here? */
/* only really used in SSLv2 */
unsigned int key_arg_length;
unsigned char key_arg[SSL_MAX_KEY_ARG_LENGTH];
int master_key_length;
unsigned char master_key[SSL_MAX_MASTER_KEY_LENGTH];
/* session_id - valid? */
unsigned int session_id_length;
unsigned char session_id[SSL_MAX_SSL_SESSION_ID_LENGTH];
/*
* this is used to determine whether the session is being reused in the
* appropriate context. It is up to the application to set this, via
* SSL_new
*/
unsigned int sid_ctx_length;
unsigned char sid_ctx[SSL_MAX_SID_CTX_LENGTH];
# ifndef OPENSSL_NO_KRB5
unsigned int krb5_client_princ_len;
unsigned char krb5_client_princ[SSL_MAX_KRB5_PRINCIPAL_LENGTH];
# endif /* OPENSSL_NO_KRB5 */
# ifndef OPENSSL_NO_PSK
char *psk_identity_hint;
char *psk_identity;
# endif
/*
* Used to indicate that session resumption is not allowed. Applications
* can also set this bit for a new session via not_resumable_session_cb
* to disable session caching and tickets.
*/
int not_resumable;
/* The cert is the certificate used to establish this connection */
struct sess_cert_st /* SESS_CERT */ *sess_cert;
/*
* This is the cert for the other end. On clients, it will be the same as
* sess_cert->peer_key->x509 (the latter is not enough as sess_cert is
* not retained in the external representation of sessions, see
* ssl_asn1.c).
*/
X509 *peer;
/*
* when app_verify_callback accepts a session where the peer's
* certificate is not ok, we must remember the error for session reuse:
*/
long verify_result; /* only for servers */
int references;
long timeout;
long time;
unsigned int compress_meth; /* Need to lookup the method */
const SSL_CIPHER *cipher;
unsigned long cipher_id; /* when ASN.1 loaded, this needs to be used
* to load the 'cipher' structure */
STACK_OF(SSL_CIPHER) *ciphers; /* shared ciphers? */
CRYPTO_EX_DATA ex_data; /* application specific data */
/*
* These are used to make removal of session-ids more efficient and to
* implement a maximum cache size.
*/
struct ssl_session_st *prev, *next;
# ifndef OPENSSL_NO_TLSEXT
char *tlsext_hostname;
# ifndef OPENSSL_NO_EC
size_t tlsext_ecpointformatlist_length;
unsigned char *tlsext_ecpointformatlist; /* peer's list */
size_t tlsext_ellipticcurvelist_length;
unsigned char *tlsext_ellipticcurvelist; /* peer's list */
# endif /* OPENSSL_NO_EC */
/* RFC4507 info */
unsigned char *tlsext_tick; /* Session ticket */
size_t tlsext_ticklen; /* Session ticket length */
long tlsext_tick_lifetime_hint; /* Session lifetime hint in seconds */
# endif
# ifndef OPENSSL_NO_SRP
char *srp_username;
# endif
};
# endif
# define SSL_OP_MICROSOFT_SESS_ID_BUG 0x00000001L
# define SSL_OP_NETSCAPE_CHALLENGE_BUG 0x00000002L
/* Allow initial connection to servers that don't support RI */
# define SSL_OP_LEGACY_SERVER_CONNECT 0x00000004L
# define SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG 0x00000008L
# define SSL_OP_TLSEXT_PADDING 0x00000010L
# define SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER 0x00000020L
# define SSL_OP_SAFARI_ECDHE_ECDSA_BUG 0x00000040L
# define SSL_OP_SSLEAY_080_CLIENT_DH_BUG 0x00000080L
# define SSL_OP_TLS_D5_BUG 0x00000100L
# define SSL_OP_TLS_BLOCK_PADDING_BUG 0x00000200L
/* Hasn't done anything since OpenSSL 0.9.7h, retained for compatibility */
# define SSL_OP_MSIE_SSLV2_RSA_PADDING 0x0
/* Refers to ancient SSLREF and SSLv2, retained for compatibility */
# define SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG 0x0
/*
* Disable SSL 3.0/TLS 1.0 CBC vulnerability workaround that was added in
* OpenSSL 0.9.6d. Usually (depending on the application protocol) the
* workaround is not needed. Unfortunately some broken SSL/TLS
* implementations cannot handle it at all, which is why we include it in
* SSL_OP_ALL.
*/
/* added in 0.9.6e */
# define SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS 0x00000800L
/*
* SSL_OP_ALL: various bug workarounds that should be rather harmless. This
* used to be 0x000FFFFFL before 0.9.7.
*/
# define SSL_OP_ALL 0x80000BFFL
/* DTLS options */
# define SSL_OP_NO_QUERY_MTU 0x00001000L
/* Turn on Cookie Exchange (on relevant for servers) */
# define SSL_OP_COOKIE_EXCHANGE 0x00002000L
/* Don't use RFC4507 ticket extension */
# define SSL_OP_NO_TICKET 0x00004000L
/* Use Cisco's "speshul" version of DTLS_BAD_VER (as client) */
# define SSL_OP_CISCO_ANYCONNECT 0x00008000L
/* As server, disallow session resumption on renegotiation */
# define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION 0x00010000L
/* Don't use compression even if supported */
# define SSL_OP_NO_COMPRESSION 0x00020000L
/* Permit unsafe legacy renegotiation */
# define SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x00040000L
/* If set, always create a new key when using tmp_ecdh parameters */
# define SSL_OP_SINGLE_ECDH_USE 0x00080000L
/* Does nothing: retained for compatibility */
# define SSL_OP_SINGLE_DH_USE 0x00100000L
/* Does nothing: retained for compatibiity */
# define SSL_OP_EPHEMERAL_RSA 0x0
/*
* Set on servers to choose the cipher according to the server's preferences
*/
# define SSL_OP_CIPHER_SERVER_PREFERENCE 0x00400000L
/*
* If set, a server will allow a client to issue a SSLv3.0 version number as
* latest version supported in the premaster secret, even when TLSv1.0
* (version 3.1) was announced in the client hello. Normally this is
* forbidden to prevent version rollback attacks.
*/
# define SSL_OP_TLS_ROLLBACK_BUG 0x00800000L
# define SSL_OP_NO_SSLv2 0x01000000L
# define SSL_OP_NO_SSLv3 0x02000000L
# define SSL_OP_NO_TLSv1 0x04000000L
# define SSL_OP_NO_TLSv1_2 0x08000000L
# define SSL_OP_NO_TLSv1_1 0x10000000L
# define SSL_OP_NO_DTLSv1 0x04000000L
# define SSL_OP_NO_DTLSv1_2 0x08000000L
# define SSL_OP_NO_SSL_MASK (SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3|\
SSL_OP_NO_TLSv1|SSL_OP_NO_TLSv1_1|SSL_OP_NO_TLSv1_2)
/*
* These next two were never actually used for anything since SSLeay zap so
* we have some more flags.
*/
/*
* The next flag deliberately changes the ciphertest, this is a check for the
* PKCS#1 attack
*/
# define SSL_OP_PKCS1_CHECK_1 0x0
# define SSL_OP_PKCS1_CHECK_2 0x0
# define SSL_OP_NETSCAPE_CA_DN_BUG 0x20000000L
# define SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG 0x40000000L
/*
* Make server add server-hello extension from early version of cryptopro
* draft, when GOST ciphersuite is negotiated. Required for interoperability
* with CryptoPro CSP 3.x
*/
# define SSL_OP_CRYPTOPRO_TLSEXT_BUG 0x80000000L
/*
* Allow SSL_write(..., n) to return r with 0 < r < n (i.e. report success
* when just a single record has been written):
*/
# define SSL_MODE_ENABLE_PARTIAL_WRITE 0x00000001L
/*
* Make it possible to retry SSL_write() with changed buffer location (buffer
* contents must stay the same!); this is not the default to avoid the
* misconception that non-blocking SSL_write() behaves like non-blocking
* write():
*/
# define SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER 0x00000002L
/*
* Never bother the application with retries if the transport is blocking:
*/
# define SSL_MODE_AUTO_RETRY 0x00000004L
/* Don't attempt to automatically build certificate chain */
# define SSL_MODE_NO_AUTO_CHAIN 0x00000008L
/*
* Save RAM by releasing read and write buffers when they're empty. (SSL3 and
* TLS only.) "Released" buffers are put onto a free-list in the context or
* just freed (depending on the context's setting for freelist_max_len).
*/
# define SSL_MODE_RELEASE_BUFFERS 0x00000010L
/*
* Send the current time in the Random fields of the ClientHello and
* ServerHello records for compatibility with hypothetical implementations
* that require it.
*/
# define SSL_MODE_SEND_CLIENTHELLO_TIME 0x00000020L
# define SSL_MODE_SEND_SERVERHELLO_TIME 0x00000040L
/*
* Send TLS_FALLBACK_SCSV in the ClientHello. To be set only by applications
* that reconnect with a downgraded protocol version; see
* draft-ietf-tls-downgrade-scsv-00 for details. DO NOT ENABLE THIS if your
* application attempts a normal handshake. Only use this in explicit
* fallback retries, following the guidance in
* draft-ietf-tls-downgrade-scsv-00.
*/
# define SSL_MODE_SEND_FALLBACK_SCSV 0x00000080L
/* Cert related flags */
/*
* Many implementations ignore some aspects of the TLS standards such as
* enforcing certifcate chain algorithms. When this is set we enforce them.
*/
# define SSL_CERT_FLAG_TLS_STRICT 0x00000001L
/* Suite B modes, takes same values as certificate verify flags */
# define SSL_CERT_FLAG_SUITEB_128_LOS_ONLY 0x10000
/* Suite B 192 bit only mode */
# define SSL_CERT_FLAG_SUITEB_192_LOS 0x20000
/* Suite B 128 bit mode allowing 192 bit algorithms */
# define SSL_CERT_FLAG_SUITEB_128_LOS 0x30000
/* Perform all sorts of protocol violations for testing purposes */
# define SSL_CERT_FLAG_BROKEN_PROTOCOL 0x10000000
/* Flags for building certificate chains */
/* Treat any existing certificates as untrusted CAs */
# define SSL_BUILD_CHAIN_FLAG_UNTRUSTED 0x1
/* Don't include root CA in chain */
# define SSL_BUILD_CHAIN_FLAG_NO_ROOT 0x2
/* Just check certificates already there */
# define SSL_BUILD_CHAIN_FLAG_CHECK 0x4
/* Ignore verification errors */
# define SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR 0x8
/* Clear verification errors from queue */
# define SSL_BUILD_CHAIN_FLAG_CLEAR_ERROR 0x10
/* Flags returned by SSL_check_chain */
/* Certificate can be used with this session */
# define CERT_PKEY_VALID 0x1
/* Certificate can also be used for signing */
# define CERT_PKEY_SIGN 0x2
/* EE certificate signing algorithm OK */
# define CERT_PKEY_EE_SIGNATURE 0x10
/* CA signature algorithms OK */
# define CERT_PKEY_CA_SIGNATURE 0x20
/* EE certificate parameters OK */
# define CERT_PKEY_EE_PARAM 0x40
/* CA certificate parameters OK */
# define CERT_PKEY_CA_PARAM 0x80
/* Signing explicitly allowed as opposed to SHA1 fallback */
# define CERT_PKEY_EXPLICIT_SIGN 0x100
/* Client CA issuer names match (always set for server cert) */
# define CERT_PKEY_ISSUER_NAME 0x200
/* Cert type matches client types (always set for server cert) */
# define CERT_PKEY_CERT_TYPE 0x400
/* Cert chain suitable to Suite B */
# define CERT_PKEY_SUITEB 0x800
# define SSL_CONF_FLAG_CMDLINE 0x1
# define SSL_CONF_FLAG_FILE 0x2
# define SSL_CONF_FLAG_CLIENT 0x4
# define SSL_CONF_FLAG_SERVER 0x8
# define SSL_CONF_FLAG_SHOW_ERRORS 0x10
# define SSL_CONF_FLAG_CERTIFICATE 0x20
/* Configuration value types */
# define SSL_CONF_TYPE_UNKNOWN 0x0
# define SSL_CONF_TYPE_STRING 0x1
# define SSL_CONF_TYPE_FILE 0x2
# define SSL_CONF_TYPE_DIR 0x3
/*
* Note: SSL[_CTX]_set_{options,mode} use |= op on the previous value, they
* cannot be used to clear bits.
*/
# define SSL_CTX_set_options(ctx,op) \
SSL_CTX_ctrl((ctx),SSL_CTRL_OPTIONS,(op),NULL)
# define SSL_CTX_clear_options(ctx,op) \
SSL_CTX_ctrl((ctx),SSL_CTRL_CLEAR_OPTIONS,(op),NULL)
# define SSL_CTX_get_options(ctx) \
SSL_CTX_ctrl((ctx),SSL_CTRL_OPTIONS,0,NULL)
# define SSL_set_options(ssl,op) \
SSL_ctrl((ssl),SSL_CTRL_OPTIONS,(op),NULL)
# define SSL_clear_options(ssl,op) \
SSL_ctrl((ssl),SSL_CTRL_CLEAR_OPTIONS,(op),NULL)
# define SSL_get_options(ssl) \
SSL_ctrl((ssl),SSL_CTRL_OPTIONS,0,NULL)
# define SSL_CTX_set_mode(ctx,op) \
SSL_CTX_ctrl((ctx),SSL_CTRL_MODE,(op),NULL)
# define SSL_CTX_clear_mode(ctx,op) \
SSL_CTX_ctrl((ctx),SSL_CTRL_CLEAR_MODE,(op),NULL)
# define SSL_CTX_get_mode(ctx) \
SSL_CTX_ctrl((ctx),SSL_CTRL_MODE,0,NULL)
# define SSL_clear_mode(ssl,op) \
SSL_ctrl((ssl),SSL_CTRL_CLEAR_MODE,(op),NULL)
# define SSL_set_mode(ssl,op) \
SSL_ctrl((ssl),SSL_CTRL_MODE,(op),NULL)
# define SSL_get_mode(ssl) \
SSL_ctrl((ssl),SSL_CTRL_MODE,0,NULL)
# define SSL_set_mtu(ssl, mtu) \
SSL_ctrl((ssl),SSL_CTRL_SET_MTU,(mtu),NULL)
# define DTLS_set_link_mtu(ssl, mtu) \
SSL_ctrl((ssl),DTLS_CTRL_SET_LINK_MTU,(mtu),NULL)
# define DTLS_get_link_min_mtu(ssl) \
SSL_ctrl((ssl),DTLS_CTRL_GET_LINK_MIN_MTU,0,NULL)
# define SSL_get_secure_renegotiation_support(ssl) \
SSL_ctrl((ssl), SSL_CTRL_GET_RI_SUPPORT, 0, NULL)
# ifndef OPENSSL_NO_HEARTBEATS
# define SSL_heartbeat(ssl) \
SSL_ctrl((ssl),SSL_CTRL_TLS_EXT_SEND_HEARTBEAT,0,NULL)
# endif
# define SSL_CTX_set_cert_flags(ctx,op) \
SSL_CTX_ctrl((ctx),SSL_CTRL_CERT_FLAGS,(op),NULL)
# define SSL_set_cert_flags(s,op) \
SSL_ctrl((s),SSL_CTRL_CERT_FLAGS,(op),NULL)
# define SSL_CTX_clear_cert_flags(ctx,op) \
SSL_CTX_ctrl((ctx),SSL_CTRL_CLEAR_CERT_FLAGS,(op),NULL)
# define SSL_clear_cert_flags(s,op) \
SSL_ctrl((s),SSL_CTRL_CLEAR_CERT_FLAGS,(op),NULL)
void SSL_CTX_set_msg_callback(SSL_CTX *ctx,
void (*cb) (int write_p, int version,
int content_type, const void *buf,
size_t len, SSL *ssl, void *arg));
void SSL_set_msg_callback(SSL *ssl,
void (*cb) (int write_p, int version,
int content_type, const void *buf,
size_t len, SSL *ssl, void *arg));
# define SSL_CTX_set_msg_callback_arg(ctx, arg) SSL_CTX_ctrl((ctx), SSL_CTRL_SET_MSG_CALLBACK_ARG, 0, (arg))
# define SSL_set_msg_callback_arg(ssl, arg) SSL_ctrl((ssl), SSL_CTRL_SET_MSG_CALLBACK_ARG, 0, (arg))
# ifndef OPENSSL_NO_SRP
# ifndef OPENSSL_NO_SSL_INTERN
typedef struct srp_ctx_st {
/* param for all the callbacks */
void *SRP_cb_arg;
/* set client Hello login callback */
int (*TLS_ext_srp_username_callback) (SSL *, int *, void *);
/* set SRP N/g param callback for verification */
int (*SRP_verify_param_callback) (SSL *, void *);
/* set SRP client passwd callback */
char *(*SRP_give_srp_client_pwd_callback) (SSL *, void *);
char *login;
BIGNUM *N, *g, *s, *B, *A;
BIGNUM *a, *b, *v;
char *info;
int strength;
unsigned long srp_Mask;
} SRP_CTX;
# endif
/* see tls_srp.c */
int SSL_SRP_CTX_init(SSL *s);
int SSL_CTX_SRP_CTX_init(SSL_CTX *ctx);
int SSL_SRP_CTX_free(SSL *ctx);
int SSL_CTX_SRP_CTX_free(SSL_CTX *ctx);
int SSL_srp_server_param_with_username(SSL *s, int *ad);
int SRP_generate_server_master_secret(SSL *s, unsigned char *master_key);
int SRP_Calc_A_param(SSL *s);
int SRP_generate_client_master_secret(SSL *s, unsigned char *master_key);
# endif
# if defined(OPENSSL_SYS_MSDOS) && !defined(OPENSSL_SYS_WIN32)
# define SSL_MAX_CERT_LIST_DEFAULT 1024*30
/* 30k max cert list :-) */
# else
# define SSL_MAX_CERT_LIST_DEFAULT 1024*100
/* 100k max cert list :-) */
# endif
# define SSL_SESSION_CACHE_MAX_SIZE_DEFAULT (1024*20)
/*
* This callback type is used inside SSL_CTX, SSL, and in the functions that
* set them. It is used to override the generation of SSL/TLS session IDs in
* a server. Return value should be zero on an error, non-zero to proceed.
* Also, callbacks should themselves check if the id they generate is unique
* otherwise the SSL handshake will fail with an error - callbacks can do
* this using the 'ssl' value they're passed by;
* SSL_has_matching_session_id(ssl, id, *id_len) The length value passed in
* is set at the maximum size the session ID can be. In SSLv2 this is 16
* bytes, whereas SSLv3/TLSv1 it is 32 bytes. The callback can alter this
* length to be less if desired, but under SSLv2 session IDs are supposed to
* be fixed at 16 bytes so the id will be padded after the callback returns
* in this case. It is also an error for the callback to set the size to
* zero.
*/
typedef int (*GEN_SESSION_CB) (const SSL *ssl, unsigned char *id,
unsigned int *id_len);
typedef struct ssl_comp_st SSL_COMP;
# ifndef OPENSSL_NO_SSL_INTERN
struct ssl_comp_st {
int id;
const char *name;
# ifndef OPENSSL_NO_COMP
COMP_METHOD *method;
# else
char *method;
# endif
};
DECLARE_STACK_OF(SSL_COMP)
DECLARE_LHASH_OF(SSL_SESSION);
struct ssl_ctx_st {
const SSL_METHOD *method;
STACK_OF(SSL_CIPHER) *cipher_list;
/* same as above but sorted for lookup */
STACK_OF(SSL_CIPHER) *cipher_list_by_id;
struct x509_store_st /* X509_STORE */ *cert_store;
LHASH_OF(SSL_SESSION) *sessions;
/*
* Most session-ids that will be cached, default is
* SSL_SESSION_CACHE_MAX_SIZE_DEFAULT. 0 is unlimited.
*/
unsigned long session_cache_size;
struct ssl_session_st *session_cache_head;
struct ssl_session_st *session_cache_tail;
/*
* This can have one of 2 values, ored together, SSL_SESS_CACHE_CLIENT,
* SSL_SESS_CACHE_SERVER, Default is SSL_SESSION_CACHE_SERVER, which
* means only SSL_accept which cache SSL_SESSIONS.
*/
int session_cache_mode;
/*
* If timeout is not 0, it is the default timeout value set when
* SSL_new() is called. This has been put in to make life easier to set
* things up
*/
long session_timeout;
/*
* If this callback is not null, it will be called each time a session id
* is added to the cache. If this function returns 1, it means that the
* callback will do a SSL_SESSION_free() when it has finished using it.
* Otherwise, on 0, it means the callback has finished with it. If
* remove_session_cb is not null, it will be called when a session-id is
* removed from the cache. After the call, OpenSSL will
* SSL_SESSION_free() it.
*/
int (*new_session_cb) (struct ssl_st *ssl, SSL_SESSION *sess);
void (*remove_session_cb) (struct ssl_ctx_st *ctx, SSL_SESSION *sess);
SSL_SESSION *(*get_session_cb) (struct ssl_st *ssl,
unsigned char *data, int len, int *copy);
struct {
int sess_connect; /* SSL new conn - started */
int sess_connect_renegotiate; /* SSL reneg - requested */
int sess_connect_good; /* SSL new conne/reneg - finished */
int sess_accept; /* SSL new accept - started */
int sess_accept_renegotiate; /* SSL reneg - requested */
int sess_accept_good; /* SSL accept/reneg - finished */
int sess_miss; /* session lookup misses */
int sess_timeout; /* reuse attempt on timeouted session */
int sess_cache_full; /* session removed due to full cache */
int sess_hit; /* session reuse actually done */
int sess_cb_hit; /* session-id that was not in the cache was
* passed back via the callback. This
* indicates that the application is
* supplying session-id's from other
* processes - spooky :-) */
} stats;
int references;
/* if defined, these override the X509_verify_cert() calls */
int (*app_verify_callback) (X509_STORE_CTX *, void *);
void *app_verify_arg;
/*
* before OpenSSL 0.9.7, 'app_verify_arg' was ignored
* ('app_verify_callback' was called with just one argument)
*/
/* Default password callback. */
pem_password_cb *default_passwd_callback;
/* Default password callback user data. */
void *default_passwd_callback_userdata;
/* get client cert callback */
int (*client_cert_cb) (SSL *ssl, X509 **x509, EVP_PKEY **pkey);
/* cookie generate callback */
int (*app_gen_cookie_cb) (SSL *ssl, unsigned char *cookie,
unsigned int *cookie_len);
/* verify cookie callback */
int (*app_verify_cookie_cb) (SSL *ssl, unsigned char *cookie,
unsigned int cookie_len);
CRYPTO_EX_DATA ex_data;
const EVP_MD *rsa_md5; /* For SSLv2 - name is 'ssl2-md5' */
const EVP_MD *md5; /* For SSLv3/TLSv1 'ssl3-md5' */
const EVP_MD *sha1; /* For SSLv3/TLSv1 'ssl3->sha1' */
STACK_OF(X509) *extra_certs;
STACK_OF(SSL_COMP) *comp_methods; /* stack of SSL_COMP, SSLv3/TLSv1 */
/* Default values used when no per-SSL value is defined follow */
/* used if SSL's info_callback is NULL */
void (*info_callback) (const SSL *ssl, int type, int val);
/* what we put in client cert requests */
STACK_OF(X509_NAME) *client_CA;
/*
* Default values to use in SSL structures follow (these are copied by
* SSL_new)
*/
unsigned long options;
unsigned long mode;
long max_cert_list;
struct cert_st /* CERT */ *cert;
int read_ahead;
/* callback that allows applications to peek at protocol messages */
void (*msg_callback) (int write_p, int version, int content_type,
const void *buf, size_t len, SSL *ssl, void *arg);
void *msg_callback_arg;
int verify_mode;
unsigned int sid_ctx_length;
unsigned char sid_ctx[SSL_MAX_SID_CTX_LENGTH];
/* called 'verify_callback' in the SSL */
int (*default_verify_callback) (int ok, X509_STORE_CTX *ctx);
/* Default generate session ID callback. */
GEN_SESSION_CB generate_session_id;
X509_VERIFY_PARAM *param;
# if 0
int purpose; /* Purpose setting */
int trust; /* Trust setting */
# endif
int quiet_shutdown;
/*
* Maximum amount of data to send in one fragment. actual record size can
* be more than this due to padding and MAC overheads.
*/
unsigned int max_send_fragment;
# ifndef OPENSSL_NO_ENGINE
/*
* Engine to pass requests for client certs to
*/
ENGINE *client_cert_engine;
# endif
# ifndef OPENSSL_NO_TLSEXT
/* TLS extensions servername callback */
int (*tlsext_servername_callback) (SSL *, int *, void *);
void *tlsext_servername_arg;
/* RFC 4507 session ticket keys */
unsigned char tlsext_tick_key_name[16];
unsigned char tlsext_tick_hmac_key[16];
unsigned char tlsext_tick_aes_key[16];
/* Callback to support customisation of ticket key setting */
int (*tlsext_ticket_key_cb) (SSL *ssl,
unsigned char *name, unsigned char *iv,
EVP_CIPHER_CTX *ectx,
HMAC_CTX *hctx, int enc);
/* certificate status request info */
/* Callback for status request */
int (*tlsext_status_cb) (SSL *ssl, void *arg);
void *tlsext_status_arg;
/* draft-rescorla-tls-opaque-prf-input-00.txt information */
int (*tlsext_opaque_prf_input_callback) (SSL *, void *peerinput,
size_t len, void *arg);
void *tlsext_opaque_prf_input_callback_arg;
# endif
# ifndef OPENSSL_NO_PSK
char *psk_identity_hint;
unsigned int (*psk_client_callback) (SSL *ssl, const char *hint,
char *identity,
unsigned int max_identity_len,
unsigned char *psk,
unsigned int max_psk_len);
unsigned int (*psk_server_callback) (SSL *ssl, const char *identity,
unsigned char *psk,
unsigned int max_psk_len);
# endif
# ifndef OPENSSL_NO_BUF_FREELISTS
# define SSL_MAX_BUF_FREELIST_LEN_DEFAULT 32
unsigned int freelist_max_len;
struct ssl3_buf_freelist_st *wbuf_freelist;
struct ssl3_buf_freelist_st *rbuf_freelist;
# endif
# ifndef OPENSSL_NO_SRP
SRP_CTX srp_ctx; /* ctx for SRP authentication */
# endif
# ifndef OPENSSL_NO_TLSEXT
# ifndef OPENSSL_NO_NEXTPROTONEG
/* Next protocol negotiation information */
/* (for experimental NPN extension). */
/*
* For a server, this contains a callback function by which the set of
* advertised protocols can be provided.
*/
int (*next_protos_advertised_cb) (SSL *s, const unsigned char **buf,
unsigned int *len, void *arg);
void *next_protos_advertised_cb_arg;
/*
* For a client, this contains a callback function that selects the next
* protocol from the list provided by the server.
*/
int (*next_proto_select_cb) (SSL *s, unsigned char **out,
unsigned char *outlen,
const unsigned char *in,
unsigned int inlen, void *arg);
void *next_proto_select_cb_arg;
# endif
/* SRTP profiles we are willing to do from RFC 5764 */
STACK_OF(SRTP_PROTECTION_PROFILE) *srtp_profiles;
/*
* ALPN information (we are in the process of transitioning from NPN to
* ALPN.)
*/
/*-
* For a server, this contains a callback function that allows the
* server to select the protocol for the connection.
* out: on successful return, this must point to the raw protocol
* name (without the length prefix).
* outlen: on successful return, this contains the length of |*out|.
* in: points to the client's list of supported protocols in
* wire-format.
* inlen: the length of |in|.
*/
int (*alpn_select_cb) (SSL *s,
const unsigned char **out,
unsigned char *outlen,
const unsigned char *in,
unsigned int inlen, void *arg);
void *alpn_select_cb_arg;
/*
* For a client, this contains the list of supported protocols in wire
* format.
*/
unsigned char *alpn_client_proto_list;
unsigned alpn_client_proto_list_len;
# ifndef OPENSSL_NO_EC
/* EC extension values inherited by SSL structure */
size_t tlsext_ecpointformatlist_length;
unsigned char *tlsext_ecpointformatlist;
size_t tlsext_ellipticcurvelist_length;
unsigned char *tlsext_ellipticcurvelist;
# endif /* OPENSSL_NO_EC */
# endif
};
# endif
# define SSL_SESS_CACHE_OFF 0x0000
# define SSL_SESS_CACHE_CLIENT 0x0001
# define SSL_SESS_CACHE_SERVER 0x0002
# define SSL_SESS_CACHE_BOTH (SSL_SESS_CACHE_CLIENT|SSL_SESS_CACHE_SERVER)
# define SSL_SESS_CACHE_NO_AUTO_CLEAR 0x0080
/* enough comments already ... see SSL_CTX_set_session_cache_mode(3) */
# define SSL_SESS_CACHE_NO_INTERNAL_LOOKUP 0x0100
# define SSL_SESS_CACHE_NO_INTERNAL_STORE 0x0200
# define SSL_SESS_CACHE_NO_INTERNAL \
(SSL_SESS_CACHE_NO_INTERNAL_LOOKUP|SSL_SESS_CACHE_NO_INTERNAL_STORE)
LHASH_OF(SSL_SESSION) *SSL_CTX_sessions(SSL_CTX *ctx);
# define SSL_CTX_sess_number(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_NUMBER,0,NULL)
# define SSL_CTX_sess_connect(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_CONNECT,0,NULL)
# define SSL_CTX_sess_connect_good(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_CONNECT_GOOD,0,NULL)
# define SSL_CTX_sess_connect_renegotiate(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_CONNECT_RENEGOTIATE,0,NULL)
# define SSL_CTX_sess_accept(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_ACCEPT,0,NULL)
# define SSL_CTX_sess_accept_renegotiate(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_ACCEPT_RENEGOTIATE,0,NULL)
# define SSL_CTX_sess_accept_good(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_ACCEPT_GOOD,0,NULL)
# define SSL_CTX_sess_hits(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_HIT,0,NULL)
# define SSL_CTX_sess_cb_hits(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_CB_HIT,0,NULL)
# define SSL_CTX_sess_misses(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_MISSES,0,NULL)
# define SSL_CTX_sess_timeouts(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_TIMEOUTS,0,NULL)
# define SSL_CTX_sess_cache_full(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_CACHE_FULL,0,NULL)
void SSL_CTX_sess_set_new_cb(SSL_CTX *ctx,
int (*new_session_cb) (struct ssl_st *ssl,
SSL_SESSION *sess));
int (*SSL_CTX_sess_get_new_cb(SSL_CTX *ctx)) (struct ssl_st *ssl,
SSL_SESSION *sess);
void SSL_CTX_sess_set_remove_cb(SSL_CTX *ctx,
void (*remove_session_cb) (struct ssl_ctx_st
*ctx,
SSL_SESSION
*sess));
void (*SSL_CTX_sess_get_remove_cb(SSL_CTX *ctx)) (struct ssl_ctx_st *ctx,
SSL_SESSION *sess);
void SSL_CTX_sess_set_get_cb(SSL_CTX *ctx,
SSL_SESSION *(*get_session_cb) (struct ssl_st
*ssl,
unsigned char
*data, int len,
int *copy));
SSL_SESSION *(*SSL_CTX_sess_get_get_cb(SSL_CTX *ctx)) (struct ssl_st *ssl,
unsigned char *Data,
int len, int *copy);
void SSL_CTX_set_info_callback(SSL_CTX *ctx,
void (*cb) (const SSL *ssl, int type,
int val));
void (*SSL_CTX_get_info_callback(SSL_CTX *ctx)) (const SSL *ssl, int type,
int val);
void SSL_CTX_set_client_cert_cb(SSL_CTX *ctx,
int (*client_cert_cb) (SSL *ssl, X509 **x509,
EVP_PKEY **pkey));
int (*SSL_CTX_get_client_cert_cb(SSL_CTX *ctx)) (SSL *ssl, X509 **x509,
EVP_PKEY **pkey);
# ifndef OPENSSL_NO_ENGINE
int SSL_CTX_set_client_cert_engine(SSL_CTX *ctx, ENGINE *e);
# endif
void SSL_CTX_set_cookie_generate_cb(SSL_CTX *ctx,
int (*app_gen_cookie_cb) (SSL *ssl,
unsigned char
*cookie,
unsigned int
*cookie_len));
void SSL_CTX_set_cookie_verify_cb(SSL_CTX *ctx,
int (*app_verify_cookie_cb) (SSL *ssl,
unsigned char
*cookie,
unsigned int
cookie_len));
# ifndef OPENSSL_NO_NEXTPROTONEG
void SSL_CTX_set_next_protos_advertised_cb(SSL_CTX *s,
int (*cb) (SSL *ssl,
const unsigned char
**out,
unsigned int *outlen,
void *arg), void *arg);
void SSL_CTX_set_next_proto_select_cb(SSL_CTX *s,
int (*cb) (SSL *ssl,
unsigned char **out,
unsigned char *outlen,
const unsigned char *in,
unsigned int inlen,
void *arg), void *arg);
void SSL_get0_next_proto_negotiated(const SSL *s, const unsigned char **data,
unsigned *len);
# endif
# ifndef OPENSSL_NO_TLSEXT
int SSL_select_next_proto(unsigned char **out, unsigned char *outlen,
const unsigned char *in, unsigned int inlen,
const unsigned char *client,
unsigned int client_len);
# endif
# define OPENSSL_NPN_UNSUPPORTED 0
# define OPENSSL_NPN_NEGOTIATED 1
# define OPENSSL_NPN_NO_OVERLAP 2
int SSL_CTX_set_alpn_protos(SSL_CTX *ctx, const unsigned char *protos,
unsigned protos_len);
int SSL_set_alpn_protos(SSL *ssl, const unsigned char *protos,
unsigned protos_len);
void SSL_CTX_set_alpn_select_cb(SSL_CTX *ctx,
int (*cb) (SSL *ssl,
const unsigned char **out,
unsigned char *outlen,
const unsigned char *in,
unsigned int inlen,
void *arg), void *arg);
void SSL_get0_alpn_selected(const SSL *ssl, const unsigned char **data,
unsigned *len);
# ifndef OPENSSL_NO_PSK
/*
* the maximum length of the buffer given to callbacks containing the
* resulting identity/psk
*/
# define PSK_MAX_IDENTITY_LEN 128
# define PSK_MAX_PSK_LEN 256
void SSL_CTX_set_psk_client_callback(SSL_CTX *ctx,
unsigned int (*psk_client_callback) (SSL
*ssl,
const
char
*hint,
char
*identity,
unsigned
int
max_identity_len,
unsigned
char
*psk,
unsigned
int
max_psk_len));
void SSL_set_psk_client_callback(SSL *ssl,
unsigned int (*psk_client_callback) (SSL
*ssl,
const
char
*hint,
char
*identity,
unsigned
int
max_identity_len,
unsigned
char
*psk,
unsigned
int
max_psk_len));
void SSL_CTX_set_psk_server_callback(SSL_CTX *ctx,
unsigned int (*psk_server_callback) (SSL
*ssl,
const
char
*identity,
unsigned
char
*psk,
unsigned
int
max_psk_len));
void SSL_set_psk_server_callback(SSL *ssl,
unsigned int (*psk_server_callback) (SSL
*ssl,
const
char
*identity,
unsigned
char
*psk,
unsigned
int
max_psk_len));
int SSL_CTX_use_psk_identity_hint(SSL_CTX *ctx, const char *identity_hint);
int SSL_use_psk_identity_hint(SSL *s, const char *identity_hint);
const char *SSL_get_psk_identity_hint(const SSL *s);
const char *SSL_get_psk_identity(const SSL *s);
# endif
# ifndef OPENSSL_NO_TLSEXT
/* Register callbacks to handle custom TLS Extensions for client or server. */
int SSL_CTX_add_client_custom_ext(SSL_CTX *ctx, unsigned int ext_type,
custom_ext_add_cb add_cb,
custom_ext_free_cb free_cb,
void *add_arg,
custom_ext_parse_cb parse_cb,
void *parse_arg);
int SSL_CTX_add_server_custom_ext(SSL_CTX *ctx, unsigned int ext_type,
custom_ext_add_cb add_cb,
custom_ext_free_cb free_cb,
void *add_arg,
custom_ext_parse_cb parse_cb,
void *parse_arg);
int SSL_extension_supported(unsigned int ext_type);
# endif
# define SSL_NOTHING 1
# define SSL_WRITING 2
# define SSL_READING 3
# define SSL_X509_LOOKUP 4
/* These will only be used when doing non-blocking IO */
# define SSL_want_nothing(s) (SSL_want(s) == SSL_NOTHING)
# define SSL_want_read(s) (SSL_want(s) == SSL_READING)
# define SSL_want_write(s) (SSL_want(s) == SSL_WRITING)
# define SSL_want_x509_lookup(s) (SSL_want(s) == SSL_X509_LOOKUP)
# define SSL_MAC_FLAG_READ_MAC_STREAM 1
# define SSL_MAC_FLAG_WRITE_MAC_STREAM 2
# ifndef OPENSSL_NO_SSL_INTERN
struct ssl_st {
/*
* protocol version (one of SSL2_VERSION, SSL3_VERSION, TLS1_VERSION,
* DTLS1_VERSION)
*/
int version;
/* SSL_ST_CONNECT or SSL_ST_ACCEPT */
int type;
/* SSLv3 */
const SSL_METHOD *method;
/*
* There are 2 BIO's even though they are normally both the same. This
* is so data can be read and written to different handlers
*/
# ifndef OPENSSL_NO_BIO
/* used by SSL_read */
BIO *rbio;
/* used by SSL_write */
BIO *wbio;
/* used during session-id reuse to concatenate messages */
BIO *bbio;
# else
/* used by SSL_read */
char *rbio;
/* used by SSL_write */
char *wbio;
char *bbio;
# endif
/*
* This holds a variable that indicates what we were doing when a 0 or -1
* is returned. This is needed for non-blocking IO so we know what
* request needs re-doing when in SSL_accept or SSL_connect
*/
int rwstate;
/* true when we are actually in SSL_accept() or SSL_connect() */
int in_handshake;
int (*handshake_func) (SSL *);
/*
* Imagine that here's a boolean member "init" that is switched as soon
* as SSL_set_{accept/connect}_state is called for the first time, so
* that "state" and "handshake_func" are properly initialized. But as
* handshake_func is == 0 until then, we use this test instead of an
* "init" member.
*/
/* are we the server side? - mostly used by SSL_clear */
int server;
/*
* Generate a new session or reuse an old one.
* NB: For servers, the 'new' session may actually be a previously
* cached session or even the previous session unless
* SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION is set
*/
int new_session;
/* don't send shutdown packets */
int quiet_shutdown;
/* we have shut things down, 0x01 sent, 0x02 for received */
int shutdown;
/* where we are */
int state;
/* where we are when reading */
int rstate;
BUF_MEM *init_buf; /* buffer used during init */
void *init_msg; /* pointer to handshake message body, set by
* ssl3_get_message() */
int init_num; /* amount read/written */
int init_off; /* amount read/written */
/* used internally to point at a raw packet */
unsigned char *packet;
unsigned int packet_length;
struct ssl2_state_st *s2; /* SSLv2 variables */
struct ssl3_state_st *s3; /* SSLv3 variables */
struct dtls1_state_st *d1; /* DTLSv1 variables */
int read_ahead; /* Read as many input bytes as possible (for
* non-blocking reads) */
/* callback that allows applications to peek at protocol messages */
void (*msg_callback) (int write_p, int version, int content_type,
const void *buf, size_t len, SSL *ssl, void *arg);
void *msg_callback_arg;
int hit; /* reusing a previous session */
X509_VERIFY_PARAM *param;
# if 0
int purpose; /* Purpose setting */
int trust; /* Trust setting */
# endif
/* crypto */
STACK_OF(SSL_CIPHER) *cipher_list;
STACK_OF(SSL_CIPHER) *cipher_list_by_id;
/*
* These are the ones being used, the ones in SSL_SESSION are the ones to
* be 'copied' into these ones
*/
int mac_flags;
EVP_CIPHER_CTX *enc_read_ctx; /* cryptographic state */
EVP_MD_CTX *read_hash; /* used for mac generation */
# ifndef OPENSSL_NO_COMP
COMP_CTX *expand; /* uncompress */
# else
char *expand;
# endif
EVP_CIPHER_CTX *enc_write_ctx; /* cryptographic state */
EVP_MD_CTX *write_hash; /* used for mac generation */
# ifndef OPENSSL_NO_COMP
COMP_CTX *compress; /* compression */
# else
char *compress;
# endif
/* session info */
/* client cert? */
/* This is used to hold the server certificate used */
struct cert_st /* CERT */ *cert;
/*
* the session_id_context is used to ensure sessions are only reused in
* the appropriate context
*/
unsigned int sid_ctx_length;
unsigned char sid_ctx[SSL_MAX_SID_CTX_LENGTH];
/* This can also be in the session once a session is established */
SSL_SESSION *session;
/* Default generate session ID callback. */
GEN_SESSION_CB generate_session_id;
/* Used in SSL2 and SSL3 */
/*
* 0 don't care about verify failure.
* 1 fail if verify fails
*/
int verify_mode;
/* fail if callback returns 0 */
int (*verify_callback) (int ok, X509_STORE_CTX *ctx);
/* optional informational callback */
void (*info_callback) (const SSL *ssl, int type, int val);
/* error bytes to be written */
int error;
/* actual code */
int error_code;
# ifndef OPENSSL_NO_KRB5
/* Kerberos 5 context */
KSSL_CTX *kssl_ctx;
# endif /* OPENSSL_NO_KRB5 */
# ifndef OPENSSL_NO_PSK
unsigned int (*psk_client_callback) (SSL *ssl, const char *hint,
char *identity,
unsigned int max_identity_len,
unsigned char *psk,
unsigned int max_psk_len);
unsigned int (*psk_server_callback) (SSL *ssl, const char *identity,
unsigned char *psk,
unsigned int max_psk_len);
# endif
SSL_CTX *ctx;
/*
* set this flag to 1 and a sleep(1) is put into all SSL_read() and
* SSL_write() calls, good for nbio debuging :-)
*/
int debug;
/* extra application data */
long verify_result;
CRYPTO_EX_DATA ex_data;
/* for server side, keep the list of CA_dn we can use */
STACK_OF(X509_NAME) *client_CA;
int references;
/* protocol behaviour */
unsigned long options;
/* API behaviour */
unsigned long mode;
long max_cert_list;
int first_packet;
/* what was passed, used for SSLv3/TLS rollback check */
int client_version;
unsigned int max_send_fragment;
# ifndef OPENSSL_NO_TLSEXT
/* TLS extension debug callback */
void (*tlsext_debug_cb) (SSL *s, int client_server, int type,
unsigned char *data, int len, void *arg);
void *tlsext_debug_arg;
char *tlsext_hostname;
/*-
* no further mod of servername
* 0 : call the servername extension callback.
* 1 : prepare 2, allow last ack just after in server callback.
* 2 : don't call servername callback, no ack in server hello
*/
int servername_done;
/* certificate status request info */
/* Status type or -1 if no status type */
int tlsext_status_type;
/* Expect OCSP CertificateStatus message */
int tlsext_status_expected;
/* OCSP status request only */
STACK_OF(OCSP_RESPID) *tlsext_ocsp_ids;
X509_EXTENSIONS *tlsext_ocsp_exts;
/* OCSP response received or to be sent */
unsigned char *tlsext_ocsp_resp;
int tlsext_ocsp_resplen;
/* RFC4507 session ticket expected to be received or sent */
int tlsext_ticket_expected;
# ifndef OPENSSL_NO_EC
size_t tlsext_ecpointformatlist_length;
/* our list */
unsigned char *tlsext_ecpointformatlist;
size_t tlsext_ellipticcurvelist_length;
/* our list */
unsigned char *tlsext_ellipticcurvelist;
# endif /* OPENSSL_NO_EC */
/*
* draft-rescorla-tls-opaque-prf-input-00.txt information to be used for
* handshakes
*/
void *tlsext_opaque_prf_input;
size_t tlsext_opaque_prf_input_len;
/* TLS Session Ticket extension override */
TLS_SESSION_TICKET_EXT *tlsext_session_ticket;
/* TLS Session Ticket extension callback */
tls_session_ticket_ext_cb_fn tls_session_ticket_ext_cb;
void *tls_session_ticket_ext_cb_arg;
/* TLS pre-shared secret session resumption */
tls_session_secret_cb_fn tls_session_secret_cb;
void *tls_session_secret_cb_arg;
SSL_CTX *initial_ctx; /* initial ctx, used to store sessions */
# ifndef OPENSSL_NO_NEXTPROTONEG
/*
* Next protocol negotiation. For the client, this is the protocol that
* we sent in NextProtocol and is set when handling ServerHello
* extensions. For a server, this is the client's selected_protocol from
* NextProtocol and is set when handling the NextProtocol message, before
* the Finished message.
*/
unsigned char *next_proto_negotiated;
unsigned char next_proto_negotiated_len;
# endif
# define session_ctx initial_ctx
/* What we'll do */
STACK_OF(SRTP_PROTECTION_PROFILE) *srtp_profiles;
/* What's been chosen */
SRTP_PROTECTION_PROFILE *srtp_profile;
/*-
* Is use of the Heartbeat extension negotiated?
* 0: disabled
* 1: enabled
* 2: enabled, but not allowed to send Requests
*/
unsigned int tlsext_heartbeat;
/* Indicates if a HeartbeatRequest is in flight */
unsigned int tlsext_hb_pending;
/* HeartbeatRequest sequence number */
unsigned int tlsext_hb_seq;
# else
# define session_ctx ctx
# endif /* OPENSSL_NO_TLSEXT */
/*-
* 1 if we are renegotiating.
* 2 if we are a server and are inside a handshake
* (i.e. not just sending a HelloRequest)
*/
int renegotiate;
# ifndef OPENSSL_NO_SRP
/* ctx for SRP authentication */
SRP_CTX srp_ctx;
# endif
# ifndef OPENSSL_NO_TLSEXT
/*
* For a client, this contains the list of supported protocols in wire
* format.
*/
unsigned char *alpn_client_proto_list;
unsigned alpn_client_proto_list_len;
# endif /* OPENSSL_NO_TLSEXT */
};
# endif
#ifdef __cplusplus
}
#endif
# include <openssl/ssl2.h>
# include <openssl/ssl3.h>
# include <openssl/tls1.h> /* This is mostly sslv3 with a few tweaks */
# include <openssl/dtls1.h> /* Datagram TLS */
# include <openssl/ssl23.h>
# include <openssl/srtp.h> /* Support for the use_srtp extension */
#ifdef __cplusplus
extern "C" {
#endif
/* compatibility */
# define SSL_set_app_data(s,arg) (SSL_set_ex_data(s,0,(char *)arg))
# define SSL_get_app_data(s) (SSL_get_ex_data(s,0))
# define SSL_SESSION_set_app_data(s,a) (SSL_SESSION_set_ex_data(s,0,(char *)a))
# define SSL_SESSION_get_app_data(s) (SSL_SESSION_get_ex_data(s,0))
# define SSL_CTX_get_app_data(ctx) (SSL_CTX_get_ex_data(ctx,0))
# define SSL_CTX_set_app_data(ctx,arg) (SSL_CTX_set_ex_data(ctx,0,(char *)arg))
/*
* The following are the possible values for ssl->state are are used to
* indicate where we are up to in the SSL connection establishment. The
* macros that follow are about the only things you should need to use and
* even then, only when using non-blocking IO. It can also be useful to work
* out where you were when the connection failed
*/
# define SSL_ST_CONNECT 0x1000
# define SSL_ST_ACCEPT 0x2000
# define SSL_ST_MASK 0x0FFF
# define SSL_ST_INIT (SSL_ST_CONNECT|SSL_ST_ACCEPT)
# define SSL_ST_BEFORE 0x4000
# define SSL_ST_OK 0x03
# define SSL_ST_RENEGOTIATE (0x04|SSL_ST_INIT)
# define SSL_ST_ERR 0x05
# define SSL_CB_LOOP 0x01
# define SSL_CB_EXIT 0x02
# define SSL_CB_READ 0x04
# define SSL_CB_WRITE 0x08
# define SSL_CB_ALERT 0x4000/* used in callback */
# define SSL_CB_READ_ALERT (SSL_CB_ALERT|SSL_CB_READ)
# define SSL_CB_WRITE_ALERT (SSL_CB_ALERT|SSL_CB_WRITE)
# define SSL_CB_ACCEPT_LOOP (SSL_ST_ACCEPT|SSL_CB_LOOP)
# define SSL_CB_ACCEPT_EXIT (SSL_ST_ACCEPT|SSL_CB_EXIT)
# define SSL_CB_CONNECT_LOOP (SSL_ST_CONNECT|SSL_CB_LOOP)
# define SSL_CB_CONNECT_EXIT (SSL_ST_CONNECT|SSL_CB_EXIT)
# define SSL_CB_HANDSHAKE_START 0x10
# define SSL_CB_HANDSHAKE_DONE 0x20
/* Is the SSL_connection established? */
# define SSL_get_state(a) SSL_state(a)
# define SSL_is_init_finished(a) (SSL_state(a) == SSL_ST_OK)
# define SSL_in_init(a) (SSL_state(a)&SSL_ST_INIT)
# define SSL_in_before(a) (SSL_state(a)&SSL_ST_BEFORE)
# define SSL_in_connect_init(a) (SSL_state(a)&SSL_ST_CONNECT)
# define SSL_in_accept_init(a) (SSL_state(a)&SSL_ST_ACCEPT)
/*
* The following 2 states are kept in ssl->rstate when reads fail, you should
* not need these
*/
# define SSL_ST_READ_HEADER 0xF0
# define SSL_ST_READ_BODY 0xF1
# define SSL_ST_READ_DONE 0xF2
/*-
* Obtain latest Finished message
* -- that we sent (SSL_get_finished)
* -- that we expected from peer (SSL_get_peer_finished).
* Returns length (0 == no Finished so far), copies up to 'count' bytes.
*/
size_t SSL_get_finished(const SSL *s, void *buf, size_t count);
size_t SSL_get_peer_finished(const SSL *s, void *buf, size_t count);
/*
* use either SSL_VERIFY_NONE or SSL_VERIFY_PEER, the last 2 options are
* 'ored' with SSL_VERIFY_PEER if they are desired
*/
# define SSL_VERIFY_NONE 0x00
# define SSL_VERIFY_PEER 0x01
# define SSL_VERIFY_FAIL_IF_NO_PEER_CERT 0x02
# define SSL_VERIFY_CLIENT_ONCE 0x04
# define OpenSSL_add_ssl_algorithms() SSL_library_init()
# define SSLeay_add_ssl_algorithms() SSL_library_init()
/* this is for backward compatibility */
# if 0 /* NEW_SSLEAY */
# define SSL_CTX_set_default_verify(a,b,c) SSL_CTX_set_verify(a,b,c)
# define SSL_set_pref_cipher(c,n) SSL_set_cipher_list(c,n)
# define SSL_add_session(a,b) SSL_CTX_add_session((a),(b))
# define SSL_remove_session(a,b) SSL_CTX_remove_session((a),(b))
# define SSL_flush_sessions(a,b) SSL_CTX_flush_sessions((a),(b))
# endif
/* More backward compatibility */
# define SSL_get_cipher(s) \
SSL_CIPHER_get_name(SSL_get_current_cipher(s))
# define SSL_get_cipher_bits(s,np) \
SSL_CIPHER_get_bits(SSL_get_current_cipher(s),np)
# define SSL_get_cipher_version(s) \
SSL_CIPHER_get_version(SSL_get_current_cipher(s))
# define SSL_get_cipher_name(s) \
SSL_CIPHER_get_name(SSL_get_current_cipher(s))
# define SSL_get_time(a) SSL_SESSION_get_time(a)
# define SSL_set_time(a,b) SSL_SESSION_set_time((a),(b))
# define SSL_get_timeout(a) SSL_SESSION_get_timeout(a)
# define SSL_set_timeout(a,b) SSL_SESSION_set_timeout((a),(b))
# define d2i_SSL_SESSION_bio(bp,s_id) ASN1_d2i_bio_of(SSL_SESSION,SSL_SESSION_new,d2i_SSL_SESSION,bp,s_id)
# define i2d_SSL_SESSION_bio(bp,s_id) ASN1_i2d_bio_of(SSL_SESSION,i2d_SSL_SESSION,bp,s_id)
DECLARE_PEM_rw(SSL_SESSION, SSL_SESSION)
# define SSL_AD_REASON_OFFSET 1000/* offset to get SSL_R_... value
* from SSL_AD_... */
/* These alert types are for SSLv3 and TLSv1 */
# define SSL_AD_CLOSE_NOTIFY SSL3_AD_CLOSE_NOTIFY
/* fatal */
# define SSL_AD_UNEXPECTED_MESSAGE SSL3_AD_UNEXPECTED_MESSAGE
/* fatal */
# define SSL_AD_BAD_RECORD_MAC SSL3_AD_BAD_RECORD_MAC
# define SSL_AD_DECRYPTION_FAILED TLS1_AD_DECRYPTION_FAILED
# define SSL_AD_RECORD_OVERFLOW TLS1_AD_RECORD_OVERFLOW
/* fatal */
# define SSL_AD_DECOMPRESSION_FAILURE SSL3_AD_DECOMPRESSION_FAILURE
/* fatal */
# define SSL_AD_HANDSHAKE_FAILURE SSL3_AD_HANDSHAKE_FAILURE
/* Not for TLS */
# define SSL_AD_NO_CERTIFICATE SSL3_AD_NO_CERTIFICATE
# define SSL_AD_BAD_CERTIFICATE SSL3_AD_BAD_CERTIFICATE
# define SSL_AD_UNSUPPORTED_CERTIFICATE SSL3_AD_UNSUPPORTED_CERTIFICATE
# define SSL_AD_CERTIFICATE_REVOKED SSL3_AD_CERTIFICATE_REVOKED
# define SSL_AD_CERTIFICATE_EXPIRED SSL3_AD_CERTIFICATE_EXPIRED
# define SSL_AD_CERTIFICATE_UNKNOWN SSL3_AD_CERTIFICATE_UNKNOWN
/* fatal */
# define SSL_AD_ILLEGAL_PARAMETER SSL3_AD_ILLEGAL_PARAMETER
/* fatal */
# define SSL_AD_UNKNOWN_CA TLS1_AD_UNKNOWN_CA
/* fatal */
# define SSL_AD_ACCESS_DENIED TLS1_AD_ACCESS_DENIED
/* fatal */
# define SSL_AD_DECODE_ERROR TLS1_AD_DECODE_ERROR
# define SSL_AD_DECRYPT_ERROR TLS1_AD_DECRYPT_ERROR
/* fatal */
# define SSL_AD_EXPORT_RESTRICTION TLS1_AD_EXPORT_RESTRICTION
/* fatal */
# define SSL_AD_PROTOCOL_VERSION TLS1_AD_PROTOCOL_VERSION
/* fatal */
# define SSL_AD_INSUFFICIENT_SECURITY TLS1_AD_INSUFFICIENT_SECURITY
/* fatal */
# define SSL_AD_INTERNAL_ERROR TLS1_AD_INTERNAL_ERROR
# define SSL_AD_USER_CANCELLED TLS1_AD_USER_CANCELLED
# define SSL_AD_NO_RENEGOTIATION TLS1_AD_NO_RENEGOTIATION
# define SSL_AD_UNSUPPORTED_EXTENSION TLS1_AD_UNSUPPORTED_EXTENSION
# define SSL_AD_CERTIFICATE_UNOBTAINABLE TLS1_AD_CERTIFICATE_UNOBTAINABLE
# define SSL_AD_UNRECOGNIZED_NAME TLS1_AD_UNRECOGNIZED_NAME
# define SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE
# define SSL_AD_BAD_CERTIFICATE_HASH_VALUE TLS1_AD_BAD_CERTIFICATE_HASH_VALUE
/* fatal */
# define SSL_AD_UNKNOWN_PSK_IDENTITY TLS1_AD_UNKNOWN_PSK_IDENTITY
/* fatal */
# define SSL_AD_INAPPROPRIATE_FALLBACK TLS1_AD_INAPPROPRIATE_FALLBACK
# define SSL_ERROR_NONE 0
# define SSL_ERROR_SSL 1
# define SSL_ERROR_WANT_READ 2
# define SSL_ERROR_WANT_WRITE 3
# define SSL_ERROR_WANT_X509_LOOKUP 4
# define SSL_ERROR_SYSCALL 5/* look at error stack/return
* value/errno */
# define SSL_ERROR_ZERO_RETURN 6
# define SSL_ERROR_WANT_CONNECT 7
# define SSL_ERROR_WANT_ACCEPT 8
# define SSL_CTRL_NEED_TMP_RSA 1
# define SSL_CTRL_SET_TMP_RSA 2
# define SSL_CTRL_SET_TMP_DH 3
# define SSL_CTRL_SET_TMP_ECDH 4
# define SSL_CTRL_SET_TMP_RSA_CB 5
# define SSL_CTRL_SET_TMP_DH_CB 6
# define SSL_CTRL_SET_TMP_ECDH_CB 7
# define SSL_CTRL_GET_SESSION_REUSED 8
# define SSL_CTRL_GET_CLIENT_CERT_REQUEST 9
# define SSL_CTRL_GET_NUM_RENEGOTIATIONS 10
# define SSL_CTRL_CLEAR_NUM_RENEGOTIATIONS 11
# define SSL_CTRL_GET_TOTAL_RENEGOTIATIONS 12
# define SSL_CTRL_GET_FLAGS 13
# define SSL_CTRL_EXTRA_CHAIN_CERT 14
# define SSL_CTRL_SET_MSG_CALLBACK 15
# define SSL_CTRL_SET_MSG_CALLBACK_ARG 16
/* only applies to datagram connections */
# define SSL_CTRL_SET_MTU 17
/* Stats */
# define SSL_CTRL_SESS_NUMBER 20
# define SSL_CTRL_SESS_CONNECT 21
# define SSL_CTRL_SESS_CONNECT_GOOD 22
# define SSL_CTRL_SESS_CONNECT_RENEGOTIATE 23
# define SSL_CTRL_SESS_ACCEPT 24
# define SSL_CTRL_SESS_ACCEPT_GOOD 25
# define SSL_CTRL_SESS_ACCEPT_RENEGOTIATE 26
# define SSL_CTRL_SESS_HIT 27
# define SSL_CTRL_SESS_CB_HIT 28
# define SSL_CTRL_SESS_MISSES 29
# define SSL_CTRL_SESS_TIMEOUTS 30
# define SSL_CTRL_SESS_CACHE_FULL 31
# define SSL_CTRL_OPTIONS 32
# define SSL_CTRL_MODE 33
# define SSL_CTRL_GET_READ_AHEAD 40
# define SSL_CTRL_SET_READ_AHEAD 41
# define SSL_CTRL_SET_SESS_CACHE_SIZE 42
# define SSL_CTRL_GET_SESS_CACHE_SIZE 43
# define SSL_CTRL_SET_SESS_CACHE_MODE 44
# define SSL_CTRL_GET_SESS_CACHE_MODE 45
# define SSL_CTRL_GET_MAX_CERT_LIST 50
# define SSL_CTRL_SET_MAX_CERT_LIST 51
# define SSL_CTRL_SET_MAX_SEND_FRAGMENT 52
/* see tls1.h for macros based on these */
# ifndef OPENSSL_NO_TLSEXT
# define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
# define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
# define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
# define SSL_CTRL_SET_TLSEXT_DEBUG_CB 56
# define SSL_CTRL_SET_TLSEXT_DEBUG_ARG 57
# define SSL_CTRL_GET_TLSEXT_TICKET_KEYS 58
# define SSL_CTRL_SET_TLSEXT_TICKET_KEYS 59
# define SSL_CTRL_SET_TLSEXT_OPAQUE_PRF_INPUT 60
# define SSL_CTRL_SET_TLSEXT_OPAQUE_PRF_INPUT_CB 61
# define SSL_CTRL_SET_TLSEXT_OPAQUE_PRF_INPUT_CB_ARG 62
# define SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB 63
# define SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB_ARG 64
# define SSL_CTRL_SET_TLSEXT_STATUS_REQ_TYPE 65
# define SSL_CTRL_GET_TLSEXT_STATUS_REQ_EXTS 66
# define SSL_CTRL_SET_TLSEXT_STATUS_REQ_EXTS 67
# define SSL_CTRL_GET_TLSEXT_STATUS_REQ_IDS 68
# define SSL_CTRL_SET_TLSEXT_STATUS_REQ_IDS 69
# define SSL_CTRL_GET_TLSEXT_STATUS_REQ_OCSP_RESP 70
# define SSL_CTRL_SET_TLSEXT_STATUS_REQ_OCSP_RESP 71
# define SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB 72
# define SSL_CTRL_SET_TLS_EXT_SRP_USERNAME_CB 75
# define SSL_CTRL_SET_SRP_VERIFY_PARAM_CB 76
# define SSL_CTRL_SET_SRP_GIVE_CLIENT_PWD_CB 77
# define SSL_CTRL_SET_SRP_ARG 78
# define SSL_CTRL_SET_TLS_EXT_SRP_USERNAME 79
# define SSL_CTRL_SET_TLS_EXT_SRP_STRENGTH 80
# define SSL_CTRL_SET_TLS_EXT_SRP_PASSWORD 81
# ifndef OPENSSL_NO_HEARTBEATS
# define SSL_CTRL_TLS_EXT_SEND_HEARTBEAT 85
# define SSL_CTRL_GET_TLS_EXT_HEARTBEAT_PENDING 86
# define SSL_CTRL_SET_TLS_EXT_HEARTBEAT_NO_REQUESTS 87
# endif
# endif /* OPENSSL_NO_TLSEXT */
# define DTLS_CTRL_GET_TIMEOUT 73
# define DTLS_CTRL_HANDLE_TIMEOUT 74
# define DTLS_CTRL_LISTEN 75
# define SSL_CTRL_GET_RI_SUPPORT 76
# define SSL_CTRL_CLEAR_OPTIONS 77
# define SSL_CTRL_CLEAR_MODE 78
# define SSL_CTRL_GET_EXTRA_CHAIN_CERTS 82
# define SSL_CTRL_CLEAR_EXTRA_CHAIN_CERTS 83
# define SSL_CTRL_CHAIN 88
# define SSL_CTRL_CHAIN_CERT 89
# define SSL_CTRL_GET_CURVES 90
# define SSL_CTRL_SET_CURVES 91
# define SSL_CTRL_SET_CURVES_LIST 92
# define SSL_CTRL_GET_SHARED_CURVE 93
# define SSL_CTRL_SET_ECDH_AUTO 94
# define SSL_CTRL_SET_SIGALGS 97
# define SSL_CTRL_SET_SIGALGS_LIST 98
# define SSL_CTRL_CERT_FLAGS 99
# define SSL_CTRL_CLEAR_CERT_FLAGS 100
# define SSL_CTRL_SET_CLIENT_SIGALGS 101
# define SSL_CTRL_SET_CLIENT_SIGALGS_LIST 102
# define SSL_CTRL_GET_CLIENT_CERT_TYPES 103
# define SSL_CTRL_SET_CLIENT_CERT_TYPES 104
# define SSL_CTRL_BUILD_CERT_CHAIN 105
# define SSL_CTRL_SET_VERIFY_CERT_STORE 106
# define SSL_CTRL_SET_CHAIN_CERT_STORE 107
# define SSL_CTRL_GET_PEER_SIGNATURE_NID 108
# define SSL_CTRL_GET_SERVER_TMP_KEY 109
# define SSL_CTRL_GET_RAW_CIPHERLIST 110
# define SSL_CTRL_GET_EC_POINT_FORMATS 111
# define SSL_CTRL_GET_CHAIN_CERTS 115
# define SSL_CTRL_SELECT_CURRENT_CERT 116
# define SSL_CTRL_SET_CURRENT_CERT 117
# define SSL_CTRL_CHECK_PROTO_VERSION 119
# define DTLS_CTRL_SET_LINK_MTU 120
# define DTLS_CTRL_GET_LINK_MIN_MTU 121
# define SSL_CERT_SET_FIRST 1
# define SSL_CERT_SET_NEXT 2
# define SSL_CERT_SET_SERVER 3
# define DTLSv1_get_timeout(ssl, arg) \
SSL_ctrl(ssl,DTLS_CTRL_GET_TIMEOUT,0, (void *)arg)
# define DTLSv1_handle_timeout(ssl) \
SSL_ctrl(ssl,DTLS_CTRL_HANDLE_TIMEOUT,0, NULL)
# define DTLSv1_listen(ssl, peer) \
SSL_ctrl(ssl,DTLS_CTRL_LISTEN,0, (void *)peer)
# define SSL_session_reused(ssl) \
SSL_ctrl((ssl),SSL_CTRL_GET_SESSION_REUSED,0,NULL)
# define SSL_num_renegotiations(ssl) \
SSL_ctrl((ssl),SSL_CTRL_GET_NUM_RENEGOTIATIONS,0,NULL)
# define SSL_clear_num_renegotiations(ssl) \
SSL_ctrl((ssl),SSL_CTRL_CLEAR_NUM_RENEGOTIATIONS,0,NULL)
# define SSL_total_renegotiations(ssl) \
SSL_ctrl((ssl),SSL_CTRL_GET_TOTAL_RENEGOTIATIONS,0,NULL)
# define SSL_CTX_need_tmp_RSA(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_NEED_TMP_RSA,0,NULL)
# define SSL_CTX_set_tmp_rsa(ctx,rsa) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_TMP_RSA,0,(char *)rsa)
# define SSL_CTX_set_tmp_dh(ctx,dh) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_TMP_DH,0,(char *)dh)
# define SSL_CTX_set_tmp_ecdh(ctx,ecdh) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_TMP_ECDH,0,(char *)ecdh)
# define SSL_need_tmp_RSA(ssl) \
SSL_ctrl(ssl,SSL_CTRL_NEED_TMP_RSA,0,NULL)
# define SSL_set_tmp_rsa(ssl,rsa) \
SSL_ctrl(ssl,SSL_CTRL_SET_TMP_RSA,0,(char *)rsa)
# define SSL_set_tmp_dh(ssl,dh) \
SSL_ctrl(ssl,SSL_CTRL_SET_TMP_DH,0,(char *)dh)
# define SSL_set_tmp_ecdh(ssl,ecdh) \
SSL_ctrl(ssl,SSL_CTRL_SET_TMP_ECDH,0,(char *)ecdh)
# define SSL_CTX_add_extra_chain_cert(ctx,x509) \
SSL_CTX_ctrl(ctx,SSL_CTRL_EXTRA_CHAIN_CERT,0,(char *)x509)
# define SSL_CTX_get_extra_chain_certs(ctx,px509) \
SSL_CTX_ctrl(ctx,SSL_CTRL_GET_EXTRA_CHAIN_CERTS,0,px509)
# define SSL_CTX_get_extra_chain_certs_only(ctx,px509) \
SSL_CTX_ctrl(ctx,SSL_CTRL_GET_EXTRA_CHAIN_CERTS,1,px509)
# define SSL_CTX_clear_extra_chain_certs(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_CLEAR_EXTRA_CHAIN_CERTS,0,NULL)
# define SSL_CTX_set0_chain(ctx,sk) \
SSL_CTX_ctrl(ctx,SSL_CTRL_CHAIN,0,(char *)sk)
# define SSL_CTX_set1_chain(ctx,sk) \
SSL_CTX_ctrl(ctx,SSL_CTRL_CHAIN,1,(char *)sk)
# define SSL_CTX_add0_chain_cert(ctx,x509) \
SSL_CTX_ctrl(ctx,SSL_CTRL_CHAIN_CERT,0,(char *)x509)
# define SSL_CTX_add1_chain_cert(ctx,x509) \
SSL_CTX_ctrl(ctx,SSL_CTRL_CHAIN_CERT,1,(char *)x509)
# define SSL_CTX_get0_chain_certs(ctx,px509) \
SSL_CTX_ctrl(ctx,SSL_CTRL_GET_CHAIN_CERTS,0,px509)
# define SSL_CTX_clear_chain_certs(ctx) \
SSL_CTX_set0_chain(ctx,NULL)
# define SSL_CTX_build_cert_chain(ctx, flags) \
SSL_CTX_ctrl(ctx,SSL_CTRL_BUILD_CERT_CHAIN, flags, NULL)
# define SSL_CTX_select_current_cert(ctx,x509) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SELECT_CURRENT_CERT,0,(char *)x509)
# define SSL_CTX_set_current_cert(ctx, op) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CURRENT_CERT, op, NULL)
# define SSL_CTX_set0_verify_cert_store(ctx,st) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_VERIFY_CERT_STORE,0,(char *)st)
# define SSL_CTX_set1_verify_cert_store(ctx,st) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_VERIFY_CERT_STORE,1,(char *)st)
# define SSL_CTX_set0_chain_cert_store(ctx,st) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CHAIN_CERT_STORE,0,(char *)st)
# define SSL_CTX_set1_chain_cert_store(ctx,st) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CHAIN_CERT_STORE,1,(char *)st)
# define SSL_set0_chain(ctx,sk) \
SSL_ctrl(ctx,SSL_CTRL_CHAIN,0,(char *)sk)
# define SSL_set1_chain(ctx,sk) \
SSL_ctrl(ctx,SSL_CTRL_CHAIN,1,(char *)sk)
# define SSL_add0_chain_cert(ctx,x509) \
SSL_ctrl(ctx,SSL_CTRL_CHAIN_CERT,0,(char *)x509)
# define SSL_add1_chain_cert(ctx,x509) \
SSL_ctrl(ctx,SSL_CTRL_CHAIN_CERT,1,(char *)x509)
# define SSL_get0_chain_certs(ctx,px509) \
SSL_ctrl(ctx,SSL_CTRL_GET_CHAIN_CERTS,0,px509)
# define SSL_clear_chain_certs(ctx) \
SSL_set0_chain(ctx,NULL)
# define SSL_build_cert_chain(s, flags) \
SSL_ctrl(s,SSL_CTRL_BUILD_CERT_CHAIN, flags, NULL)
# define SSL_select_current_cert(ctx,x509) \
SSL_ctrl(ctx,SSL_CTRL_SELECT_CURRENT_CERT,0,(char *)x509)
# define SSL_set_current_cert(ctx,op) \
SSL_ctrl(ctx,SSL_CTRL_SET_CURRENT_CERT, op, NULL)
# define SSL_set0_verify_cert_store(s,st) \
SSL_ctrl(s,SSL_CTRL_SET_VERIFY_CERT_STORE,0,(char *)st)
# define SSL_set1_verify_cert_store(s,st) \
SSL_ctrl(s,SSL_CTRL_SET_VERIFY_CERT_STORE,1,(char *)st)
# define SSL_set0_chain_cert_store(s,st) \
SSL_ctrl(s,SSL_CTRL_SET_CHAIN_CERT_STORE,0,(char *)st)
# define SSL_set1_chain_cert_store(s,st) \
SSL_ctrl(s,SSL_CTRL_SET_CHAIN_CERT_STORE,1,(char *)st)
# define SSL_get1_curves(ctx, s) \
SSL_ctrl(ctx,SSL_CTRL_GET_CURVES,0,(char *)s)
# define SSL_CTX_set1_curves(ctx, clist, clistlen) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CURVES,clistlen,(char *)clist)
# define SSL_CTX_set1_curves_list(ctx, s) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CURVES_LIST,0,(char *)s)
# define SSL_set1_curves(ctx, clist, clistlen) \
SSL_ctrl(ctx,SSL_CTRL_SET_CURVES,clistlen,(char *)clist)
# define SSL_set1_curves_list(ctx, s) \
SSL_ctrl(ctx,SSL_CTRL_SET_CURVES_LIST,0,(char *)s)
# define SSL_get_shared_curve(s, n) \
SSL_ctrl(s,SSL_CTRL_GET_SHARED_CURVE,n,NULL)
# define SSL_CTX_set_ecdh_auto(ctx, onoff) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_ECDH_AUTO,onoff,NULL)
# define SSL_set_ecdh_auto(s, onoff) \
SSL_ctrl(s,SSL_CTRL_SET_ECDH_AUTO,onoff,NULL)
# define SSL_CTX_set1_sigalgs(ctx, slist, slistlen) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_SIGALGS,slistlen,(int *)slist)
# define SSL_CTX_set1_sigalgs_list(ctx, s) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_SIGALGS_LIST,0,(char *)s)
# define SSL_set1_sigalgs(ctx, slist, slistlen) \
SSL_ctrl(ctx,SSL_CTRL_SET_SIGALGS,slistlen,(int *)slist)
# define SSL_set1_sigalgs_list(ctx, s) \
SSL_ctrl(ctx,SSL_CTRL_SET_SIGALGS_LIST,0,(char *)s)
# define SSL_CTX_set1_client_sigalgs(ctx, slist, slistlen) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CLIENT_SIGALGS,slistlen,(int *)slist)
# define SSL_CTX_set1_client_sigalgs_list(ctx, s) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CLIENT_SIGALGS_LIST,0,(char *)s)
# define SSL_set1_client_sigalgs(ctx, slist, slistlen) \
SSL_ctrl(ctx,SSL_CTRL_SET_CLIENT_SIGALGS,clistlen,(int *)slist)
# define SSL_set1_client_sigalgs_list(ctx, s) \
SSL_ctrl(ctx,SSL_CTRL_SET_CLIENT_SIGALGS_LIST,0,(char *)s)
# define SSL_get0_certificate_types(s, clist) \
SSL_ctrl(s, SSL_CTRL_GET_CLIENT_CERT_TYPES, 0, (char *)clist)
# define SSL_CTX_set1_client_certificate_types(ctx, clist, clistlen) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CLIENT_CERT_TYPES,clistlen,(char *)clist)
# define SSL_set1_client_certificate_types(s, clist, clistlen) \
SSL_ctrl(s,SSL_CTRL_SET_CLIENT_CERT_TYPES,clistlen,(char *)clist)
# define SSL_get_peer_signature_nid(s, pn) \
SSL_ctrl(s,SSL_CTRL_GET_PEER_SIGNATURE_NID,0,pn)
# define SSL_get_server_tmp_key(s, pk) \
SSL_ctrl(s,SSL_CTRL_GET_SERVER_TMP_KEY,0,pk)
# define SSL_get0_raw_cipherlist(s, plst) \
SSL_ctrl(s,SSL_CTRL_GET_RAW_CIPHERLIST,0,(char *)plst)
# define SSL_get0_ec_point_formats(s, plst) \
SSL_ctrl(s,SSL_CTRL_GET_EC_POINT_FORMATS,0,(char *)plst)
# ifndef OPENSSL_NO_BIO
BIO_METHOD *BIO_f_ssl(void);
BIO *BIO_new_ssl(SSL_CTX *ctx, int client);
BIO *BIO_new_ssl_connect(SSL_CTX *ctx);
BIO *BIO_new_buffer_ssl_connect(SSL_CTX *ctx);
int BIO_ssl_copy_session_id(BIO *to, BIO *from);
void BIO_ssl_shutdown(BIO *ssl_bio);
# endif
int SSL_CTX_set_cipher_list(SSL_CTX *, const char *str);
SSL_CTX *SSL_CTX_new(const SSL_METHOD *meth);
void SSL_CTX_free(SSL_CTX *);
long SSL_CTX_set_timeout(SSL_CTX *ctx, long t);
long SSL_CTX_get_timeout(const SSL_CTX *ctx);
X509_STORE *SSL_CTX_get_cert_store(const SSL_CTX *);
void SSL_CTX_set_cert_store(SSL_CTX *, X509_STORE *);
int SSL_want(const SSL *s);
int SSL_clear(SSL *s);
void SSL_CTX_flush_sessions(SSL_CTX *ctx, long tm);
const SSL_CIPHER *SSL_get_current_cipher(const SSL *s);
int SSL_CIPHER_get_bits(const SSL_CIPHER *c, int *alg_bits);
char *SSL_CIPHER_get_version(const SSL_CIPHER *c);
const char *SSL_CIPHER_get_name(const SSL_CIPHER *c);
unsigned long SSL_CIPHER_get_id(const SSL_CIPHER *c);
int SSL_get_fd(const SSL *s);
int SSL_get_rfd(const SSL *s);
int SSL_get_wfd(const SSL *s);
const char *SSL_get_cipher_list(const SSL *s, int n);
char *SSL_get_shared_ciphers(const SSL *s, char *buf, int len);
int SSL_get_read_ahead(const SSL *s);
int SSL_pending(const SSL *s);
# ifndef OPENSSL_NO_SOCK
int SSL_set_fd(SSL *s, int fd);
int SSL_set_rfd(SSL *s, int fd);
int SSL_set_wfd(SSL *s, int fd);
# endif
# ifndef OPENSSL_NO_BIO
void SSL_set_bio(SSL *s, BIO *rbio, BIO *wbio);
BIO *SSL_get_rbio(const SSL *s);
BIO *SSL_get_wbio(const SSL *s);
# endif
int SSL_set_cipher_list(SSL *s, const char *str);
void SSL_set_read_ahead(SSL *s, int yes);
int SSL_get_verify_mode(const SSL *s);
int SSL_get_verify_depth(const SSL *s);
int (*SSL_get_verify_callback(const SSL *s)) (int, X509_STORE_CTX *);
void SSL_set_verify(SSL *s, int mode,
int (*callback) (int ok, X509_STORE_CTX *ctx));
void SSL_set_verify_depth(SSL *s, int depth);
void SSL_set_cert_cb(SSL *s, int (*cb) (SSL *ssl, void *arg), void *arg);
# ifndef OPENSSL_NO_RSA
int SSL_use_RSAPrivateKey(SSL *ssl, RSA *rsa);
# endif
int SSL_use_RSAPrivateKey_ASN1(SSL *ssl, unsigned char *d, long len);
int SSL_use_PrivateKey(SSL *ssl, EVP_PKEY *pkey);
int SSL_use_PrivateKey_ASN1(int pk, SSL *ssl, const unsigned char *d,
long len);
int SSL_use_certificate(SSL *ssl, X509 *x);
int SSL_use_certificate_ASN1(SSL *ssl, const unsigned char *d, int len);
# ifndef OPENSSL_NO_TLSEXT
/* Set serverinfo data for the current active cert. */
int SSL_CTX_use_serverinfo(SSL_CTX *ctx, const unsigned char *serverinfo,
size_t serverinfo_length);
# ifndef OPENSSL_NO_STDIO
int SSL_CTX_use_serverinfo_file(SSL_CTX *ctx, const char *file);
# endif /* NO_STDIO */
# endif
# ifndef OPENSSL_NO_STDIO
int SSL_use_RSAPrivateKey_file(SSL *ssl, const char *file, int type);
int SSL_use_PrivateKey_file(SSL *ssl, const char *file, int type);
int SSL_use_certificate_file(SSL *ssl, const char *file, int type);
int SSL_CTX_use_RSAPrivateKey_file(SSL_CTX *ctx, const char *file, int type);
int SSL_CTX_use_PrivateKey_file(SSL_CTX *ctx, const char *file, int type);
int SSL_CTX_use_certificate_file(SSL_CTX *ctx, const char *file, int type);
/* PEM type */
int SSL_CTX_use_certificate_chain_file(SSL_CTX *ctx, const char *file);
STACK_OF(X509_NAME) *SSL_load_client_CA_file(const char *file);
int SSL_add_file_cert_subjects_to_stack(STACK_OF(X509_NAME) *stackCAs,
const char *file);
# ifndef OPENSSL_SYS_VMS
/* XXXXX: Better scheme needed! [was: #ifndef MAC_OS_pre_X] */
# ifndef OPENSSL_SYS_MACINTOSH_CLASSIC
int SSL_add_dir_cert_subjects_to_stack(STACK_OF(X509_NAME) *stackCAs,
const char *dir);
# endif
# endif
# endif
void SSL_load_error_strings(void);
const char *SSL_state_string(const SSL *s);
const char *SSL_rstate_string(const SSL *s);
const char *SSL_state_string_long(const SSL *s);
const char *SSL_rstate_string_long(const SSL *s);
long SSL_SESSION_get_time(const SSL_SESSION *s);
long SSL_SESSION_set_time(SSL_SESSION *s, long t);
long SSL_SESSION_get_timeout(const SSL_SESSION *s);
long SSL_SESSION_set_timeout(SSL_SESSION *s, long t);
void SSL_copy_session_id(SSL *to, const SSL *from);
X509 *SSL_SESSION_get0_peer(SSL_SESSION *s);
int SSL_SESSION_set1_id_context(SSL_SESSION *s, const unsigned char *sid_ctx,
unsigned int sid_ctx_len);
SSL_SESSION *SSL_SESSION_new(void);
const unsigned char *SSL_SESSION_get_id(const SSL_SESSION *s,
unsigned int *len);
unsigned int SSL_SESSION_get_compress_id(const SSL_SESSION *s);
# ifndef OPENSSL_NO_FP_API
int SSL_SESSION_print_fp(FILE *fp, const SSL_SESSION *ses);
# endif
# ifndef OPENSSL_NO_BIO
int SSL_SESSION_print(BIO *fp, const SSL_SESSION *ses);
# endif
void SSL_SESSION_free(SSL_SESSION *ses);
int i2d_SSL_SESSION(SSL_SESSION *in, unsigned char **pp);
int SSL_set_session(SSL *to, SSL_SESSION *session);
int SSL_CTX_add_session(SSL_CTX *s, SSL_SESSION *c);
int SSL_CTX_remove_session(SSL_CTX *, SSL_SESSION *c);
int SSL_CTX_set_generate_session_id(SSL_CTX *, GEN_SESSION_CB);
int SSL_set_generate_session_id(SSL *, GEN_SESSION_CB);
int SSL_has_matching_session_id(const SSL *ssl, const unsigned char *id,
unsigned int id_len);
SSL_SESSION *d2i_SSL_SESSION(SSL_SESSION **a, const unsigned char **pp,
long length);
# ifdef HEADER_X509_H
X509 *SSL_get_peer_certificate(const SSL *s);
# endif
STACK_OF(X509) *SSL_get_peer_cert_chain(const SSL *s);
int SSL_CTX_get_verify_mode(const SSL_CTX *ctx);
int SSL_CTX_get_verify_depth(const SSL_CTX *ctx);
int (*SSL_CTX_get_verify_callback(const SSL_CTX *ctx)) (int,
X509_STORE_CTX *);
void SSL_CTX_set_verify(SSL_CTX *ctx, int mode,
int (*callback) (int, X509_STORE_CTX *));
void SSL_CTX_set_verify_depth(SSL_CTX *ctx, int depth);
void SSL_CTX_set_cert_verify_callback(SSL_CTX *ctx,
int (*cb) (X509_STORE_CTX *, void *),
void *arg);
void SSL_CTX_set_cert_cb(SSL_CTX *c, int (*cb) (SSL *ssl, void *arg),
void *arg);
# ifndef OPENSSL_NO_RSA
int SSL_CTX_use_RSAPrivateKey(SSL_CTX *ctx, RSA *rsa);
# endif
int SSL_CTX_use_RSAPrivateKey_ASN1(SSL_CTX *ctx, const unsigned char *d,
long len);
int SSL_CTX_use_PrivateKey(SSL_CTX *ctx, EVP_PKEY *pkey);
int SSL_CTX_use_PrivateKey_ASN1(int pk, SSL_CTX *ctx,
const unsigned char *d, long len);
int SSL_CTX_use_certificate(SSL_CTX *ctx, X509 *x);
int SSL_CTX_use_certificate_ASN1(SSL_CTX *ctx, int len,
const unsigned char *d);
void SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx, pem_password_cb *cb);
void SSL_CTX_set_default_passwd_cb_userdata(SSL_CTX *ctx, void *u);
int SSL_CTX_check_private_key(const SSL_CTX *ctx);
int SSL_check_private_key(const SSL *ctx);
int SSL_CTX_set_session_id_context(SSL_CTX *ctx, const unsigned char *sid_ctx,
unsigned int sid_ctx_len);
SSL *SSL_new(SSL_CTX *ctx);
int SSL_set_session_id_context(SSL *ssl, const unsigned char *sid_ctx,
unsigned int sid_ctx_len);
int SSL_CTX_set_purpose(SSL_CTX *s, int purpose);
int SSL_set_purpose(SSL *s, int purpose);
int SSL_CTX_set_trust(SSL_CTX *s, int trust);
int SSL_set_trust(SSL *s, int trust);
int SSL_CTX_set1_param(SSL_CTX *ctx, X509_VERIFY_PARAM *vpm);
int SSL_set1_param(SSL *ssl, X509_VERIFY_PARAM *vpm);
X509_VERIFY_PARAM *SSL_CTX_get0_param(SSL_CTX *ctx);
X509_VERIFY_PARAM *SSL_get0_param(SSL *ssl);
# ifndef OPENSSL_NO_SRP
int SSL_CTX_set_srp_username(SSL_CTX *ctx, char *name);
int SSL_CTX_set_srp_password(SSL_CTX *ctx, char *password);
int SSL_CTX_set_srp_strength(SSL_CTX *ctx, int strength);
int SSL_CTX_set_srp_client_pwd_callback(SSL_CTX *ctx,
char *(*cb) (SSL *, void *));
int SSL_CTX_set_srp_verify_param_callback(SSL_CTX *ctx,
int (*cb) (SSL *, void *));
int SSL_CTX_set_srp_username_callback(SSL_CTX *ctx,
int (*cb) (SSL *, int *, void *));
int SSL_CTX_set_srp_cb_arg(SSL_CTX *ctx, void *arg);
int SSL_set_srp_server_param(SSL *s, const BIGNUM *N, const BIGNUM *g,
BIGNUM *sa, BIGNUM *v, char *info);
int SSL_set_srp_server_param_pw(SSL *s, const char *user, const char *pass,
const char *grp);
BIGNUM *SSL_get_srp_g(SSL *s);
BIGNUM *SSL_get_srp_N(SSL *s);
char *SSL_get_srp_username(SSL *s);
char *SSL_get_srp_userinfo(SSL *s);
# endif
void SSL_certs_clear(SSL *s);
void SSL_free(SSL *ssl);
int SSL_accept(SSL *ssl);
int SSL_connect(SSL *ssl);
int SSL_read(SSL *ssl, void *buf, int num);
int SSL_peek(SSL *ssl, void *buf, int num);
int SSL_write(SSL *ssl, const void *buf, int num);
long SSL_ctrl(SSL *ssl, int cmd, long larg, void *parg);
long SSL_callback_ctrl(SSL *, int, void (*)(void));
long SSL_CTX_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg);
long SSL_CTX_callback_ctrl(SSL_CTX *, int, void (*)(void));
int SSL_get_error(const SSL *s, int ret_code);
const char *SSL_get_version(const SSL *s);
/* This sets the 'default' SSL version that SSL_new() will create */
int SSL_CTX_set_ssl_version(SSL_CTX *ctx, const SSL_METHOD *meth);
# ifndef OPENSSL_NO_SSL2_METHOD
const SSL_METHOD *SSLv2_method(void); /* SSLv2 */
const SSL_METHOD *SSLv2_server_method(void); /* SSLv2 */
const SSL_METHOD *SSLv2_client_method(void); /* SSLv2 */
# endif
# ifndef OPENSSL_NO_SSL3_METHOD
const SSL_METHOD *SSLv3_method(void); /* SSLv3 */
const SSL_METHOD *SSLv3_server_method(void); /* SSLv3 */
const SSL_METHOD *SSLv3_client_method(void); /* SSLv3 */
# endif
const SSL_METHOD *SSLv23_method(void); /* Negotiate highest available SSL/TLS
* version */
const SSL_METHOD *SSLv23_server_method(void); /* Negotiate highest available
* SSL/TLS version */
const SSL_METHOD *SSLv23_client_method(void); /* Negotiate highest available
* SSL/TLS version */
const SSL_METHOD *TLSv1_method(void); /* TLSv1.0 */
const SSL_METHOD *TLSv1_server_method(void); /* TLSv1.0 */
const SSL_METHOD *TLSv1_client_method(void); /* TLSv1.0 */
const SSL_METHOD *TLSv1_1_method(void); /* TLSv1.1 */
const SSL_METHOD *TLSv1_1_server_method(void); /* TLSv1.1 */
const SSL_METHOD *TLSv1_1_client_method(void); /* TLSv1.1 */
const SSL_METHOD *TLSv1_2_method(void); /* TLSv1.2 */
const SSL_METHOD *TLSv1_2_server_method(void); /* TLSv1.2 */
const SSL_METHOD *TLSv1_2_client_method(void); /* TLSv1.2 */
const SSL_METHOD *DTLSv1_method(void); /* DTLSv1.0 */
const SSL_METHOD *DTLSv1_server_method(void); /* DTLSv1.0 */
const SSL_METHOD *DTLSv1_client_method(void); /* DTLSv1.0 */
const SSL_METHOD *DTLSv1_2_method(void); /* DTLSv1.2 */
const SSL_METHOD *DTLSv1_2_server_method(void); /* DTLSv1.2 */
const SSL_METHOD *DTLSv1_2_client_method(void); /* DTLSv1.2 */
const SSL_METHOD *DTLS_method(void); /* DTLS 1.0 and 1.2 */
const SSL_METHOD *DTLS_server_method(void); /* DTLS 1.0 and 1.2 */
const SSL_METHOD *DTLS_client_method(void); /* DTLS 1.0 and 1.2 */
STACK_OF(SSL_CIPHER) *SSL_get_ciphers(const SSL *s);
int SSL_do_handshake(SSL *s);
int SSL_renegotiate(SSL *s);
int SSL_renegotiate_abbreviated(SSL *s);
int SSL_renegotiate_pending(SSL *s);
int SSL_shutdown(SSL *s);
const SSL_METHOD *SSL_CTX_get_ssl_method(SSL_CTX *ctx);
const SSL_METHOD *SSL_get_ssl_method(SSL *s);
int SSL_set_ssl_method(SSL *s, const SSL_METHOD *method);
const char *SSL_alert_type_string_long(int value);
const char *SSL_alert_type_string(int value);
const char *SSL_alert_desc_string_long(int value);
const char *SSL_alert_desc_string(int value);
void SSL_set_client_CA_list(SSL *s, STACK_OF(X509_NAME) *name_list);
void SSL_CTX_set_client_CA_list(SSL_CTX *ctx, STACK_OF(X509_NAME) *name_list);
STACK_OF(X509_NAME) *SSL_get_client_CA_list(const SSL *s);
STACK_OF(X509_NAME) *SSL_CTX_get_client_CA_list(const SSL_CTX *s);
int SSL_add_client_CA(SSL *ssl, X509 *x);
int SSL_CTX_add_client_CA(SSL_CTX *ctx, X509 *x);
void SSL_set_connect_state(SSL *s);
void SSL_set_accept_state(SSL *s);
long SSL_get_default_timeout(const SSL *s);
int SSL_library_init(void);
char *SSL_CIPHER_description(const SSL_CIPHER *, char *buf, int size);
STACK_OF(X509_NAME) *SSL_dup_CA_list(STACK_OF(X509_NAME) *sk);
SSL *SSL_dup(SSL *ssl);
X509 *SSL_get_certificate(const SSL *ssl);
/*
* EVP_PKEY
*/ struct evp_pkey_st *SSL_get_privatekey(const SSL *ssl);
X509 *SSL_CTX_get0_certificate(const SSL_CTX *ctx);
EVP_PKEY *SSL_CTX_get0_privatekey(const SSL_CTX *ctx);
void SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx, int mode);
int SSL_CTX_get_quiet_shutdown(const SSL_CTX *ctx);
void SSL_set_quiet_shutdown(SSL *ssl, int mode);
int SSL_get_quiet_shutdown(const SSL *ssl);
void SSL_set_shutdown(SSL *ssl, int mode);
int SSL_get_shutdown(const SSL *ssl);
int SSL_version(const SSL *ssl);
int SSL_CTX_set_default_verify_paths(SSL_CTX *ctx);
int SSL_CTX_load_verify_locations(SSL_CTX *ctx, const char *CAfile,
const char *CApath);
# define SSL_get0_session SSL_get_session/* just peek at pointer */
SSL_SESSION *SSL_get_session(const SSL *ssl);
SSL_SESSION *SSL_get1_session(SSL *ssl); /* obtain a reference count */
SSL_CTX *SSL_get_SSL_CTX(const SSL *ssl);
SSL_CTX *SSL_set_SSL_CTX(SSL *ssl, SSL_CTX *ctx);
void SSL_set_info_callback(SSL *ssl,
void (*cb) (const SSL *ssl, int type, int val));
void (*SSL_get_info_callback(const SSL *ssl)) (const SSL *ssl, int type,
int val);
int SSL_state(const SSL *ssl);
void SSL_set_state(SSL *ssl, int state);
void SSL_set_verify_result(SSL *ssl, long v);
long SSL_get_verify_result(const SSL *ssl);
int SSL_set_ex_data(SSL *ssl, int idx, void *data);
void *SSL_get_ex_data(const SSL *ssl, int idx);
int SSL_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func,
CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func);
int SSL_SESSION_set_ex_data(SSL_SESSION *ss, int idx, void *data);
void *SSL_SESSION_get_ex_data(const SSL_SESSION *ss, int idx);
int SSL_SESSION_get_ex_new_index(long argl, void *argp,
CRYPTO_EX_new *new_func,
CRYPTO_EX_dup *dup_func,
CRYPTO_EX_free *free_func);
int SSL_CTX_set_ex_data(SSL_CTX *ssl, int idx, void *data);
void *SSL_CTX_get_ex_data(const SSL_CTX *ssl, int idx);
int SSL_CTX_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func,
CRYPTO_EX_dup *dup_func,
CRYPTO_EX_free *free_func);
int SSL_get_ex_data_X509_STORE_CTX_idx(void);
# define SSL_CTX_sess_set_cache_size(ctx,t) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_SESS_CACHE_SIZE,t,NULL)
# define SSL_CTX_sess_get_cache_size(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_GET_SESS_CACHE_SIZE,0,NULL)
# define SSL_CTX_set_session_cache_mode(ctx,m) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_SESS_CACHE_MODE,m,NULL)
# define SSL_CTX_get_session_cache_mode(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_GET_SESS_CACHE_MODE,0,NULL)
# define SSL_CTX_get_default_read_ahead(ctx) SSL_CTX_get_read_ahead(ctx)
# define SSL_CTX_set_default_read_ahead(ctx,m) SSL_CTX_set_read_ahead(ctx,m)
# define SSL_CTX_get_read_ahead(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_GET_READ_AHEAD,0,NULL)
# define SSL_CTX_set_read_ahead(ctx,m) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_READ_AHEAD,m,NULL)
# define SSL_CTX_get_max_cert_list(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_GET_MAX_CERT_LIST,0,NULL)
# define SSL_CTX_set_max_cert_list(ctx,m) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_MAX_CERT_LIST,m,NULL)
# define SSL_get_max_cert_list(ssl) \
SSL_ctrl(ssl,SSL_CTRL_GET_MAX_CERT_LIST,0,NULL)
# define SSL_set_max_cert_list(ssl,m) \
SSL_ctrl(ssl,SSL_CTRL_SET_MAX_CERT_LIST,m,NULL)
# define SSL_CTX_set_max_send_fragment(ctx,m) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_MAX_SEND_FRAGMENT,m,NULL)
# define SSL_set_max_send_fragment(ssl,m) \
SSL_ctrl(ssl,SSL_CTRL_SET_MAX_SEND_FRAGMENT,m,NULL)
/* NB: the keylength is only applicable when is_export is true */
# ifndef OPENSSL_NO_RSA
void SSL_CTX_set_tmp_rsa_callback(SSL_CTX *ctx,
RSA *(*cb) (SSL *ssl, int is_export,
int keylength));
void SSL_set_tmp_rsa_callback(SSL *ssl,
RSA *(*cb) (SSL *ssl, int is_export,
int keylength));
# endif
# ifndef OPENSSL_NO_DH
void SSL_CTX_set_tmp_dh_callback(SSL_CTX *ctx,
DH *(*dh) (SSL *ssl, int is_export,
int keylength));
void SSL_set_tmp_dh_callback(SSL *ssl,
DH *(*dh) (SSL *ssl, int is_export,
int keylength));
# endif
# ifndef OPENSSL_NO_ECDH
void SSL_CTX_set_tmp_ecdh_callback(SSL_CTX *ctx,
EC_KEY *(*ecdh) (SSL *ssl, int is_export,
int keylength));
void SSL_set_tmp_ecdh_callback(SSL *ssl,
EC_KEY *(*ecdh) (SSL *ssl, int is_export,
int keylength));
# endif
const COMP_METHOD *SSL_get_current_compression(SSL *s);
const COMP_METHOD *SSL_get_current_expansion(SSL *s);
const char *SSL_COMP_get_name(const COMP_METHOD *comp);
STACK_OF(SSL_COMP) *SSL_COMP_get_compression_methods(void);
STACK_OF(SSL_COMP) *SSL_COMP_set0_compression_methods(STACK_OF(SSL_COMP)
*meths);
void SSL_COMP_free_compression_methods(void);
int SSL_COMP_add_compression_method(int id, COMP_METHOD *cm);
const SSL_CIPHER *SSL_CIPHER_find(SSL *ssl, const unsigned char *ptr);
/* TLS extensions functions */
int SSL_set_session_ticket_ext(SSL *s, void *ext_data, int ext_len);
int SSL_set_session_ticket_ext_cb(SSL *s, tls_session_ticket_ext_cb_fn cb,
void *arg);
/* Pre-shared secret session resumption functions */
int SSL_set_session_secret_cb(SSL *s,
tls_session_secret_cb_fn tls_session_secret_cb,
void *arg);
void SSL_set_debug(SSL *s, int debug);
int SSL_cache_hit(SSL *s);
int SSL_is_server(SSL *s);
SSL_CONF_CTX *SSL_CONF_CTX_new(void);
int SSL_CONF_CTX_finish(SSL_CONF_CTX *cctx);
void SSL_CONF_CTX_free(SSL_CONF_CTX *cctx);
unsigned int SSL_CONF_CTX_set_flags(SSL_CONF_CTX *cctx, unsigned int flags);
unsigned int SSL_CONF_CTX_clear_flags(SSL_CONF_CTX *cctx, unsigned int flags);
int SSL_CONF_CTX_set1_prefix(SSL_CONF_CTX *cctx, const char *pre);
void SSL_CONF_CTX_set_ssl(SSL_CONF_CTX *cctx, SSL *ssl);
void SSL_CONF_CTX_set_ssl_ctx(SSL_CONF_CTX *cctx, SSL_CTX *ctx);
int SSL_CONF_cmd(SSL_CONF_CTX *cctx, const char *cmd, const char *value);
int SSL_CONF_cmd_argv(SSL_CONF_CTX *cctx, int *pargc, char ***pargv);
int SSL_CONF_cmd_value_type(SSL_CONF_CTX *cctx, const char *cmd);
# ifndef OPENSSL_NO_SSL_TRACE
void SSL_trace(int write_p, int version, int content_type,
const void *buf, size_t len, SSL *ssl, void *arg);
const char *SSL_CIPHER_standard_name(const SSL_CIPHER *c);
# endif
# ifndef OPENSSL_NO_UNIT_TEST
const struct openssl_ssl_test_functions *SSL_test_functions(void);
# endif
/* BEGIN ERROR CODES */
/*
* The following lines are auto generated by the script mkerr.pl. Any changes
* made after this point may be overwritten when the script is next run.
*/
void ERR_load_SSL_strings(void);
/* Error codes for the SSL functions. */
/* Function codes. */
# define SSL_F_CHECK_SUITEB_CIPHER_LIST 331
# define SSL_F_CLIENT_CERTIFICATE 100
# define SSL_F_CLIENT_FINISHED 167
# define SSL_F_CLIENT_HELLO 101
# define SSL_F_CLIENT_MASTER_KEY 102
# define SSL_F_D2I_SSL_SESSION 103
# define SSL_F_DO_DTLS1_WRITE 245
# define SSL_F_DO_SSL3_WRITE 104
# define SSL_F_DTLS1_ACCEPT 246
# define SSL_F_DTLS1_ADD_CERT_TO_BUF 295
# define SSL_F_DTLS1_BUFFER_RECORD 247
# define SSL_F_DTLS1_CHECK_TIMEOUT_NUM 316
# define SSL_F_DTLS1_CLIENT_HELLO 248
# define SSL_F_DTLS1_CONNECT 249
# define SSL_F_DTLS1_ENC 250
# define SSL_F_DTLS1_GET_HELLO_VERIFY 251
# define SSL_F_DTLS1_GET_MESSAGE 252
# define SSL_F_DTLS1_GET_MESSAGE_FRAGMENT 253
# define SSL_F_DTLS1_GET_RECORD 254
# define SSL_F_DTLS1_HANDLE_TIMEOUT 297
# define SSL_F_DTLS1_HEARTBEAT 305
# define SSL_F_DTLS1_OUTPUT_CERT_CHAIN 255
# define SSL_F_DTLS1_PREPROCESS_FRAGMENT 288
# define SSL_F_DTLS1_PROCESS_BUFFERED_RECORDS 424
# define SSL_F_DTLS1_PROCESS_OUT_OF_SEQ_MESSAGE 256
# define SSL_F_DTLS1_PROCESS_RECORD 257
# define SSL_F_DTLS1_READ_BYTES 258
# define SSL_F_DTLS1_READ_FAILED 259
# define SSL_F_DTLS1_SEND_CERTIFICATE_REQUEST 260
# define SSL_F_DTLS1_SEND_CLIENT_CERTIFICATE 261
# define SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE 262
# define SSL_F_DTLS1_SEND_CLIENT_VERIFY 263
# define SSL_F_DTLS1_SEND_HELLO_VERIFY_REQUEST 264
# define SSL_F_DTLS1_SEND_SERVER_CERTIFICATE 265
# define SSL_F_DTLS1_SEND_SERVER_HELLO 266
# define SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE 267
# define SSL_F_DTLS1_WRITE_APP_DATA_BYTES 268
# define SSL_F_GET_CLIENT_FINISHED 105
# define SSL_F_GET_CLIENT_HELLO 106
# define SSL_F_GET_CLIENT_MASTER_KEY 107
# define SSL_F_GET_SERVER_FINISHED 108
# define SSL_F_GET_SERVER_HELLO 109
# define SSL_F_GET_SERVER_STATIC_DH_KEY 340
# define SSL_F_GET_SERVER_VERIFY 110
# define SSL_F_I2D_SSL_SESSION 111
# define SSL_F_READ_N 112
# define SSL_F_REQUEST_CERTIFICATE 113
# define SSL_F_SERVER_FINISH 239
# define SSL_F_SERVER_HELLO 114
# define SSL_F_SERVER_VERIFY 240
# define SSL_F_SSL23_ACCEPT 115
# define SSL_F_SSL23_CLIENT_HELLO 116
# define SSL_F_SSL23_CONNECT 117
# define SSL_F_SSL23_GET_CLIENT_HELLO 118
# define SSL_F_SSL23_GET_SERVER_HELLO 119
# define SSL_F_SSL23_PEEK 237
# define SSL_F_SSL23_READ 120
# define SSL_F_SSL23_WRITE 121
# define SSL_F_SSL2_ACCEPT 122
# define SSL_F_SSL2_CONNECT 123
# define SSL_F_SSL2_ENC_INIT 124
# define SSL_F_SSL2_GENERATE_KEY_MATERIAL 241
# define SSL_F_SSL2_PEEK 234
# define SSL_F_SSL2_READ 125
# define SSL_F_SSL2_READ_INTERNAL 236
# define SSL_F_SSL2_SET_CERTIFICATE 126
# define SSL_F_SSL2_WRITE 127
# define SSL_F_SSL3_ACCEPT 128
# define SSL_F_SSL3_ADD_CERT_TO_BUF 296
# define SSL_F_SSL3_CALLBACK_CTRL 233
# define SSL_F_SSL3_CHANGE_CIPHER_STATE 129
# define SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM 130
# define SSL_F_SSL3_CHECK_CLIENT_HELLO 304
# define SSL_F_SSL3_CHECK_FINISHED 339
# define SSL_F_SSL3_CLIENT_HELLO 131
# define SSL_F_SSL3_CONNECT 132
# define SSL_F_SSL3_CTRL 213
# define SSL_F_SSL3_CTX_CTRL 133
# define SSL_F_SSL3_DIGEST_CACHED_RECORDS 293
# define SSL_F_SSL3_DO_CHANGE_CIPHER_SPEC 292
# define SSL_F_SSL3_ENC 134
# define SSL_F_SSL3_GENERATE_KEY_BLOCK 238
# define SSL_F_SSL3_GENERATE_MASTER_SECRET 388
# define SSL_F_SSL3_GET_CERTIFICATE_REQUEST 135
# define SSL_F_SSL3_GET_CERT_STATUS 289
# define SSL_F_SSL3_GET_CERT_VERIFY 136
# define SSL_F_SSL3_GET_CLIENT_CERTIFICATE 137
# define SSL_F_SSL3_GET_CLIENT_HELLO 138
# define SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE 139
# define SSL_F_SSL3_GET_FINISHED 140
# define SSL_F_SSL3_GET_KEY_EXCHANGE 141
# define SSL_F_SSL3_GET_MESSAGE 142
# define SSL_F_SSL3_GET_NEW_SESSION_TICKET 283
# define SSL_F_SSL3_GET_NEXT_PROTO 306
# define SSL_F_SSL3_GET_RECORD 143
# define SSL_F_SSL3_GET_SERVER_CERTIFICATE 144
# define SSL_F_SSL3_GET_SERVER_DONE 145
# define SSL_F_SSL3_GET_SERVER_HELLO 146
# define SSL_F_SSL3_HANDSHAKE_MAC 285
# define SSL_F_SSL3_NEW_SESSION_TICKET 287
# define SSL_F_SSL3_OUTPUT_CERT_CHAIN 147
# define SSL_F_SSL3_PEEK 235
# define SSL_F_SSL3_READ_BYTES 148
# define SSL_F_SSL3_READ_N 149
# define SSL_F_SSL3_SEND_CERTIFICATE_REQUEST 150
# define SSL_F_SSL3_SEND_CLIENT_CERTIFICATE 151
# define SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE 152
# define SSL_F_SSL3_SEND_CLIENT_VERIFY 153
# define SSL_F_SSL3_SEND_SERVER_CERTIFICATE 154
# define SSL_F_SSL3_SEND_SERVER_HELLO 242
# define SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE 155
# define SSL_F_SSL3_SETUP_KEY_BLOCK 157
# define SSL_F_SSL3_SETUP_READ_BUFFER 156
# define SSL_F_SSL3_SETUP_WRITE_BUFFER 291
# define SSL_F_SSL3_WRITE_BYTES 158
# define SSL_F_SSL3_WRITE_PENDING 159
# define SSL_F_SSL_ADD_CERT_CHAIN 318
# define SSL_F_SSL_ADD_CERT_TO_BUF 319
# define SSL_F_SSL_ADD_CLIENTHELLO_RENEGOTIATE_EXT 298
# define SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT 277
# define SSL_F_SSL_ADD_CLIENTHELLO_USE_SRTP_EXT 307
# define SSL_F_SSL_ADD_DIR_CERT_SUBJECTS_TO_STACK 215
# define SSL_F_SSL_ADD_FILE_CERT_SUBJECTS_TO_STACK 216
# define SSL_F_SSL_ADD_SERVERHELLO_RENEGOTIATE_EXT 299
# define SSL_F_SSL_ADD_SERVERHELLO_TLSEXT 278
# define SSL_F_SSL_ADD_SERVERHELLO_USE_SRTP_EXT 308
# define SSL_F_SSL_BAD_METHOD 160
# define SSL_F_SSL_BUILD_CERT_CHAIN 332
# define SSL_F_SSL_BYTES_TO_CIPHER_LIST 161
# define SSL_F_SSL_CERT_DUP 221
# define SSL_F_SSL_CERT_INST 222
# define SSL_F_SSL_CERT_INSTANTIATE 214
# define SSL_F_SSL_CERT_NEW 162
# define SSL_F_SSL_CHECK_PRIVATE_KEY 163
# define SSL_F_SSL_CHECK_SERVERHELLO_TLSEXT 280
# define SSL_F_SSL_CHECK_SRVR_ECC_CERT_AND_ALG 279
# define SSL_F_SSL_CIPHER_PROCESS_RULESTR 230
# define SSL_F_SSL_CIPHER_STRENGTH_SORT 231
# define SSL_F_SSL_CLEAR 164
# define SSL_F_SSL_COMP_ADD_COMPRESSION_METHOD 165
# define SSL_F_SSL_CONF_CMD 334
# define SSL_F_SSL_CREATE_CIPHER_LIST 166
# define SSL_F_SSL_CTRL 232
# define SSL_F_SSL_CTX_CHECK_PRIVATE_KEY 168
# define SSL_F_SSL_CTX_MAKE_PROFILES 309
# define SSL_F_SSL_CTX_NEW 169
# define SSL_F_SSL_CTX_SET_CIPHER_LIST 269
# define SSL_F_SSL_CTX_SET_CLIENT_CERT_ENGINE 290
# define SSL_F_SSL_CTX_SET_PURPOSE 226
# define SSL_F_SSL_CTX_SET_SESSION_ID_CONTEXT 219
# define SSL_F_SSL_CTX_SET_SSL_VERSION 170
# define SSL_F_SSL_CTX_SET_TRUST 229
# define SSL_F_SSL_CTX_USE_CERTIFICATE 171
# define SSL_F_SSL_CTX_USE_CERTIFICATE_ASN1 172
# define SSL_F_SSL_CTX_USE_CERTIFICATE_CHAIN_FILE 220
# define SSL_F_SSL_CTX_USE_CERTIFICATE_FILE 173
# define SSL_F_SSL_CTX_USE_PRIVATEKEY 174
# define SSL_F_SSL_CTX_USE_PRIVATEKEY_ASN1 175
# define SSL_F_SSL_CTX_USE_PRIVATEKEY_FILE 176
# define SSL_F_SSL_CTX_USE_PSK_IDENTITY_HINT 272
# define SSL_F_SSL_CTX_USE_RSAPRIVATEKEY 177
# define SSL_F_SSL_CTX_USE_RSAPRIVATEKEY_ASN1 178
# define SSL_F_SSL_CTX_USE_RSAPRIVATEKEY_FILE 179
# define SSL_F_SSL_CTX_USE_SERVERINFO 336
# define SSL_F_SSL_CTX_USE_SERVERINFO_FILE 337
# define SSL_F_SSL_DO_HANDSHAKE 180
# define SSL_F_SSL_GET_NEW_SESSION 181
# define SSL_F_SSL_GET_PREV_SESSION 217
# define SSL_F_SSL_GET_SERVER_CERT_INDEX 322
# define SSL_F_SSL_GET_SERVER_SEND_CERT 182
# define SSL_F_SSL_GET_SERVER_SEND_PKEY 317
# define SSL_F_SSL_GET_SIGN_PKEY 183
# define SSL_F_SSL_INIT_WBIO_BUFFER 184
# define SSL_F_SSL_LOAD_CLIENT_CA_FILE 185
# define SSL_F_SSL_NEW 186
# define SSL_F_SSL_PARSE_CLIENTHELLO_RENEGOTIATE_EXT 300
# define SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT 302
# define SSL_F_SSL_PARSE_CLIENTHELLO_USE_SRTP_EXT 310
# define SSL_F_SSL_PARSE_SERVERHELLO_RENEGOTIATE_EXT 301
# define SSL_F_SSL_PARSE_SERVERHELLO_TLSEXT 303
# define SSL_F_SSL_PARSE_SERVERHELLO_USE_SRTP_EXT 311
# define SSL_F_SSL_PEEK 270
# define SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT 281
# define SSL_F_SSL_PREPARE_SERVERHELLO_TLSEXT 282
# define SSL_F_SSL_READ 223
# define SSL_F_SSL_RSA_PRIVATE_DECRYPT 187
# define SSL_F_SSL_RSA_PUBLIC_ENCRYPT 188
# define SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT 320
# define SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT 321
# define SSL_F_SSL_SESSION_DUP 348
# define SSL_F_SSL_SESSION_NEW 189
# define SSL_F_SSL_SESSION_PRINT_FP 190
# define SSL_F_SSL_SESSION_SET1_ID_CONTEXT 312
# define SSL_F_SSL_SESS_CERT_NEW 225
# define SSL_F_SSL_SET_CERT 191
# define SSL_F_SSL_SET_CIPHER_LIST 271
# define SSL_F_SSL_SET_FD 192
# define SSL_F_SSL_SET_PKEY 193
# define SSL_F_SSL_SET_PURPOSE 227
# define SSL_F_SSL_SET_RFD 194
# define SSL_F_SSL_SET_SESSION 195
# define SSL_F_SSL_SET_SESSION_ID_CONTEXT 218
# define SSL_F_SSL_SET_SESSION_TICKET_EXT 294
# define SSL_F_SSL_SET_TRUST 228
# define SSL_F_SSL_SET_WFD 196
# define SSL_F_SSL_SHUTDOWN 224
# define SSL_F_SSL_SRP_CTX_INIT 313
# define SSL_F_SSL_UNDEFINED_CONST_FUNCTION 243
# define SSL_F_SSL_UNDEFINED_FUNCTION 197
# define SSL_F_SSL_UNDEFINED_VOID_FUNCTION 244
# define SSL_F_SSL_USE_CERTIFICATE 198
# define SSL_F_SSL_USE_CERTIFICATE_ASN1 199
# define SSL_F_SSL_USE_CERTIFICATE_FILE 200
# define SSL_F_SSL_USE_PRIVATEKEY 201
# define SSL_F_SSL_USE_PRIVATEKEY_ASN1 202
# define SSL_F_SSL_USE_PRIVATEKEY_FILE 203
# define SSL_F_SSL_USE_PSK_IDENTITY_HINT 273
# define SSL_F_SSL_USE_RSAPRIVATEKEY 204
# define SSL_F_SSL_USE_RSAPRIVATEKEY_ASN1 205
# define SSL_F_SSL_USE_RSAPRIVATEKEY_FILE 206
# define SSL_F_SSL_VERIFY_CERT_CHAIN 207
# define SSL_F_SSL_WRITE 208
# define SSL_F_TLS12_CHECK_PEER_SIGALG 333
# define SSL_F_TLS1_CERT_VERIFY_MAC 286
# define SSL_F_TLS1_CHANGE_CIPHER_STATE 209
# define SSL_F_TLS1_CHECK_SERVERHELLO_TLSEXT 274
# define SSL_F_TLS1_ENC 210
# define SSL_F_TLS1_EXPORT_KEYING_MATERIAL 314
# define SSL_F_TLS1_GET_CURVELIST 338
# define SSL_F_TLS1_HEARTBEAT 315
# define SSL_F_TLS1_PREPARE_CLIENTHELLO_TLSEXT 275
# define SSL_F_TLS1_PREPARE_SERVERHELLO_TLSEXT 276
# define SSL_F_TLS1_PRF 284
# define SSL_F_TLS1_SETUP_KEY_BLOCK 211
# define SSL_F_TLS1_SET_SERVER_SIGALGS 335
# define SSL_F_WRITE_PENDING 212
/* Reason codes. */
# define SSL_R_APP_DATA_IN_HANDSHAKE 100
# define SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT 272
# define SSL_R_BAD_ALERT_RECORD 101
# define SSL_R_BAD_AUTHENTICATION_TYPE 102
# define SSL_R_BAD_CHANGE_CIPHER_SPEC 103
# define SSL_R_BAD_CHECKSUM 104
# define SSL_R_BAD_DATA 390
# define SSL_R_BAD_DATA_RETURNED_BY_CALLBACK 106
# define SSL_R_BAD_DECOMPRESSION 107
# define SSL_R_BAD_DH_G_LENGTH 108
# define SSL_R_BAD_DH_G_VALUE 375
# define SSL_R_BAD_DH_PUB_KEY_LENGTH 109
# define SSL_R_BAD_DH_PUB_KEY_VALUE 393
# define SSL_R_BAD_DH_P_LENGTH 110
# define SSL_R_BAD_DH_P_VALUE 395
# define SSL_R_BAD_DIGEST_LENGTH 111
# define SSL_R_BAD_DSA_SIGNATURE 112
# define SSL_R_BAD_ECC_CERT 304
# define SSL_R_BAD_ECDSA_SIGNATURE 305
# define SSL_R_BAD_ECPOINT 306
# define SSL_R_BAD_HANDSHAKE_LENGTH 332
# define SSL_R_BAD_HELLO_REQUEST 105
# define SSL_R_BAD_LENGTH 271
# define SSL_R_BAD_MAC_DECODE 113
# define SSL_R_BAD_MAC_LENGTH 333
# define SSL_R_BAD_MESSAGE_TYPE 114
# define SSL_R_BAD_PACKET_LENGTH 115
# define SSL_R_BAD_PROTOCOL_VERSION_NUMBER 116
# define SSL_R_BAD_PSK_IDENTITY_HINT_LENGTH 316
# define SSL_R_BAD_RESPONSE_ARGUMENT 117
# define SSL_R_BAD_RSA_DECRYPT 118
# define SSL_R_BAD_RSA_ENCRYPT 119
# define SSL_R_BAD_RSA_E_LENGTH 120
# define SSL_R_BAD_RSA_MODULUS_LENGTH 121
# define SSL_R_BAD_RSA_SIGNATURE 122
# define SSL_R_BAD_SIGNATURE 123
# define SSL_R_BAD_SRP_A_LENGTH 347
# define SSL_R_BAD_SRP_B_LENGTH 348
# define SSL_R_BAD_SRP_G_LENGTH 349
# define SSL_R_BAD_SRP_N_LENGTH 350
# define SSL_R_BAD_SRP_PARAMETERS 371
# define SSL_R_BAD_SRP_S_LENGTH 351
# define SSL_R_BAD_SRTP_MKI_VALUE 352
# define SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST 353
# define SSL_R_BAD_SSL_FILETYPE 124
# define SSL_R_BAD_SSL_SESSION_ID_LENGTH 125
# define SSL_R_BAD_STATE 126
# define SSL_R_BAD_VALUE 384
# define SSL_R_BAD_WRITE_RETRY 127
# define SSL_R_BIO_NOT_SET 128
# define SSL_R_BLOCK_CIPHER_PAD_IS_WRONG 129
# define SSL_R_BN_LIB 130
# define SSL_R_CA_DN_LENGTH_MISMATCH 131
# define SSL_R_CA_DN_TOO_LONG 132
# define SSL_R_CCS_RECEIVED_EARLY 133
# define SSL_R_CERTIFICATE_VERIFY_FAILED 134
# define SSL_R_CERT_CB_ERROR 377
# define SSL_R_CERT_LENGTH_MISMATCH 135
# define SSL_R_CHALLENGE_IS_DIFFERENT 136
# define SSL_R_CIPHER_CODE_WRONG_LENGTH 137
# define SSL_R_CIPHER_OR_HASH_UNAVAILABLE 138
# define SSL_R_CIPHER_TABLE_SRC_ERROR 139
# define SSL_R_CLIENTHELLO_TLSEXT 226
# define SSL_R_COMPRESSED_LENGTH_TOO_LONG 140
# define SSL_R_COMPRESSION_DISABLED 343
# define SSL_R_COMPRESSION_FAILURE 141
# define SSL_R_COMPRESSION_ID_NOT_WITHIN_PRIVATE_RANGE 307
# define SSL_R_COMPRESSION_LIBRARY_ERROR 142
# define SSL_R_CONNECTION_ID_IS_DIFFERENT 143
# define SSL_R_CONNECTION_TYPE_NOT_SET 144
# define SSL_R_COOKIE_MISMATCH 308
# define SSL_R_DATA_BETWEEN_CCS_AND_FINISHED 145
# define SSL_R_DATA_LENGTH_TOO_LONG 146
# define SSL_R_DECRYPTION_FAILED 147
# define SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC 281
# define SSL_R_DH_KEY_TOO_SMALL 372
# define SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG 148
# define SSL_R_DIGEST_CHECK_FAILED 149
# define SSL_R_DTLS_MESSAGE_TOO_BIG 334
# define SSL_R_DUPLICATE_COMPRESSION_ID 309
# define SSL_R_ECC_CERT_NOT_FOR_KEY_AGREEMENT 317
# define SSL_R_ECC_CERT_NOT_FOR_SIGNING 318
# define SSL_R_ECC_CERT_SHOULD_HAVE_RSA_SIGNATURE 322
# define SSL_R_ECC_CERT_SHOULD_HAVE_SHA1_SIGNATURE 323
# define SSL_R_ECDH_REQUIRED_FOR_SUITEB_MODE 374
# define SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER 310
# define SSL_R_EMPTY_SRTP_PROTECTION_PROFILE_LIST 354
# define SSL_R_ENCRYPTED_LENGTH_TOO_LONG 150
# define SSL_R_ERROR_GENERATING_TMP_RSA_KEY 282
# define SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST 151
# define SSL_R_EXCESSIVE_MESSAGE_SIZE 152
# define SSL_R_EXTRA_DATA_IN_MESSAGE 153
# define SSL_R_GOT_A_FIN_BEFORE_A_CCS 154
# define SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS 355
# define SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION 356
# define SSL_R_HTTPS_PROXY_REQUEST 155
# define SSL_R_HTTP_REQUEST 156
# define SSL_R_ILLEGAL_PADDING 283
# define SSL_R_ILLEGAL_SUITEB_DIGEST 380
# define SSL_R_INAPPROPRIATE_FALLBACK 373
# define SSL_R_INCONSISTENT_COMPRESSION 340
# define SSL_R_INVALID_CHALLENGE_LENGTH 158
# define SSL_R_INVALID_COMMAND 280
# define SSL_R_INVALID_COMPRESSION_ALGORITHM 341
# define SSL_R_INVALID_NULL_CMD_NAME 385
# define SSL_R_INVALID_PURPOSE 278
# define SSL_R_INVALID_SERVERINFO_DATA 388
# define SSL_R_INVALID_SRP_USERNAME 357
# define SSL_R_INVALID_STATUS_RESPONSE 328
# define SSL_R_INVALID_TICKET_KEYS_LENGTH 325
# define SSL_R_INVALID_TRUST 279
# define SSL_R_KEY_ARG_TOO_LONG 284
# define SSL_R_KRB5 285
# define SSL_R_KRB5_C_CC_PRINC 286
# define SSL_R_KRB5_C_GET_CRED 287
# define SSL_R_KRB5_C_INIT 288
# define SSL_R_KRB5_C_MK_REQ 289
# define SSL_R_KRB5_S_BAD_TICKET 290
# define SSL_R_KRB5_S_INIT 291
# define SSL_R_KRB5_S_RD_REQ 292
# define SSL_R_KRB5_S_TKT_EXPIRED 293
# define SSL_R_KRB5_S_TKT_NYV 294
# define SSL_R_KRB5_S_TKT_SKEW 295
# define SSL_R_LENGTH_MISMATCH 159
# define SSL_R_LENGTH_TOO_SHORT 160
# define SSL_R_LIBRARY_BUG 274
# define SSL_R_LIBRARY_HAS_NO_CIPHERS 161
# define SSL_R_MESSAGE_TOO_LONG 296
# define SSL_R_MISSING_DH_DSA_CERT 162
# define SSL_R_MISSING_DH_KEY 163
# define SSL_R_MISSING_DH_RSA_CERT 164
# define SSL_R_MISSING_DSA_SIGNING_CERT 165
# define SSL_R_MISSING_ECDH_CERT 382
# define SSL_R_MISSING_ECDSA_SIGNING_CERT 381
# define SSL_R_MISSING_EXPORT_TMP_DH_KEY 166
# define SSL_R_MISSING_EXPORT_TMP_RSA_KEY 167
# define SSL_R_MISSING_RSA_CERTIFICATE 168
# define SSL_R_MISSING_RSA_ENCRYPTING_CERT 169
# define SSL_R_MISSING_RSA_SIGNING_CERT 170
# define SSL_R_MISSING_SRP_PARAM 358
# define SSL_R_MISSING_TMP_DH_KEY 171
# define SSL_R_MISSING_TMP_ECDH_KEY 311
# define SSL_R_MISSING_TMP_RSA_KEY 172
# define SSL_R_MISSING_TMP_RSA_PKEY 173
# define SSL_R_MISSING_VERIFY_MESSAGE 174
# define SSL_R_MULTIPLE_SGC_RESTARTS 346
# define SSL_R_NON_SSLV2_INITIAL_PACKET 175
# define SSL_R_NO_CERTIFICATES_RETURNED 176
# define SSL_R_NO_CERTIFICATE_ASSIGNED 177
# define SSL_R_NO_CERTIFICATE_RETURNED 178
# define SSL_R_NO_CERTIFICATE_SET 179
# define SSL_R_NO_CERTIFICATE_SPECIFIED 180
# define SSL_R_NO_CIPHERS_AVAILABLE 181
# define SSL_R_NO_CIPHERS_PASSED 182
# define SSL_R_NO_CIPHERS_SPECIFIED 183
# define SSL_R_NO_CIPHER_LIST 184
# define SSL_R_NO_CIPHER_MATCH 185
# define SSL_R_NO_CLIENT_CERT_METHOD 331
# define SSL_R_NO_CLIENT_CERT_RECEIVED 186
# define SSL_R_NO_COMPRESSION_SPECIFIED 187
# define SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER 330
# define SSL_R_NO_METHOD_SPECIFIED 188
# define SSL_R_NO_PEM_EXTENSIONS 389
# define SSL_R_NO_PRIVATEKEY 189
# define SSL_R_NO_PRIVATE_KEY_ASSIGNED 190
# define SSL_R_NO_PROTOCOLS_AVAILABLE 191
# define SSL_R_NO_PUBLICKEY 192
# define SSL_R_NO_RENEGOTIATION 339
# define SSL_R_NO_REQUIRED_DIGEST 324
# define SSL_R_NO_SHARED_CIPHER 193
# define SSL_R_NO_SHARED_SIGATURE_ALGORITHMS 376
# define SSL_R_NO_SRTP_PROFILES 359
# define SSL_R_NO_VERIFY_CALLBACK 194
# define SSL_R_NULL_SSL_CTX 195
# define SSL_R_NULL_SSL_METHOD_PASSED 196
# define SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED 197
# define SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED 344
# define SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE 387
# define SSL_R_ONLY_TLS_1_2_ALLOWED_IN_SUITEB_MODE 379
# define SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE 297
# define SSL_R_OPAQUE_PRF_INPUT_TOO_LONG 327
# define SSL_R_PACKET_LENGTH_TOO_LONG 198
# define SSL_R_PARSE_TLSEXT 227
# define SSL_R_PATH_TOO_LONG 270
# define SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE 199
# define SSL_R_PEER_ERROR 200
# define SSL_R_PEER_ERROR_CERTIFICATE 201
# define SSL_R_PEER_ERROR_NO_CERTIFICATE 202
# define SSL_R_PEER_ERROR_NO_CIPHER 203
# define SSL_R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE 204
# define SSL_R_PEM_NAME_BAD_PREFIX 391
# define SSL_R_PEM_NAME_TOO_SHORT 392
# define SSL_R_PRE_MAC_LENGTH_TOO_LONG 205
# define SSL_R_PROBLEMS_MAPPING_CIPHER_FUNCTIONS 206
# define SSL_R_PROTOCOL_IS_SHUTDOWN 207
# define SSL_R_PSK_IDENTITY_NOT_FOUND 223
# define SSL_R_PSK_NO_CLIENT_CB 224
# define SSL_R_PSK_NO_SERVER_CB 225
# define SSL_R_PUBLIC_KEY_ENCRYPT_ERROR 208
# define SSL_R_PUBLIC_KEY_IS_NOT_RSA 209
# define SSL_R_PUBLIC_KEY_NOT_RSA 210
# define SSL_R_READ_BIO_NOT_SET 211
# define SSL_R_READ_TIMEOUT_EXPIRED 312
# define SSL_R_READ_WRONG_PACKET_TYPE 212
# define SSL_R_RECORD_LENGTH_MISMATCH 213
# define SSL_R_RECORD_TOO_LARGE 214
# define SSL_R_RECORD_TOO_SMALL 298
# define SSL_R_RENEGOTIATE_EXT_TOO_LONG 335
# define SSL_R_RENEGOTIATION_ENCODING_ERR 336
# define SSL_R_RENEGOTIATION_MISMATCH 337
# define SSL_R_REQUIRED_CIPHER_MISSING 215
# define SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING 342
# define SSL_R_REUSE_CERT_LENGTH_NOT_ZERO 216
# define SSL_R_REUSE_CERT_TYPE_NOT_ZERO 217
# define SSL_R_REUSE_CIPHER_LIST_NOT_ZERO 218
# define SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING 345
# define SSL_R_SERVERHELLO_TLSEXT 275
# define SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED 277
# define SSL_R_SHORT_READ 219
# define SSL_R_SHUTDOWN_WHILE_IN_INIT 407
# define SSL_R_SIGNATURE_ALGORITHMS_ERROR 360
# define SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE 220
# define SSL_R_SRP_A_CALC 361
# define SSL_R_SRTP_COULD_NOT_ALLOCATE_PROFILES 362
# define SSL_R_SRTP_PROTECTION_PROFILE_LIST_TOO_LONG 363
# define SSL_R_SRTP_UNKNOWN_PROTECTION_PROFILE 364
# define SSL_R_SSL23_DOING_SESSION_ID_REUSE 221
# define SSL_R_SSL2_CONNECTION_ID_TOO_LONG 299
# define SSL_R_SSL3_EXT_INVALID_ECPOINTFORMAT 321
# define SSL_R_SSL3_EXT_INVALID_SERVERNAME 319
# define SSL_R_SSL3_EXT_INVALID_SERVERNAME_TYPE 320
# define SSL_R_SSL3_SESSION_ID_TOO_LONG 300
# define SSL_R_SSL3_SESSION_ID_TOO_SHORT 222
# define SSL_R_SSLV3_ALERT_BAD_CERTIFICATE 1042
# define SSL_R_SSLV3_ALERT_BAD_RECORD_MAC 1020
# define SSL_R_SSLV3_ALERT_CERTIFICATE_EXPIRED 1045
# define SSL_R_SSLV3_ALERT_CERTIFICATE_REVOKED 1044
# define SSL_R_SSLV3_ALERT_CERTIFICATE_UNKNOWN 1046
# define SSL_R_SSLV3_ALERT_DECOMPRESSION_FAILURE 1030
# define SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE 1040
# define SSL_R_SSLV3_ALERT_ILLEGAL_PARAMETER 1047
# define SSL_R_SSLV3_ALERT_NO_CERTIFICATE 1041
# define SSL_R_SSLV3_ALERT_UNEXPECTED_MESSAGE 1010
# define SSL_R_SSLV3_ALERT_UNSUPPORTED_CERTIFICATE 1043
# define SSL_R_SSL_CTX_HAS_NO_DEFAULT_SSL_VERSION 228
# define SSL_R_SSL_HANDSHAKE_FAILURE 229
# define SSL_R_SSL_LIBRARY_HAS_NO_CIPHERS 230
# define SSL_R_SSL_SESSION_ID_CALLBACK_FAILED 301
# define SSL_R_SSL_SESSION_ID_CONFLICT 302
# define SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG 273
# define SSL_R_SSL_SESSION_ID_HAS_BAD_LENGTH 303
# define SSL_R_SSL_SESSION_ID_IS_DIFFERENT 231
# define SSL_R_TLSV1_ALERT_ACCESS_DENIED 1049
# define SSL_R_TLSV1_ALERT_DECODE_ERROR 1050
# define SSL_R_TLSV1_ALERT_DECRYPTION_FAILED 1021
# define SSL_R_TLSV1_ALERT_DECRYPT_ERROR 1051
# define SSL_R_TLSV1_ALERT_EXPORT_RESTRICTION 1060
# define SSL_R_TLSV1_ALERT_INAPPROPRIATE_FALLBACK 1086
# define SSL_R_TLSV1_ALERT_INSUFFICIENT_SECURITY 1071
# define SSL_R_TLSV1_ALERT_INTERNAL_ERROR 1080
# define SSL_R_TLSV1_ALERT_NO_RENEGOTIATION 1100
# define SSL_R_TLSV1_ALERT_PROTOCOL_VERSION 1070
# define SSL_R_TLSV1_ALERT_RECORD_OVERFLOW 1022
# define SSL_R_TLSV1_ALERT_UNKNOWN_CA 1048
# define SSL_R_TLSV1_ALERT_USER_CANCELLED 1090
# define SSL_R_TLSV1_BAD_CERTIFICATE_HASH_VALUE 1114
# define SSL_R_TLSV1_BAD_CERTIFICATE_STATUS_RESPONSE 1113
# define SSL_R_TLSV1_CERTIFICATE_UNOBTAINABLE 1111
# define SSL_R_TLSV1_UNRECOGNIZED_NAME 1112
# define SSL_R_TLSV1_UNSUPPORTED_EXTENSION 1110
# define SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER 232
# define SSL_R_TLS_HEARTBEAT_PEER_DOESNT_ACCEPT 365
# define SSL_R_TLS_HEARTBEAT_PENDING 366
# define SSL_R_TLS_ILLEGAL_EXPORTER_LABEL 367
# define SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST 157
# define SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST 233
# define SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG 234
# define SSL_R_TOO_MANY_WARN_ALERTS 409
# define SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER 235
# define SSL_R_UNABLE_TO_DECODE_DH_CERTS 236
# define SSL_R_UNABLE_TO_DECODE_ECDH_CERTS 313
# define SSL_R_UNABLE_TO_EXTRACT_PUBLIC_KEY 237
# define SSL_R_UNABLE_TO_FIND_DH_PARAMETERS 238
# define SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS 314
# define SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS 239
# define SSL_R_UNABLE_TO_FIND_SSL_METHOD 240
# define SSL_R_UNABLE_TO_LOAD_SSL2_MD5_ROUTINES 241
# define SSL_R_UNABLE_TO_LOAD_SSL3_MD5_ROUTINES 242
# define SSL_R_UNABLE_TO_LOAD_SSL3_SHA1_ROUTINES 243
# define SSL_R_UNEXPECTED_MESSAGE 244
# define SSL_R_UNEXPECTED_RECORD 245
# define SSL_R_UNINITIALIZED 276
# define SSL_R_UNKNOWN_ALERT_TYPE 246
# define SSL_R_UNKNOWN_CERTIFICATE_TYPE 247
# define SSL_R_UNKNOWN_CIPHER_RETURNED 248
# define SSL_R_UNKNOWN_CIPHER_TYPE 249
# define SSL_R_UNKNOWN_CMD_NAME 386
# define SSL_R_UNKNOWN_DIGEST 368
# define SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE 250
# define SSL_R_UNKNOWN_PKEY_TYPE 251
# define SSL_R_UNKNOWN_PROTOCOL 252
# define SSL_R_UNKNOWN_REMOTE_ERROR_TYPE 253
# define SSL_R_UNKNOWN_SSL_VERSION 254
# define SSL_R_UNKNOWN_STATE 255
# define SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED 338
# define SSL_R_UNSUPPORTED_CIPHER 256
# define SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM 257
# define SSL_R_UNSUPPORTED_DIGEST_TYPE 326
# define SSL_R_UNSUPPORTED_ELLIPTIC_CURVE 315
# define SSL_R_UNSUPPORTED_PROTOCOL 258
# define SSL_R_UNSUPPORTED_SSL_VERSION 259
# define SSL_R_UNSUPPORTED_STATUS_TYPE 329
# define SSL_R_USE_SRTP_NOT_NEGOTIATED 369
# define SSL_R_WRITE_BIO_NOT_SET 260
# define SSL_R_WRONG_CERTIFICATE_TYPE 383
# define SSL_R_WRONG_CIPHER_RETURNED 261
# define SSL_R_WRONG_CURVE 378
# define SSL_R_WRONG_MESSAGE_TYPE 262
# define SSL_R_WRONG_NUMBER_OF_KEY_BITS 263
# define SSL_R_WRONG_SIGNATURE_LENGTH 264
# define SSL_R_WRONG_SIGNATURE_SIZE 265
# define SSL_R_WRONG_SIGNATURE_TYPE 370
# define SSL_R_WRONG_SSL_VERSION 266
# define SSL_R_WRONG_VERSION_NUMBER 267
# define SSL_R_X509_LIB 268
# define SSL_R_X509_VERIFICATION_SETUP_PROBLEMS 269
#ifdef __cplusplus
}
#endif
#endif
|
/* ssl/ssl.h */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
* Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/* ====================================================================
* Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
* ECC cipher suite support in OpenSSL originally developed by
* SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
*/
/* ====================================================================
* Copyright 2005 Nokia. All rights reserved.
*
* The portions of the attached software ("Contribution") is developed by
* Nokia Corporation and is licensed pursuant to the OpenSSL open source
* license.
*
* The Contribution, originally written by Mika Kousa and Pasi Eronen of
* Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
* support (see RFC 4279) to OpenSSL.
*
* No patent licenses or other rights except those expressly stated in
* the OpenSSL open source license shall be deemed granted or received
* expressly, by implication, estoppel, or otherwise.
*
* No assurances are provided by Nokia that the Contribution does not
* infringe the patent or other intellectual property rights of any third
* party or that the license provides you with all the necessary rights
* to make use of the Contribution.
*
* THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
* ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
* SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
* OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
* OTHERWISE.
*/
#ifndef HEADER_SSL_H
# define HEADER_SSL_H
# include <openssl/e_os2.h>
# ifndef OPENSSL_NO_COMP
# include <openssl/comp.h>
# endif
# ifndef OPENSSL_NO_BIO
# include <openssl/bio.h>
# endif
# ifndef OPENSSL_NO_DEPRECATED
# ifndef OPENSSL_NO_X509
# include <openssl/x509.h>
# endif
# include <openssl/crypto.h>
# include <openssl/lhash.h>
# include <openssl/buffer.h>
# endif
# include <openssl/pem.h>
# include <openssl/hmac.h>
# include <openssl/kssl.h>
# include <openssl/safestack.h>
# include <openssl/symhacks.h>
#ifdef __cplusplus
extern "C" {
#endif
/* SSLeay version number for ASN.1 encoding of the session information */
/*-
* Version 0 - initial version
* Version 1 - added the optional peer certificate
*/
# define SSL_SESSION_ASN1_VERSION 0x0001
/* text strings for the ciphers */
# define SSL_TXT_NULL_WITH_MD5 SSL2_TXT_NULL_WITH_MD5
# define SSL_TXT_RC4_128_WITH_MD5 SSL2_TXT_RC4_128_WITH_MD5
# define SSL_TXT_RC4_128_EXPORT40_WITH_MD5 SSL2_TXT_RC4_128_EXPORT40_WITH_MD5
# define SSL_TXT_RC2_128_CBC_WITH_MD5 SSL2_TXT_RC2_128_CBC_WITH_MD5
# define SSL_TXT_RC2_128_CBC_EXPORT40_WITH_MD5 SSL2_TXT_RC2_128_CBC_EXPORT40_WITH_MD5
# define SSL_TXT_IDEA_128_CBC_WITH_MD5 SSL2_TXT_IDEA_128_CBC_WITH_MD5
# define SSL_TXT_DES_64_CBC_WITH_MD5 SSL2_TXT_DES_64_CBC_WITH_MD5
# define SSL_TXT_DES_64_CBC_WITH_SHA SSL2_TXT_DES_64_CBC_WITH_SHA
# define SSL_TXT_DES_192_EDE3_CBC_WITH_MD5 SSL2_TXT_DES_192_EDE3_CBC_WITH_MD5
# define SSL_TXT_DES_192_EDE3_CBC_WITH_SHA SSL2_TXT_DES_192_EDE3_CBC_WITH_SHA
/*
* VRS Additional Kerberos5 entries
*/
# define SSL_TXT_KRB5_DES_64_CBC_SHA SSL3_TXT_KRB5_DES_64_CBC_SHA
# define SSL_TXT_KRB5_DES_192_CBC3_SHA SSL3_TXT_KRB5_DES_192_CBC3_SHA
# define SSL_TXT_KRB5_RC4_128_SHA SSL3_TXT_KRB5_RC4_128_SHA
# define SSL_TXT_KRB5_IDEA_128_CBC_SHA SSL3_TXT_KRB5_IDEA_128_CBC_SHA
# define SSL_TXT_KRB5_DES_64_CBC_MD5 SSL3_TXT_KRB5_DES_64_CBC_MD5
# define SSL_TXT_KRB5_DES_192_CBC3_MD5 SSL3_TXT_KRB5_DES_192_CBC3_MD5
# define SSL_TXT_KRB5_RC4_128_MD5 SSL3_TXT_KRB5_RC4_128_MD5
# define SSL_TXT_KRB5_IDEA_128_CBC_MD5 SSL3_TXT_KRB5_IDEA_128_CBC_MD5
# define SSL_TXT_KRB5_DES_40_CBC_SHA SSL3_TXT_KRB5_DES_40_CBC_SHA
# define SSL_TXT_KRB5_RC2_40_CBC_SHA SSL3_TXT_KRB5_RC2_40_CBC_SHA
# define SSL_TXT_KRB5_RC4_40_SHA SSL3_TXT_KRB5_RC4_40_SHA
# define SSL_TXT_KRB5_DES_40_CBC_MD5 SSL3_TXT_KRB5_DES_40_CBC_MD5
# define SSL_TXT_KRB5_RC2_40_CBC_MD5 SSL3_TXT_KRB5_RC2_40_CBC_MD5
# define SSL_TXT_KRB5_RC4_40_MD5 SSL3_TXT_KRB5_RC4_40_MD5
# define SSL_TXT_KRB5_DES_40_CBC_SHA SSL3_TXT_KRB5_DES_40_CBC_SHA
# define SSL_TXT_KRB5_DES_40_CBC_MD5 SSL3_TXT_KRB5_DES_40_CBC_MD5
# define SSL_TXT_KRB5_DES_64_CBC_SHA SSL3_TXT_KRB5_DES_64_CBC_SHA
# define SSL_TXT_KRB5_DES_64_CBC_MD5 SSL3_TXT_KRB5_DES_64_CBC_MD5
# define SSL_TXT_KRB5_DES_192_CBC3_SHA SSL3_TXT_KRB5_DES_192_CBC3_SHA
# define SSL_TXT_KRB5_DES_192_CBC3_MD5 SSL3_TXT_KRB5_DES_192_CBC3_MD5
# define SSL_MAX_KRB5_PRINCIPAL_LENGTH 256
# define SSL_MAX_SSL_SESSION_ID_LENGTH 32
# define SSL_MAX_SID_CTX_LENGTH 32
# define SSL_MIN_RSA_MODULUS_LENGTH_IN_BYTES (512/8)
# define SSL_MAX_KEY_ARG_LENGTH 8
# define SSL_MAX_MASTER_KEY_LENGTH 48
/* These are used to specify which ciphers to use and not to use */
# define SSL_TXT_EXP40 "EXPORT40"
# define SSL_TXT_EXP56 "EXPORT56"
# define SSL_TXT_LOW "LOW"
# define SSL_TXT_MEDIUM "MEDIUM"
# define SSL_TXT_HIGH "HIGH"
# define SSL_TXT_FIPS "FIPS"
# define SSL_TXT_kFZA "kFZA"/* unused! */
# define SSL_TXT_aFZA "aFZA"/* unused! */
# define SSL_TXT_eFZA "eFZA"/* unused! */
# define SSL_TXT_FZA "FZA"/* unused! */
# define SSL_TXT_aNULL "aNULL"
# define SSL_TXT_eNULL "eNULL"
# define SSL_TXT_NULL "NULL"
# define SSL_TXT_kRSA "kRSA"
# define SSL_TXT_kDHr "kDHr"
# define SSL_TXT_kDHd "kDHd"
# define SSL_TXT_kDH "kDH"
# define SSL_TXT_kEDH "kEDH"
# define SSL_TXT_kDHE "kDHE"/* alias for kEDH */
# define SSL_TXT_kKRB5 "kKRB5"
# define SSL_TXT_kECDHr "kECDHr"
# define SSL_TXT_kECDHe "kECDHe"
# define SSL_TXT_kECDH "kECDH"
# define SSL_TXT_kEECDH "kEECDH"
# define SSL_TXT_kECDHE "kECDHE"/* alias for kEECDH */
# define SSL_TXT_kPSK "kPSK"
# define SSL_TXT_kGOST "kGOST"
# define SSL_TXT_kSRP "kSRP"
# define SSL_TXT_aRSA "aRSA"
# define SSL_TXT_aDSS "aDSS"
# define SSL_TXT_aDH "aDH"
# define SSL_TXT_aECDH "aECDH"
# define SSL_TXT_aKRB5 "aKRB5"
# define SSL_TXT_aECDSA "aECDSA"
# define SSL_TXT_aPSK "aPSK"
# define SSL_TXT_aGOST94 "aGOST94"
# define SSL_TXT_aGOST01 "aGOST01"
# define SSL_TXT_aGOST "aGOST"
# define SSL_TXT_aSRP "aSRP"
# define SSL_TXT_DSS "DSS"
# define SSL_TXT_DH "DH"
# define SSL_TXT_EDH "EDH"/* same as "kEDH:-ADH" */
# define SSL_TXT_DHE "DHE"/* alias for EDH */
# define SSL_TXT_ADH "ADH"
# define SSL_TXT_RSA "RSA"
# define SSL_TXT_ECDH "ECDH"
# define SSL_TXT_EECDH "EECDH"/* same as "kEECDH:-AECDH" */
# define SSL_TXT_ECDHE "ECDHE"/* alias for ECDHE" */
# define SSL_TXT_AECDH "AECDH"
# define SSL_TXT_ECDSA "ECDSA"
# define SSL_TXT_KRB5 "KRB5"
# define SSL_TXT_PSK "PSK"
# define SSL_TXT_SRP "SRP"
# define SSL_TXT_DES "DES"
# define SSL_TXT_3DES "3DES"
# define SSL_TXT_RC4 "RC4"
# define SSL_TXT_RC2 "RC2"
# define SSL_TXT_IDEA "IDEA"
# define SSL_TXT_SEED "SEED"
# define SSL_TXT_AES128 "AES128"
# define SSL_TXT_AES256 "AES256"
# define SSL_TXT_AES "AES"
# define SSL_TXT_AES_GCM "AESGCM"
# define SSL_TXT_CAMELLIA128 "CAMELLIA128"
# define SSL_TXT_CAMELLIA256 "CAMELLIA256"
# define SSL_TXT_CAMELLIA "CAMELLIA"
# define SSL_TXT_MD5 "MD5"
# define SSL_TXT_SHA1 "SHA1"
# define SSL_TXT_SHA "SHA"/* same as "SHA1" */
# define SSL_TXT_GOST94 "GOST94"
# define SSL_TXT_GOST89MAC "GOST89MAC"
# define SSL_TXT_SHA256 "SHA256"
# define SSL_TXT_SHA384 "SHA384"
# define SSL_TXT_SSLV2 "SSLv2"
# define SSL_TXT_SSLV3 "SSLv3"
# define SSL_TXT_TLSV1 "TLSv1"
# define SSL_TXT_TLSV1_1 "TLSv1.1"
# define SSL_TXT_TLSV1_2 "TLSv1.2"
# define SSL_TXT_EXP "EXP"
# define SSL_TXT_EXPORT "EXPORT"
# define SSL_TXT_ALL "ALL"
/*-
* COMPLEMENTOF* definitions. These identifiers are used to (de-select)
* ciphers normally not being used.
* Example: "RC4" will activate all ciphers using RC4 including ciphers
* without authentication, which would normally disabled by DEFAULT (due
* the "!ADH" being part of default). Therefore "RC4:!COMPLEMENTOFDEFAULT"
* will make sure that it is also disabled in the specific selection.
* COMPLEMENTOF* identifiers are portable between version, as adjustments
* to the default cipher setup will also be included here.
*
* COMPLEMENTOFDEFAULT does not experience the same special treatment that
* DEFAULT gets, as only selection is being done and no sorting as needed
* for DEFAULT.
*/
# define SSL_TXT_CMPALL "COMPLEMENTOFALL"
# define SSL_TXT_CMPDEF "COMPLEMENTOFDEFAULT"
/*
* The following cipher list is used by default. It also is substituted when
* an application-defined cipher list string starts with 'DEFAULT'.
*/
# define SSL_DEFAULT_CIPHER_LIST "ALL:!EXPORT:!LOW:!aNULL:!eNULL:!SSLv2"
/*
* As of OpenSSL 1.0.0, ssl_create_cipher_list() in ssl/ssl_ciph.c always
* starts with a reasonable order, and all we have to do for DEFAULT is
* throwing out anonymous and unencrypted ciphersuites! (The latter are not
* actually enabled by ALL, but "ALL:RSA" would enable some of them.)
*/
/* Used in SSL_set_shutdown()/SSL_get_shutdown(); */
# define SSL_SENT_SHUTDOWN 1
# define SSL_RECEIVED_SHUTDOWN 2
#ifdef __cplusplus
}
#endif
#ifdef __cplusplus
extern "C" {
#endif
# if (defined(OPENSSL_NO_RSA) || defined(OPENSSL_NO_MD5)) && !defined(OPENSSL_NO_SSL2)
# define OPENSSL_NO_SSL2
# endif
# define SSL_FILETYPE_ASN1 X509_FILETYPE_ASN1
# define SSL_FILETYPE_PEM X509_FILETYPE_PEM
/*
* This is needed to stop compilers complaining about the 'struct ssl_st *'
* function parameters used to prototype callbacks in SSL_CTX.
*/
typedef struct ssl_st *ssl_crock_st;
typedef struct tls_session_ticket_ext_st TLS_SESSION_TICKET_EXT;
typedef struct ssl_method_st SSL_METHOD;
typedef struct ssl_cipher_st SSL_CIPHER;
typedef struct ssl_session_st SSL_SESSION;
typedef struct tls_sigalgs_st TLS_SIGALGS;
typedef struct ssl_conf_ctx_st SSL_CONF_CTX;
DECLARE_STACK_OF(SSL_CIPHER)
/* SRTP protection profiles for use with the use_srtp extension (RFC 5764)*/
typedef struct srtp_protection_profile_st {
const char *name;
unsigned long id;
} SRTP_PROTECTION_PROFILE;
DECLARE_STACK_OF(SRTP_PROTECTION_PROFILE)
typedef int (*tls_session_ticket_ext_cb_fn) (SSL *s,
const unsigned char *data,
int len, void *arg);
typedef int (*tls_session_secret_cb_fn) (SSL *s, void *secret,
int *secret_len,
STACK_OF(SSL_CIPHER) *peer_ciphers,
SSL_CIPHER **cipher, void *arg);
# ifndef OPENSSL_NO_TLSEXT
/* Typedefs for handling custom extensions */
typedef int (*custom_ext_add_cb) (SSL *s, unsigned int ext_type,
const unsigned char **out,
size_t *outlen, int *al, void *add_arg);
typedef void (*custom_ext_free_cb) (SSL *s, unsigned int ext_type,
const unsigned char *out, void *add_arg);
typedef int (*custom_ext_parse_cb) (SSL *s, unsigned int ext_type,
const unsigned char *in,
size_t inlen, int *al, void *parse_arg);
# endif
# ifndef OPENSSL_NO_SSL_INTERN
/* used to hold info on the particular ciphers used */
struct ssl_cipher_st {
int valid;
const char *name; /* text name */
unsigned long id; /* id, 4 bytes, first is version */
/*
* changed in 0.9.9: these four used to be portions of a single value
* 'algorithms'
*/
unsigned long algorithm_mkey; /* key exchange algorithm */
unsigned long algorithm_auth; /* server authentication */
unsigned long algorithm_enc; /* symmetric encryption */
unsigned long algorithm_mac; /* symmetric authentication */
unsigned long algorithm_ssl; /* (major) protocol version */
unsigned long algo_strength; /* strength and export flags */
unsigned long algorithm2; /* Extra flags */
int strength_bits; /* Number of bits really used */
int alg_bits; /* Number of bits for algorithm */
};
/* Used to hold functions for SSLv2 or SSLv3/TLSv1 functions */
struct ssl_method_st {
int version;
int (*ssl_new) (SSL *s);
void (*ssl_clear) (SSL *s);
void (*ssl_free) (SSL *s);
int (*ssl_accept) (SSL *s);
int (*ssl_connect) (SSL *s);
int (*ssl_read) (SSL *s, void *buf, int len);
int (*ssl_peek) (SSL *s, void *buf, int len);
int (*ssl_write) (SSL *s, const void *buf, int len);
int (*ssl_shutdown) (SSL *s);
int (*ssl_renegotiate) (SSL *s);
int (*ssl_renegotiate_check) (SSL *s);
long (*ssl_get_message) (SSL *s, int st1, int stn, int mt, long
max, int *ok);
int (*ssl_read_bytes) (SSL *s, int type, unsigned char *buf, int len,
int peek);
int (*ssl_write_bytes) (SSL *s, int type, const void *buf_, int len);
int (*ssl_dispatch_alert) (SSL *s);
long (*ssl_ctrl) (SSL *s, int cmd, long larg, void *parg);
long (*ssl_ctx_ctrl) (SSL_CTX *ctx, int cmd, long larg, void *parg);
const SSL_CIPHER *(*get_cipher_by_char) (const unsigned char *ptr);
int (*put_cipher_by_char) (const SSL_CIPHER *cipher, unsigned char *ptr);
int (*ssl_pending) (const SSL *s);
int (*num_ciphers) (void);
const SSL_CIPHER *(*get_cipher) (unsigned ncipher);
const struct ssl_method_st *(*get_ssl_method) (int version);
long (*get_timeout) (void);
struct ssl3_enc_method *ssl3_enc; /* Extra SSLv3/TLS stuff */
int (*ssl_version) (void);
long (*ssl_callback_ctrl) (SSL *s, int cb_id, void (*fp) (void));
long (*ssl_ctx_callback_ctrl) (SSL_CTX *s, int cb_id, void (*fp) (void));
};
/*-
* Lets make this into an ASN.1 type structure as follows
* SSL_SESSION_ID ::= SEQUENCE {
* version INTEGER, -- structure version number
* SSLversion INTEGER, -- SSL version number
* Cipher OCTET STRING, -- the 3 byte cipher ID
* Session_ID OCTET STRING, -- the Session ID
* Master_key OCTET STRING, -- the master key
* KRB5_principal OCTET STRING -- optional Kerberos principal
* Key_Arg [ 0 ] IMPLICIT OCTET STRING, -- the optional Key argument
* Time [ 1 ] EXPLICIT INTEGER, -- optional Start Time
* Timeout [ 2 ] EXPLICIT INTEGER, -- optional Timeout ins seconds
* Peer [ 3 ] EXPLICIT X509, -- optional Peer Certificate
* Session_ID_context [ 4 ] EXPLICIT OCTET STRING, -- the Session ID context
* Verify_result [ 5 ] EXPLICIT INTEGER, -- X509_V_... code for `Peer'
* HostName [ 6 ] EXPLICIT OCTET STRING, -- optional HostName from servername TLS extension
* PSK_identity_hint [ 7 ] EXPLICIT OCTET STRING, -- optional PSK identity hint
* PSK_identity [ 8 ] EXPLICIT OCTET STRING, -- optional PSK identity
* Ticket_lifetime_hint [9] EXPLICIT INTEGER, -- server's lifetime hint for session ticket
* Ticket [10] EXPLICIT OCTET STRING, -- session ticket (clients only)
* Compression_meth [11] EXPLICIT OCTET STRING, -- optional compression method
* SRP_username [ 12 ] EXPLICIT OCTET STRING -- optional SRP username
* }
* Look in ssl/ssl_asn1.c for more details
* I'm using EXPLICIT tags so I can read the damn things using asn1parse :-).
*/
struct ssl_session_st {
int ssl_version; /* what ssl version session info is being
* kept in here? */
/* only really used in SSLv2 */
unsigned int key_arg_length;
unsigned char key_arg[SSL_MAX_KEY_ARG_LENGTH];
int master_key_length;
unsigned char master_key[SSL_MAX_MASTER_KEY_LENGTH];
/* session_id - valid? */
unsigned int session_id_length;
unsigned char session_id[SSL_MAX_SSL_SESSION_ID_LENGTH];
/*
* this is used to determine whether the session is being reused in the
* appropriate context. It is up to the application to set this, via
* SSL_new
*/
unsigned int sid_ctx_length;
unsigned char sid_ctx[SSL_MAX_SID_CTX_LENGTH];
# ifndef OPENSSL_NO_KRB5
unsigned int krb5_client_princ_len;
unsigned char krb5_client_princ[SSL_MAX_KRB5_PRINCIPAL_LENGTH];
# endif /* OPENSSL_NO_KRB5 */
# ifndef OPENSSL_NO_PSK
char *psk_identity_hint;
char *psk_identity;
# endif
/*
* Used to indicate that session resumption is not allowed. Applications
* can also set this bit for a new session via not_resumable_session_cb
* to disable session caching and tickets.
*/
int not_resumable;
/* The cert is the certificate used to establish this connection */
struct sess_cert_st /* SESS_CERT */ *sess_cert;
/*
* This is the cert for the other end. On clients, it will be the same as
* sess_cert->peer_key->x509 (the latter is not enough as sess_cert is
* not retained in the external representation of sessions, see
* ssl_asn1.c).
*/
X509 *peer;
/*
* when app_verify_callback accepts a session where the peer's
* certificate is not ok, we must remember the error for session reuse:
*/
long verify_result; /* only for servers */
int references;
long timeout;
long time;
unsigned int compress_meth; /* Need to lookup the method */
const SSL_CIPHER *cipher;
unsigned long cipher_id; /* when ASN.1 loaded, this needs to be used
* to load the 'cipher' structure */
STACK_OF(SSL_CIPHER) *ciphers; /* shared ciphers? */
CRYPTO_EX_DATA ex_data; /* application specific data */
/*
* These are used to make removal of session-ids more efficient and to
* implement a maximum cache size.
*/
struct ssl_session_st *prev, *next;
# ifndef OPENSSL_NO_TLSEXT
char *tlsext_hostname;
# ifndef OPENSSL_NO_EC
size_t tlsext_ecpointformatlist_length;
unsigned char *tlsext_ecpointformatlist; /* peer's list */
size_t tlsext_ellipticcurvelist_length;
unsigned char *tlsext_ellipticcurvelist; /* peer's list */
# endif /* OPENSSL_NO_EC */
/* RFC4507 info */
unsigned char *tlsext_tick; /* Session ticket */
size_t tlsext_ticklen; /* Session ticket length */
long tlsext_tick_lifetime_hint; /* Session lifetime hint in seconds */
# endif
# ifndef OPENSSL_NO_SRP
char *srp_username;
# endif
};
# endif
# define SSL_OP_MICROSOFT_SESS_ID_BUG 0x00000001L
# define SSL_OP_NETSCAPE_CHALLENGE_BUG 0x00000002L
/* Allow initial connection to servers that don't support RI */
# define SSL_OP_LEGACY_SERVER_CONNECT 0x00000004L
# define SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG 0x00000008L
# define SSL_OP_TLSEXT_PADDING 0x00000010L
# define SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER 0x00000020L
# define SSL_OP_SAFARI_ECDHE_ECDSA_BUG 0x00000040L
# define SSL_OP_SSLEAY_080_CLIENT_DH_BUG 0x00000080L
# define SSL_OP_TLS_D5_BUG 0x00000100L
# define SSL_OP_TLS_BLOCK_PADDING_BUG 0x00000200L
/* Hasn't done anything since OpenSSL 0.9.7h, retained for compatibility */
# define SSL_OP_MSIE_SSLV2_RSA_PADDING 0x0
/* Refers to ancient SSLREF and SSLv2, retained for compatibility */
# define SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG 0x0
/*
* Disable SSL 3.0/TLS 1.0 CBC vulnerability workaround that was added in
* OpenSSL 0.9.6d. Usually (depending on the application protocol) the
* workaround is not needed. Unfortunately some broken SSL/TLS
* implementations cannot handle it at all, which is why we include it in
* SSL_OP_ALL.
*/
/* added in 0.9.6e */
# define SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS 0x00000800L
/*
* SSL_OP_ALL: various bug workarounds that should be rather harmless. This
* used to be 0x000FFFFFL before 0.9.7.
*/
# define SSL_OP_ALL 0x80000BFFL
/* DTLS options */
# define SSL_OP_NO_QUERY_MTU 0x00001000L
/* Turn on Cookie Exchange (on relevant for servers) */
# define SSL_OP_COOKIE_EXCHANGE 0x00002000L
/* Don't use RFC4507 ticket extension */
# define SSL_OP_NO_TICKET 0x00004000L
/* Use Cisco's "speshul" version of DTLS_BAD_VER (as client) */
# define SSL_OP_CISCO_ANYCONNECT 0x00008000L
/* As server, disallow session resumption on renegotiation */
# define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION 0x00010000L
/* Don't use compression even if supported */
# define SSL_OP_NO_COMPRESSION 0x00020000L
/* Permit unsafe legacy renegotiation */
# define SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x00040000L
/* If set, always create a new key when using tmp_ecdh parameters */
# define SSL_OP_SINGLE_ECDH_USE 0x00080000L
/* Does nothing: retained for compatibility */
# define SSL_OP_SINGLE_DH_USE 0x00100000L
/* Does nothing: retained for compatibiity */
# define SSL_OP_EPHEMERAL_RSA 0x0
/*
* Set on servers to choose the cipher according to the server's preferences
*/
# define SSL_OP_CIPHER_SERVER_PREFERENCE 0x00400000L
/*
* If set, a server will allow a client to issue a SSLv3.0 version number as
* latest version supported in the premaster secret, even when TLSv1.0
* (version 3.1) was announced in the client hello. Normally this is
* forbidden to prevent version rollback attacks.
*/
# define SSL_OP_TLS_ROLLBACK_BUG 0x00800000L
# define SSL_OP_NO_SSLv2 0x01000000L
# define SSL_OP_NO_SSLv3 0x02000000L
# define SSL_OP_NO_TLSv1 0x04000000L
# define SSL_OP_NO_TLSv1_2 0x08000000L
# define SSL_OP_NO_TLSv1_1 0x10000000L
# define SSL_OP_NO_DTLSv1 0x04000000L
# define SSL_OP_NO_DTLSv1_2 0x08000000L
# define SSL_OP_NO_SSL_MASK (SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3|\
SSL_OP_NO_TLSv1|SSL_OP_NO_TLSv1_1|SSL_OP_NO_TLSv1_2)
/*
* These next two were never actually used for anything since SSLeay zap so
* we have some more flags.
*/
/*
* The next flag deliberately changes the ciphertest, this is a check for the
* PKCS#1 attack
*/
# define SSL_OP_PKCS1_CHECK_1 0x0
# define SSL_OP_PKCS1_CHECK_2 0x0
# define SSL_OP_NETSCAPE_CA_DN_BUG 0x20000000L
# define SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG 0x40000000L
/*
* Make server add server-hello extension from early version of cryptopro
* draft, when GOST ciphersuite is negotiated. Required for interoperability
* with CryptoPro CSP 3.x
*/
# define SSL_OP_CRYPTOPRO_TLSEXT_BUG 0x80000000L
/*
* Allow SSL_write(..., n) to return r with 0 < r < n (i.e. report success
* when just a single record has been written):
*/
# define SSL_MODE_ENABLE_PARTIAL_WRITE 0x00000001L
/*
* Make it possible to retry SSL_write() with changed buffer location (buffer
* contents must stay the same!); this is not the default to avoid the
* misconception that non-blocking SSL_write() behaves like non-blocking
* write():
*/
# define SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER 0x00000002L
/*
* Never bother the application with retries if the transport is blocking:
*/
# define SSL_MODE_AUTO_RETRY 0x00000004L
/* Don't attempt to automatically build certificate chain */
# define SSL_MODE_NO_AUTO_CHAIN 0x00000008L
/*
* Save RAM by releasing read and write buffers when they're empty. (SSL3 and
* TLS only.) "Released" buffers are put onto a free-list in the context or
* just freed (depending on the context's setting for freelist_max_len).
*/
# define SSL_MODE_RELEASE_BUFFERS 0x00000010L
/*
* Send the current time in the Random fields of the ClientHello and
* ServerHello records for compatibility with hypothetical implementations
* that require it.
*/
# define SSL_MODE_SEND_CLIENTHELLO_TIME 0x00000020L
# define SSL_MODE_SEND_SERVERHELLO_TIME 0x00000040L
/*
* Send TLS_FALLBACK_SCSV in the ClientHello. To be set only by applications
* that reconnect with a downgraded protocol version; see
* draft-ietf-tls-downgrade-scsv-00 for details. DO NOT ENABLE THIS if your
* application attempts a normal handshake. Only use this in explicit
* fallback retries, following the guidance in
* draft-ietf-tls-downgrade-scsv-00.
*/
# define SSL_MODE_SEND_FALLBACK_SCSV 0x00000080L
/* Cert related flags */
/*
* Many implementations ignore some aspects of the TLS standards such as
* enforcing certifcate chain algorithms. When this is set we enforce them.
*/
# define SSL_CERT_FLAG_TLS_STRICT 0x00000001L
/* Suite B modes, takes same values as certificate verify flags */
# define SSL_CERT_FLAG_SUITEB_128_LOS_ONLY 0x10000
/* Suite B 192 bit only mode */
# define SSL_CERT_FLAG_SUITEB_192_LOS 0x20000
/* Suite B 128 bit mode allowing 192 bit algorithms */
# define SSL_CERT_FLAG_SUITEB_128_LOS 0x30000
/* Perform all sorts of protocol violations for testing purposes */
# define SSL_CERT_FLAG_BROKEN_PROTOCOL 0x10000000
/* Flags for building certificate chains */
/* Treat any existing certificates as untrusted CAs */
# define SSL_BUILD_CHAIN_FLAG_UNTRUSTED 0x1
/* Don't include root CA in chain */
# define SSL_BUILD_CHAIN_FLAG_NO_ROOT 0x2
/* Just check certificates already there */
# define SSL_BUILD_CHAIN_FLAG_CHECK 0x4
/* Ignore verification errors */
# define SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR 0x8
/* Clear verification errors from queue */
# define SSL_BUILD_CHAIN_FLAG_CLEAR_ERROR 0x10
/* Flags returned by SSL_check_chain */
/* Certificate can be used with this session */
# define CERT_PKEY_VALID 0x1
/* Certificate can also be used for signing */
# define CERT_PKEY_SIGN 0x2
/* EE certificate signing algorithm OK */
# define CERT_PKEY_EE_SIGNATURE 0x10
/* CA signature algorithms OK */
# define CERT_PKEY_CA_SIGNATURE 0x20
/* EE certificate parameters OK */
# define CERT_PKEY_EE_PARAM 0x40
/* CA certificate parameters OK */
# define CERT_PKEY_CA_PARAM 0x80
/* Signing explicitly allowed as opposed to SHA1 fallback */
# define CERT_PKEY_EXPLICIT_SIGN 0x100
/* Client CA issuer names match (always set for server cert) */
# define CERT_PKEY_ISSUER_NAME 0x200
/* Cert type matches client types (always set for server cert) */
# define CERT_PKEY_CERT_TYPE 0x400
/* Cert chain suitable to Suite B */
# define CERT_PKEY_SUITEB 0x800
# define SSL_CONF_FLAG_CMDLINE 0x1
# define SSL_CONF_FLAG_FILE 0x2
# define SSL_CONF_FLAG_CLIENT 0x4
# define SSL_CONF_FLAG_SERVER 0x8
# define SSL_CONF_FLAG_SHOW_ERRORS 0x10
# define SSL_CONF_FLAG_CERTIFICATE 0x20
/* Configuration value types */
# define SSL_CONF_TYPE_UNKNOWN 0x0
# define SSL_CONF_TYPE_STRING 0x1
# define SSL_CONF_TYPE_FILE 0x2
# define SSL_CONF_TYPE_DIR 0x3
/*
* Note: SSL[_CTX]_set_{options,mode} use |= op on the previous value, they
* cannot be used to clear bits.
*/
# define SSL_CTX_set_options(ctx,op) \
SSL_CTX_ctrl((ctx),SSL_CTRL_OPTIONS,(op),NULL)
# define SSL_CTX_clear_options(ctx,op) \
SSL_CTX_ctrl((ctx),SSL_CTRL_CLEAR_OPTIONS,(op),NULL)
# define SSL_CTX_get_options(ctx) \
SSL_CTX_ctrl((ctx),SSL_CTRL_OPTIONS,0,NULL)
# define SSL_set_options(ssl,op) \
SSL_ctrl((ssl),SSL_CTRL_OPTIONS,(op),NULL)
# define SSL_clear_options(ssl,op) \
SSL_ctrl((ssl),SSL_CTRL_CLEAR_OPTIONS,(op),NULL)
# define SSL_get_options(ssl) \
SSL_ctrl((ssl),SSL_CTRL_OPTIONS,0,NULL)
# define SSL_CTX_set_mode(ctx,op) \
SSL_CTX_ctrl((ctx),SSL_CTRL_MODE,(op),NULL)
# define SSL_CTX_clear_mode(ctx,op) \
SSL_CTX_ctrl((ctx),SSL_CTRL_CLEAR_MODE,(op),NULL)
# define SSL_CTX_get_mode(ctx) \
SSL_CTX_ctrl((ctx),SSL_CTRL_MODE,0,NULL)
# define SSL_clear_mode(ssl,op) \
SSL_ctrl((ssl),SSL_CTRL_CLEAR_MODE,(op),NULL)
# define SSL_set_mode(ssl,op) \
SSL_ctrl((ssl),SSL_CTRL_MODE,(op),NULL)
# define SSL_get_mode(ssl) \
SSL_ctrl((ssl),SSL_CTRL_MODE,0,NULL)
# define SSL_set_mtu(ssl, mtu) \
SSL_ctrl((ssl),SSL_CTRL_SET_MTU,(mtu),NULL)
# define DTLS_set_link_mtu(ssl, mtu) \
SSL_ctrl((ssl),DTLS_CTRL_SET_LINK_MTU,(mtu),NULL)
# define DTLS_get_link_min_mtu(ssl) \
SSL_ctrl((ssl),DTLS_CTRL_GET_LINK_MIN_MTU,0,NULL)
# define SSL_get_secure_renegotiation_support(ssl) \
SSL_ctrl((ssl), SSL_CTRL_GET_RI_SUPPORT, 0, NULL)
# ifndef OPENSSL_NO_HEARTBEATS
# define SSL_heartbeat(ssl) \
SSL_ctrl((ssl),SSL_CTRL_TLS_EXT_SEND_HEARTBEAT,0,NULL)
# endif
# define SSL_CTX_set_cert_flags(ctx,op) \
SSL_CTX_ctrl((ctx),SSL_CTRL_CERT_FLAGS,(op),NULL)
# define SSL_set_cert_flags(s,op) \
SSL_ctrl((s),SSL_CTRL_CERT_FLAGS,(op),NULL)
# define SSL_CTX_clear_cert_flags(ctx,op) \
SSL_CTX_ctrl((ctx),SSL_CTRL_CLEAR_CERT_FLAGS,(op),NULL)
# define SSL_clear_cert_flags(s,op) \
SSL_ctrl((s),SSL_CTRL_CLEAR_CERT_FLAGS,(op),NULL)
void SSL_CTX_set_msg_callback(SSL_CTX *ctx,
void (*cb) (int write_p, int version,
int content_type, const void *buf,
size_t len, SSL *ssl, void *arg));
void SSL_set_msg_callback(SSL *ssl,
void (*cb) (int write_p, int version,
int content_type, const void *buf,
size_t len, SSL *ssl, void *arg));
# define SSL_CTX_set_msg_callback_arg(ctx, arg) SSL_CTX_ctrl((ctx), SSL_CTRL_SET_MSG_CALLBACK_ARG, 0, (arg))
# define SSL_set_msg_callback_arg(ssl, arg) SSL_ctrl((ssl), SSL_CTRL_SET_MSG_CALLBACK_ARG, 0, (arg))
# ifndef OPENSSL_NO_SRP
# ifndef OPENSSL_NO_SSL_INTERN
typedef struct srp_ctx_st {
/* param for all the callbacks */
void *SRP_cb_arg;
/* set client Hello login callback */
int (*TLS_ext_srp_username_callback) (SSL *, int *, void *);
/* set SRP N/g param callback for verification */
int (*SRP_verify_param_callback) (SSL *, void *);
/* set SRP client passwd callback */
char *(*SRP_give_srp_client_pwd_callback) (SSL *, void *);
char *login;
BIGNUM *N, *g, *s, *B, *A;
BIGNUM *a, *b, *v;
char *info;
int strength;
unsigned long srp_Mask;
} SRP_CTX;
# endif
/* see tls_srp.c */
int SSL_SRP_CTX_init(SSL *s);
int SSL_CTX_SRP_CTX_init(SSL_CTX *ctx);
int SSL_SRP_CTX_free(SSL *ctx);
int SSL_CTX_SRP_CTX_free(SSL_CTX *ctx);
int SSL_srp_server_param_with_username(SSL *s, int *ad);
int SRP_generate_server_master_secret(SSL *s, unsigned char *master_key);
int SRP_Calc_A_param(SSL *s);
int SRP_generate_client_master_secret(SSL *s, unsigned char *master_key);
# endif
# if defined(OPENSSL_SYS_MSDOS) && !defined(OPENSSL_SYS_WIN32)
# define SSL_MAX_CERT_LIST_DEFAULT 1024*30
/* 30k max cert list :-) */
# else
# define SSL_MAX_CERT_LIST_DEFAULT 1024*100
/* 100k max cert list :-) */
# endif
# define SSL_SESSION_CACHE_MAX_SIZE_DEFAULT (1024*20)
/*
* This callback type is used inside SSL_CTX, SSL, and in the functions that
* set them. It is used to override the generation of SSL/TLS session IDs in
* a server. Return value should be zero on an error, non-zero to proceed.
* Also, callbacks should themselves check if the id they generate is unique
* otherwise the SSL handshake will fail with an error - callbacks can do
* this using the 'ssl' value they're passed by;
* SSL_has_matching_session_id(ssl, id, *id_len) The length value passed in
* is set at the maximum size the session ID can be. In SSLv2 this is 16
* bytes, whereas SSLv3/TLSv1 it is 32 bytes. The callback can alter this
* length to be less if desired, but under SSLv2 session IDs are supposed to
* be fixed at 16 bytes so the id will be padded after the callback returns
* in this case. It is also an error for the callback to set the size to
* zero.
*/
typedef int (*GEN_SESSION_CB) (const SSL *ssl, unsigned char *id,
unsigned int *id_len);
typedef struct ssl_comp_st SSL_COMP;
# ifndef OPENSSL_NO_SSL_INTERN
struct ssl_comp_st {
int id;
const char *name;
# ifndef OPENSSL_NO_COMP
COMP_METHOD *method;
# else
char *method;
# endif
};
DECLARE_STACK_OF(SSL_COMP)
DECLARE_LHASH_OF(SSL_SESSION);
struct ssl_ctx_st {
const SSL_METHOD *method;
STACK_OF(SSL_CIPHER) *cipher_list;
/* same as above but sorted for lookup */
STACK_OF(SSL_CIPHER) *cipher_list_by_id;
struct x509_store_st /* X509_STORE */ *cert_store;
LHASH_OF(SSL_SESSION) *sessions;
/*
* Most session-ids that will be cached, default is
* SSL_SESSION_CACHE_MAX_SIZE_DEFAULT. 0 is unlimited.
*/
unsigned long session_cache_size;
struct ssl_session_st *session_cache_head;
struct ssl_session_st *session_cache_tail;
/*
* This can have one of 2 values, ored together, SSL_SESS_CACHE_CLIENT,
* SSL_SESS_CACHE_SERVER, Default is SSL_SESSION_CACHE_SERVER, which
* means only SSL_accept which cache SSL_SESSIONS.
*/
int session_cache_mode;
/*
* If timeout is not 0, it is the default timeout value set when
* SSL_new() is called. This has been put in to make life easier to set
* things up
*/
long session_timeout;
/*
* If this callback is not null, it will be called each time a session id
* is added to the cache. If this function returns 1, it means that the
* callback will do a SSL_SESSION_free() when it has finished using it.
* Otherwise, on 0, it means the callback has finished with it. If
* remove_session_cb is not null, it will be called when a session-id is
* removed from the cache. After the call, OpenSSL will
* SSL_SESSION_free() it.
*/
int (*new_session_cb) (struct ssl_st *ssl, SSL_SESSION *sess);
void (*remove_session_cb) (struct ssl_ctx_st *ctx, SSL_SESSION *sess);
SSL_SESSION *(*get_session_cb) (struct ssl_st *ssl,
unsigned char *data, int len, int *copy);
struct {
int sess_connect; /* SSL new conn - started */
int sess_connect_renegotiate; /* SSL reneg - requested */
int sess_connect_good; /* SSL new conne/reneg - finished */
int sess_accept; /* SSL new accept - started */
int sess_accept_renegotiate; /* SSL reneg - requested */
int sess_accept_good; /* SSL accept/reneg - finished */
int sess_miss; /* session lookup misses */
int sess_timeout; /* reuse attempt on timeouted session */
int sess_cache_full; /* session removed due to full cache */
int sess_hit; /* session reuse actually done */
int sess_cb_hit; /* session-id that was not in the cache was
* passed back via the callback. This
* indicates that the application is
* supplying session-id's from other
* processes - spooky :-) */
} stats;
int references;
/* if defined, these override the X509_verify_cert() calls */
int (*app_verify_callback) (X509_STORE_CTX *, void *);
void *app_verify_arg;
/*
* before OpenSSL 0.9.7, 'app_verify_arg' was ignored
* ('app_verify_callback' was called with just one argument)
*/
/* Default password callback. */
pem_password_cb *default_passwd_callback;
/* Default password callback user data. */
void *default_passwd_callback_userdata;
/* get client cert callback */
int (*client_cert_cb) (SSL *ssl, X509 **x509, EVP_PKEY **pkey);
/* cookie generate callback */
int (*app_gen_cookie_cb) (SSL *ssl, unsigned char *cookie,
unsigned int *cookie_len);
/* verify cookie callback */
int (*app_verify_cookie_cb) (SSL *ssl, unsigned char *cookie,
unsigned int cookie_len);
CRYPTO_EX_DATA ex_data;
const EVP_MD *rsa_md5; /* For SSLv2 - name is 'ssl2-md5' */
const EVP_MD *md5; /* For SSLv3/TLSv1 'ssl3-md5' */
const EVP_MD *sha1; /* For SSLv3/TLSv1 'ssl3->sha1' */
STACK_OF(X509) *extra_certs;
STACK_OF(SSL_COMP) *comp_methods; /* stack of SSL_COMP, SSLv3/TLSv1 */
/* Default values used when no per-SSL value is defined follow */
/* used if SSL's info_callback is NULL */
void (*info_callback) (const SSL *ssl, int type, int val);
/* what we put in client cert requests */
STACK_OF(X509_NAME) *client_CA;
/*
* Default values to use in SSL structures follow (these are copied by
* SSL_new)
*/
unsigned long options;
unsigned long mode;
long max_cert_list;
struct cert_st /* CERT */ *cert;
int read_ahead;
/* callback that allows applications to peek at protocol messages */
void (*msg_callback) (int write_p, int version, int content_type,
const void *buf, size_t len, SSL *ssl, void *arg);
void *msg_callback_arg;
int verify_mode;
unsigned int sid_ctx_length;
unsigned char sid_ctx[SSL_MAX_SID_CTX_LENGTH];
/* called 'verify_callback' in the SSL */
int (*default_verify_callback) (int ok, X509_STORE_CTX *ctx);
/* Default generate session ID callback. */
GEN_SESSION_CB generate_session_id;
X509_VERIFY_PARAM *param;
# if 0
int purpose; /* Purpose setting */
int trust; /* Trust setting */
# endif
int quiet_shutdown;
/*
* Maximum amount of data to send in one fragment. actual record size can
* be more than this due to padding and MAC overheads.
*/
unsigned int max_send_fragment;
# ifndef OPENSSL_NO_ENGINE
/*
* Engine to pass requests for client certs to
*/
ENGINE *client_cert_engine;
# endif
# ifndef OPENSSL_NO_TLSEXT
/* TLS extensions servername callback */
int (*tlsext_servername_callback) (SSL *, int *, void *);
void *tlsext_servername_arg;
/* RFC 4507 session ticket keys */
unsigned char tlsext_tick_key_name[16];
unsigned char tlsext_tick_hmac_key[16];
unsigned char tlsext_tick_aes_key[16];
/* Callback to support customisation of ticket key setting */
int (*tlsext_ticket_key_cb) (SSL *ssl,
unsigned char *name, unsigned char *iv,
EVP_CIPHER_CTX *ectx,
HMAC_CTX *hctx, int enc);
/* certificate status request info */
/* Callback for status request */
int (*tlsext_status_cb) (SSL *ssl, void *arg);
void *tlsext_status_arg;
/* draft-rescorla-tls-opaque-prf-input-00.txt information */
int (*tlsext_opaque_prf_input_callback) (SSL *, void *peerinput,
size_t len, void *arg);
void *tlsext_opaque_prf_input_callback_arg;
# endif
# ifndef OPENSSL_NO_PSK
char *psk_identity_hint;
unsigned int (*psk_client_callback) (SSL *ssl, const char *hint,
char *identity,
unsigned int max_identity_len,
unsigned char *psk,
unsigned int max_psk_len);
unsigned int (*psk_server_callback) (SSL *ssl, const char *identity,
unsigned char *psk,
unsigned int max_psk_len);
# endif
# ifndef OPENSSL_NO_BUF_FREELISTS
# define SSL_MAX_BUF_FREELIST_LEN_DEFAULT 32
unsigned int freelist_max_len;
struct ssl3_buf_freelist_st *wbuf_freelist;
struct ssl3_buf_freelist_st *rbuf_freelist;
# endif
# ifndef OPENSSL_NO_SRP
SRP_CTX srp_ctx; /* ctx for SRP authentication */
# endif
# ifndef OPENSSL_NO_TLSEXT
# ifndef OPENSSL_NO_NEXTPROTONEG
/* Next protocol negotiation information */
/* (for experimental NPN extension). */
/*
* For a server, this contains a callback function by which the set of
* advertised protocols can be provided.
*/
int (*next_protos_advertised_cb) (SSL *s, const unsigned char **buf,
unsigned int *len, void *arg);
void *next_protos_advertised_cb_arg;
/*
* For a client, this contains a callback function that selects the next
* protocol from the list provided by the server.
*/
int (*next_proto_select_cb) (SSL *s, unsigned char **out,
unsigned char *outlen,
const unsigned char *in,
unsigned int inlen, void *arg);
void *next_proto_select_cb_arg;
# endif
/* SRTP profiles we are willing to do from RFC 5764 */
STACK_OF(SRTP_PROTECTION_PROFILE) *srtp_profiles;
/*
* ALPN information (we are in the process of transitioning from NPN to
* ALPN.)
*/
/*-
* For a server, this contains a callback function that allows the
* server to select the protocol for the connection.
* out: on successful return, this must point to the raw protocol
* name (without the length prefix).
* outlen: on successful return, this contains the length of |*out|.
* in: points to the client's list of supported protocols in
* wire-format.
* inlen: the length of |in|.
*/
int (*alpn_select_cb) (SSL *s,
const unsigned char **out,
unsigned char *outlen,
const unsigned char *in,
unsigned int inlen, void *arg);
void *alpn_select_cb_arg;
/*
* For a client, this contains the list of supported protocols in wire
* format.
*/
unsigned char *alpn_client_proto_list;
unsigned alpn_client_proto_list_len;
# ifndef OPENSSL_NO_EC
/* EC extension values inherited by SSL structure */
size_t tlsext_ecpointformatlist_length;
unsigned char *tlsext_ecpointformatlist;
size_t tlsext_ellipticcurvelist_length;
unsigned char *tlsext_ellipticcurvelist;
# endif /* OPENSSL_NO_EC */
# endif
};
# endif
# define SSL_SESS_CACHE_OFF 0x0000
# define SSL_SESS_CACHE_CLIENT 0x0001
# define SSL_SESS_CACHE_SERVER 0x0002
# define SSL_SESS_CACHE_BOTH (SSL_SESS_CACHE_CLIENT|SSL_SESS_CACHE_SERVER)
# define SSL_SESS_CACHE_NO_AUTO_CLEAR 0x0080
/* enough comments already ... see SSL_CTX_set_session_cache_mode(3) */
# define SSL_SESS_CACHE_NO_INTERNAL_LOOKUP 0x0100
# define SSL_SESS_CACHE_NO_INTERNAL_STORE 0x0200
# define SSL_SESS_CACHE_NO_INTERNAL \
(SSL_SESS_CACHE_NO_INTERNAL_LOOKUP|SSL_SESS_CACHE_NO_INTERNAL_STORE)
LHASH_OF(SSL_SESSION) *SSL_CTX_sessions(SSL_CTX *ctx);
# define SSL_CTX_sess_number(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_NUMBER,0,NULL)
# define SSL_CTX_sess_connect(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_CONNECT,0,NULL)
# define SSL_CTX_sess_connect_good(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_CONNECT_GOOD,0,NULL)
# define SSL_CTX_sess_connect_renegotiate(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_CONNECT_RENEGOTIATE,0,NULL)
# define SSL_CTX_sess_accept(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_ACCEPT,0,NULL)
# define SSL_CTX_sess_accept_renegotiate(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_ACCEPT_RENEGOTIATE,0,NULL)
# define SSL_CTX_sess_accept_good(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_ACCEPT_GOOD,0,NULL)
# define SSL_CTX_sess_hits(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_HIT,0,NULL)
# define SSL_CTX_sess_cb_hits(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_CB_HIT,0,NULL)
# define SSL_CTX_sess_misses(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_MISSES,0,NULL)
# define SSL_CTX_sess_timeouts(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_TIMEOUTS,0,NULL)
# define SSL_CTX_sess_cache_full(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_CACHE_FULL,0,NULL)
void SSL_CTX_sess_set_new_cb(SSL_CTX *ctx,
int (*new_session_cb) (struct ssl_st *ssl,
SSL_SESSION *sess));
int (*SSL_CTX_sess_get_new_cb(SSL_CTX *ctx)) (struct ssl_st *ssl,
SSL_SESSION *sess);
void SSL_CTX_sess_set_remove_cb(SSL_CTX *ctx,
void (*remove_session_cb) (struct ssl_ctx_st
*ctx,
SSL_SESSION
*sess));
void (*SSL_CTX_sess_get_remove_cb(SSL_CTX *ctx)) (struct ssl_ctx_st *ctx,
SSL_SESSION *sess);
void SSL_CTX_sess_set_get_cb(SSL_CTX *ctx,
SSL_SESSION *(*get_session_cb) (struct ssl_st
*ssl,
unsigned char
*data, int len,
int *copy));
SSL_SESSION *(*SSL_CTX_sess_get_get_cb(SSL_CTX *ctx)) (struct ssl_st *ssl,
unsigned char *Data,
int len, int *copy);
void SSL_CTX_set_info_callback(SSL_CTX *ctx,
void (*cb) (const SSL *ssl, int type,
int val));
void (*SSL_CTX_get_info_callback(SSL_CTX *ctx)) (const SSL *ssl, int type,
int val);
void SSL_CTX_set_client_cert_cb(SSL_CTX *ctx,
int (*client_cert_cb) (SSL *ssl, X509 **x509,
EVP_PKEY **pkey));
int (*SSL_CTX_get_client_cert_cb(SSL_CTX *ctx)) (SSL *ssl, X509 **x509,
EVP_PKEY **pkey);
# ifndef OPENSSL_NO_ENGINE
int SSL_CTX_set_client_cert_engine(SSL_CTX *ctx, ENGINE *e);
# endif
void SSL_CTX_set_cookie_generate_cb(SSL_CTX *ctx,
int (*app_gen_cookie_cb) (SSL *ssl,
unsigned char
*cookie,
unsigned int
*cookie_len));
void SSL_CTX_set_cookie_verify_cb(SSL_CTX *ctx,
int (*app_verify_cookie_cb) (SSL *ssl,
unsigned char
*cookie,
unsigned int
cookie_len));
# ifndef OPENSSL_NO_NEXTPROTONEG
void SSL_CTX_set_next_protos_advertised_cb(SSL_CTX *s,
int (*cb) (SSL *ssl,
const unsigned char
**out,
unsigned int *outlen,
void *arg), void *arg);
void SSL_CTX_set_next_proto_select_cb(SSL_CTX *s,
int (*cb) (SSL *ssl,
unsigned char **out,
unsigned char *outlen,
const unsigned char *in,
unsigned int inlen,
void *arg), void *arg);
void SSL_get0_next_proto_negotiated(const SSL *s, const unsigned char **data,
unsigned *len);
# endif
# ifndef OPENSSL_NO_TLSEXT
int SSL_select_next_proto(unsigned char **out, unsigned char *outlen,
const unsigned char *in, unsigned int inlen,
const unsigned char *client,
unsigned int client_len);
# endif
# define OPENSSL_NPN_UNSUPPORTED 0
# define OPENSSL_NPN_NEGOTIATED 1
# define OPENSSL_NPN_NO_OVERLAP 2
int SSL_CTX_set_alpn_protos(SSL_CTX *ctx, const unsigned char *protos,
unsigned protos_len);
int SSL_set_alpn_protos(SSL *ssl, const unsigned char *protos,
unsigned protos_len);
void SSL_CTX_set_alpn_select_cb(SSL_CTX *ctx,
int (*cb) (SSL *ssl,
const unsigned char **out,
unsigned char *outlen,
const unsigned char *in,
unsigned int inlen,
void *arg), void *arg);
void SSL_get0_alpn_selected(const SSL *ssl, const unsigned char **data,
unsigned *len);
# ifndef OPENSSL_NO_PSK
/*
* the maximum length of the buffer given to callbacks containing the
* resulting identity/psk
*/
# define PSK_MAX_IDENTITY_LEN 128
# define PSK_MAX_PSK_LEN 256
void SSL_CTX_set_psk_client_callback(SSL_CTX *ctx,
unsigned int (*psk_client_callback) (SSL
*ssl,
const
char
*hint,
char
*identity,
unsigned
int
max_identity_len,
unsigned
char
*psk,
unsigned
int
max_psk_len));
void SSL_set_psk_client_callback(SSL *ssl,
unsigned int (*psk_client_callback) (SSL
*ssl,
const
char
*hint,
char
*identity,
unsigned
int
max_identity_len,
unsigned
char
*psk,
unsigned
int
max_psk_len));
void SSL_CTX_set_psk_server_callback(SSL_CTX *ctx,
unsigned int (*psk_server_callback) (SSL
*ssl,
const
char
*identity,
unsigned
char
*psk,
unsigned
int
max_psk_len));
void SSL_set_psk_server_callback(SSL *ssl,
unsigned int (*psk_server_callback) (SSL
*ssl,
const
char
*identity,
unsigned
char
*psk,
unsigned
int
max_psk_len));
int SSL_CTX_use_psk_identity_hint(SSL_CTX *ctx, const char *identity_hint);
int SSL_use_psk_identity_hint(SSL *s, const char *identity_hint);
const char *SSL_get_psk_identity_hint(const SSL *s);
const char *SSL_get_psk_identity(const SSL *s);
# endif
# ifndef OPENSSL_NO_TLSEXT
/* Register callbacks to handle custom TLS Extensions for client or server. */
int SSL_CTX_add_client_custom_ext(SSL_CTX *ctx, unsigned int ext_type,
custom_ext_add_cb add_cb,
custom_ext_free_cb free_cb,
void *add_arg,
custom_ext_parse_cb parse_cb,
void *parse_arg);
int SSL_CTX_add_server_custom_ext(SSL_CTX *ctx, unsigned int ext_type,
custom_ext_add_cb add_cb,
custom_ext_free_cb free_cb,
void *add_arg,
custom_ext_parse_cb parse_cb,
void *parse_arg);
int SSL_extension_supported(unsigned int ext_type);
# endif
# define SSL_NOTHING 1
# define SSL_WRITING 2
# define SSL_READING 3
# define SSL_X509_LOOKUP 4
/* These will only be used when doing non-blocking IO */
# define SSL_want_nothing(s) (SSL_want(s) == SSL_NOTHING)
# define SSL_want_read(s) (SSL_want(s) == SSL_READING)
# define SSL_want_write(s) (SSL_want(s) == SSL_WRITING)
# define SSL_want_x509_lookup(s) (SSL_want(s) == SSL_X509_LOOKUP)
# define SSL_MAC_FLAG_READ_MAC_STREAM 1
# define SSL_MAC_FLAG_WRITE_MAC_STREAM 2
# ifndef OPENSSL_NO_SSL_INTERN
struct ssl_st {
/*
* protocol version (one of SSL2_VERSION, SSL3_VERSION, TLS1_VERSION,
* DTLS1_VERSION)
*/
int version;
/* SSL_ST_CONNECT or SSL_ST_ACCEPT */
int type;
/* SSLv3 */
const SSL_METHOD *method;
/*
* There are 2 BIO's even though they are normally both the same. This
* is so data can be read and written to different handlers
*/
# ifndef OPENSSL_NO_BIO
/* used by SSL_read */
BIO *rbio;
/* used by SSL_write */
BIO *wbio;
/* used during session-id reuse to concatenate messages */
BIO *bbio;
# else
/* used by SSL_read */
char *rbio;
/* used by SSL_write */
char *wbio;
char *bbio;
# endif
/*
* This holds a variable that indicates what we were doing when a 0 or -1
* is returned. This is needed for non-blocking IO so we know what
* request needs re-doing when in SSL_accept or SSL_connect
*/
int rwstate;
/* true when we are actually in SSL_accept() or SSL_connect() */
int in_handshake;
int (*handshake_func) (SSL *);
/*
* Imagine that here's a boolean member "init" that is switched as soon
* as SSL_set_{accept/connect}_state is called for the first time, so
* that "state" and "handshake_func" are properly initialized. But as
* handshake_func is == 0 until then, we use this test instead of an
* "init" member.
*/
/* are we the server side? - mostly used by SSL_clear */
int server;
/*
* Generate a new session or reuse an old one.
* NB: For servers, the 'new' session may actually be a previously
* cached session or even the previous session unless
* SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION is set
*/
int new_session;
/* don't send shutdown packets */
int quiet_shutdown;
/* we have shut things down, 0x01 sent, 0x02 for received */
int shutdown;
/* where we are */
int state;
/* where we are when reading */
int rstate;
BUF_MEM *init_buf; /* buffer used during init */
void *init_msg; /* pointer to handshake message body, set by
* ssl3_get_message() */
int init_num; /* amount read/written */
int init_off; /* amount read/written */
/* used internally to point at a raw packet */
unsigned char *packet;
unsigned int packet_length;
struct ssl2_state_st *s2; /* SSLv2 variables */
struct ssl3_state_st *s3; /* SSLv3 variables */
struct dtls1_state_st *d1; /* DTLSv1 variables */
int read_ahead; /* Read as many input bytes as possible (for
* non-blocking reads) */
/* callback that allows applications to peek at protocol messages */
void (*msg_callback) (int write_p, int version, int content_type,
const void *buf, size_t len, SSL *ssl, void *arg);
void *msg_callback_arg;
int hit; /* reusing a previous session */
X509_VERIFY_PARAM *param;
# if 0
int purpose; /* Purpose setting */
int trust; /* Trust setting */
# endif
/* crypto */
STACK_OF(SSL_CIPHER) *cipher_list;
STACK_OF(SSL_CIPHER) *cipher_list_by_id;
/*
* These are the ones being used, the ones in SSL_SESSION are the ones to
* be 'copied' into these ones
*/
int mac_flags;
EVP_CIPHER_CTX *enc_read_ctx; /* cryptographic state */
EVP_MD_CTX *read_hash; /* used for mac generation */
# ifndef OPENSSL_NO_COMP
COMP_CTX *expand; /* uncompress */
# else
char *expand;
# endif
EVP_CIPHER_CTX *enc_write_ctx; /* cryptographic state */
EVP_MD_CTX *write_hash; /* used for mac generation */
# ifndef OPENSSL_NO_COMP
COMP_CTX *compress; /* compression */
# else
char *compress;
# endif
/* session info */
/* client cert? */
/* This is used to hold the server certificate used */
struct cert_st /* CERT */ *cert;
/*
* the session_id_context is used to ensure sessions are only reused in
* the appropriate context
*/
unsigned int sid_ctx_length;
unsigned char sid_ctx[SSL_MAX_SID_CTX_LENGTH];
/* This can also be in the session once a session is established */
SSL_SESSION *session;
/* Default generate session ID callback. */
GEN_SESSION_CB generate_session_id;
/* Used in SSL2 and SSL3 */
/*
* 0 don't care about verify failure.
* 1 fail if verify fails
*/
int verify_mode;
/* fail if callback returns 0 */
int (*verify_callback) (int ok, X509_STORE_CTX *ctx);
/* optional informational callback */
void (*info_callback) (const SSL *ssl, int type, int val);
/* error bytes to be written */
int error;
/* actual code */
int error_code;
# ifndef OPENSSL_NO_KRB5
/* Kerberos 5 context */
KSSL_CTX *kssl_ctx;
# endif /* OPENSSL_NO_KRB5 */
# ifndef OPENSSL_NO_PSK
unsigned int (*psk_client_callback) (SSL *ssl, const char *hint,
char *identity,
unsigned int max_identity_len,
unsigned char *psk,
unsigned int max_psk_len);
unsigned int (*psk_server_callback) (SSL *ssl, const char *identity,
unsigned char *psk,
unsigned int max_psk_len);
# endif
SSL_CTX *ctx;
/*
* set this flag to 1 and a sleep(1) is put into all SSL_read() and
* SSL_write() calls, good for nbio debuging :-)
*/
int debug;
/* extra application data */
long verify_result;
CRYPTO_EX_DATA ex_data;
/* for server side, keep the list of CA_dn we can use */
STACK_OF(X509_NAME) *client_CA;
int references;
/* protocol behaviour */
unsigned long options;
/* API behaviour */
unsigned long mode;
long max_cert_list;
int first_packet;
/* what was passed, used for SSLv3/TLS rollback check */
int client_version;
unsigned int max_send_fragment;
# ifndef OPENSSL_NO_TLSEXT
/* TLS extension debug callback */
void (*tlsext_debug_cb) (SSL *s, int client_server, int type,
unsigned char *data, int len, void *arg);
void *tlsext_debug_arg;
char *tlsext_hostname;
/*-
* no further mod of servername
* 0 : call the servername extension callback.
* 1 : prepare 2, allow last ack just after in server callback.
* 2 : don't call servername callback, no ack in server hello
*/
int servername_done;
/* certificate status request info */
/* Status type or -1 if no status type */
int tlsext_status_type;
/* Expect OCSP CertificateStatus message */
int tlsext_status_expected;
/* OCSP status request only */
STACK_OF(OCSP_RESPID) *tlsext_ocsp_ids;
X509_EXTENSIONS *tlsext_ocsp_exts;
/* OCSP response received or to be sent */
unsigned char *tlsext_ocsp_resp;
int tlsext_ocsp_resplen;
/* RFC4507 session ticket expected to be received or sent */
int tlsext_ticket_expected;
# ifndef OPENSSL_NO_EC
size_t tlsext_ecpointformatlist_length;
/* our list */
unsigned char *tlsext_ecpointformatlist;
size_t tlsext_ellipticcurvelist_length;
/* our list */
unsigned char *tlsext_ellipticcurvelist;
# endif /* OPENSSL_NO_EC */
/*
* draft-rescorla-tls-opaque-prf-input-00.txt information to be used for
* handshakes
*/
void *tlsext_opaque_prf_input;
size_t tlsext_opaque_prf_input_len;
/* TLS Session Ticket extension override */
TLS_SESSION_TICKET_EXT *tlsext_session_ticket;
/* TLS Session Ticket extension callback */
tls_session_ticket_ext_cb_fn tls_session_ticket_ext_cb;
void *tls_session_ticket_ext_cb_arg;
/* TLS pre-shared secret session resumption */
tls_session_secret_cb_fn tls_session_secret_cb;
void *tls_session_secret_cb_arg;
SSL_CTX *initial_ctx; /* initial ctx, used to store sessions */
# ifndef OPENSSL_NO_NEXTPROTONEG
/*
* Next protocol negotiation. For the client, this is the protocol that
* we sent in NextProtocol and is set when handling ServerHello
* extensions. For a server, this is the client's selected_protocol from
* NextProtocol and is set when handling the NextProtocol message, before
* the Finished message.
*/
unsigned char *next_proto_negotiated;
unsigned char next_proto_negotiated_len;
# endif
# define session_ctx initial_ctx
/* What we'll do */
STACK_OF(SRTP_PROTECTION_PROFILE) *srtp_profiles;
/* What's been chosen */
SRTP_PROTECTION_PROFILE *srtp_profile;
/*-
* Is use of the Heartbeat extension negotiated?
* 0: disabled
* 1: enabled
* 2: enabled, but not allowed to send Requests
*/
unsigned int tlsext_heartbeat;
/* Indicates if a HeartbeatRequest is in flight */
unsigned int tlsext_hb_pending;
/* HeartbeatRequest sequence number */
unsigned int tlsext_hb_seq;
# else
# define session_ctx ctx
# endif /* OPENSSL_NO_TLSEXT */
/*-
* 1 if we are renegotiating.
* 2 if we are a server and are inside a handshake
* (i.e. not just sending a HelloRequest)
*/
int renegotiate;
# ifndef OPENSSL_NO_SRP
/* ctx for SRP authentication */
SRP_CTX srp_ctx;
# endif
# ifndef OPENSSL_NO_TLSEXT
/*
* For a client, this contains the list of supported protocols in wire
* format.
*/
unsigned char *alpn_client_proto_list;
unsigned alpn_client_proto_list_len;
# endif /* OPENSSL_NO_TLSEXT */
};
# endif
#ifdef __cplusplus
}
#endif
# include <openssl/ssl2.h>
# include <openssl/ssl3.h>
# include <openssl/tls1.h> /* This is mostly sslv3 with a few tweaks */
# include <openssl/dtls1.h> /* Datagram TLS */
# include <openssl/ssl23.h>
# include <openssl/srtp.h> /* Support for the use_srtp extension */
#ifdef __cplusplus
extern "C" {
#endif
/* compatibility */
# define SSL_set_app_data(s,arg) (SSL_set_ex_data(s,0,(char *)arg))
# define SSL_get_app_data(s) (SSL_get_ex_data(s,0))
# define SSL_SESSION_set_app_data(s,a) (SSL_SESSION_set_ex_data(s,0,(char *)a))
# define SSL_SESSION_get_app_data(s) (SSL_SESSION_get_ex_data(s,0))
# define SSL_CTX_get_app_data(ctx) (SSL_CTX_get_ex_data(ctx,0))
# define SSL_CTX_set_app_data(ctx,arg) (SSL_CTX_set_ex_data(ctx,0,(char *)arg))
/*
* The following are the possible values for ssl->state are are used to
* indicate where we are up to in the SSL connection establishment. The
* macros that follow are about the only things you should need to use and
* even then, only when using non-blocking IO. It can also be useful to work
* out where you were when the connection failed
*/
# define SSL_ST_CONNECT 0x1000
# define SSL_ST_ACCEPT 0x2000
# define SSL_ST_MASK 0x0FFF
# define SSL_ST_INIT (SSL_ST_CONNECT|SSL_ST_ACCEPT)
# define SSL_ST_BEFORE 0x4000
# define SSL_ST_OK 0x03
# define SSL_ST_RENEGOTIATE (0x04|SSL_ST_INIT)
# define SSL_ST_ERR (0x05|SSL_ST_INIT)
# define SSL_CB_LOOP 0x01
# define SSL_CB_EXIT 0x02
# define SSL_CB_READ 0x04
# define SSL_CB_WRITE 0x08
# define SSL_CB_ALERT 0x4000/* used in callback */
# define SSL_CB_READ_ALERT (SSL_CB_ALERT|SSL_CB_READ)
# define SSL_CB_WRITE_ALERT (SSL_CB_ALERT|SSL_CB_WRITE)
# define SSL_CB_ACCEPT_LOOP (SSL_ST_ACCEPT|SSL_CB_LOOP)
# define SSL_CB_ACCEPT_EXIT (SSL_ST_ACCEPT|SSL_CB_EXIT)
# define SSL_CB_CONNECT_LOOP (SSL_ST_CONNECT|SSL_CB_LOOP)
# define SSL_CB_CONNECT_EXIT (SSL_ST_CONNECT|SSL_CB_EXIT)
# define SSL_CB_HANDSHAKE_START 0x10
# define SSL_CB_HANDSHAKE_DONE 0x20
/* Is the SSL_connection established? */
# define SSL_get_state(a) SSL_state(a)
# define SSL_is_init_finished(a) (SSL_state(a) == SSL_ST_OK)
# define SSL_in_init(a) (SSL_state(a)&SSL_ST_INIT)
# define SSL_in_before(a) (SSL_state(a)&SSL_ST_BEFORE)
# define SSL_in_connect_init(a) (SSL_state(a)&SSL_ST_CONNECT)
# define SSL_in_accept_init(a) (SSL_state(a)&SSL_ST_ACCEPT)
/*
* The following 2 states are kept in ssl->rstate when reads fail, you should
* not need these
*/
# define SSL_ST_READ_HEADER 0xF0
# define SSL_ST_READ_BODY 0xF1
# define SSL_ST_READ_DONE 0xF2
/*-
* Obtain latest Finished message
* -- that we sent (SSL_get_finished)
* -- that we expected from peer (SSL_get_peer_finished).
* Returns length (0 == no Finished so far), copies up to 'count' bytes.
*/
size_t SSL_get_finished(const SSL *s, void *buf, size_t count);
size_t SSL_get_peer_finished(const SSL *s, void *buf, size_t count);
/*
* use either SSL_VERIFY_NONE or SSL_VERIFY_PEER, the last 2 options are
* 'ored' with SSL_VERIFY_PEER if they are desired
*/
# define SSL_VERIFY_NONE 0x00
# define SSL_VERIFY_PEER 0x01
# define SSL_VERIFY_FAIL_IF_NO_PEER_CERT 0x02
# define SSL_VERIFY_CLIENT_ONCE 0x04
# define OpenSSL_add_ssl_algorithms() SSL_library_init()
# define SSLeay_add_ssl_algorithms() SSL_library_init()
/* this is for backward compatibility */
# if 0 /* NEW_SSLEAY */
# define SSL_CTX_set_default_verify(a,b,c) SSL_CTX_set_verify(a,b,c)
# define SSL_set_pref_cipher(c,n) SSL_set_cipher_list(c,n)
# define SSL_add_session(a,b) SSL_CTX_add_session((a),(b))
# define SSL_remove_session(a,b) SSL_CTX_remove_session((a),(b))
# define SSL_flush_sessions(a,b) SSL_CTX_flush_sessions((a),(b))
# endif
/* More backward compatibility */
# define SSL_get_cipher(s) \
SSL_CIPHER_get_name(SSL_get_current_cipher(s))
# define SSL_get_cipher_bits(s,np) \
SSL_CIPHER_get_bits(SSL_get_current_cipher(s),np)
# define SSL_get_cipher_version(s) \
SSL_CIPHER_get_version(SSL_get_current_cipher(s))
# define SSL_get_cipher_name(s) \
SSL_CIPHER_get_name(SSL_get_current_cipher(s))
# define SSL_get_time(a) SSL_SESSION_get_time(a)
# define SSL_set_time(a,b) SSL_SESSION_set_time((a),(b))
# define SSL_get_timeout(a) SSL_SESSION_get_timeout(a)
# define SSL_set_timeout(a,b) SSL_SESSION_set_timeout((a),(b))
# define d2i_SSL_SESSION_bio(bp,s_id) ASN1_d2i_bio_of(SSL_SESSION,SSL_SESSION_new,d2i_SSL_SESSION,bp,s_id)
# define i2d_SSL_SESSION_bio(bp,s_id) ASN1_i2d_bio_of(SSL_SESSION,i2d_SSL_SESSION,bp,s_id)
DECLARE_PEM_rw(SSL_SESSION, SSL_SESSION)
# define SSL_AD_REASON_OFFSET 1000/* offset to get SSL_R_... value
* from SSL_AD_... */
/* These alert types are for SSLv3 and TLSv1 */
# define SSL_AD_CLOSE_NOTIFY SSL3_AD_CLOSE_NOTIFY
/* fatal */
# define SSL_AD_UNEXPECTED_MESSAGE SSL3_AD_UNEXPECTED_MESSAGE
/* fatal */
# define SSL_AD_BAD_RECORD_MAC SSL3_AD_BAD_RECORD_MAC
# define SSL_AD_DECRYPTION_FAILED TLS1_AD_DECRYPTION_FAILED
# define SSL_AD_RECORD_OVERFLOW TLS1_AD_RECORD_OVERFLOW
/* fatal */
# define SSL_AD_DECOMPRESSION_FAILURE SSL3_AD_DECOMPRESSION_FAILURE
/* fatal */
# define SSL_AD_HANDSHAKE_FAILURE SSL3_AD_HANDSHAKE_FAILURE
/* Not for TLS */
# define SSL_AD_NO_CERTIFICATE SSL3_AD_NO_CERTIFICATE
# define SSL_AD_BAD_CERTIFICATE SSL3_AD_BAD_CERTIFICATE
# define SSL_AD_UNSUPPORTED_CERTIFICATE SSL3_AD_UNSUPPORTED_CERTIFICATE
# define SSL_AD_CERTIFICATE_REVOKED SSL3_AD_CERTIFICATE_REVOKED
# define SSL_AD_CERTIFICATE_EXPIRED SSL3_AD_CERTIFICATE_EXPIRED
# define SSL_AD_CERTIFICATE_UNKNOWN SSL3_AD_CERTIFICATE_UNKNOWN
/* fatal */
# define SSL_AD_ILLEGAL_PARAMETER SSL3_AD_ILLEGAL_PARAMETER
/* fatal */
# define SSL_AD_UNKNOWN_CA TLS1_AD_UNKNOWN_CA
/* fatal */
# define SSL_AD_ACCESS_DENIED TLS1_AD_ACCESS_DENIED
/* fatal */
# define SSL_AD_DECODE_ERROR TLS1_AD_DECODE_ERROR
# define SSL_AD_DECRYPT_ERROR TLS1_AD_DECRYPT_ERROR
/* fatal */
# define SSL_AD_EXPORT_RESTRICTION TLS1_AD_EXPORT_RESTRICTION
/* fatal */
# define SSL_AD_PROTOCOL_VERSION TLS1_AD_PROTOCOL_VERSION
/* fatal */
# define SSL_AD_INSUFFICIENT_SECURITY TLS1_AD_INSUFFICIENT_SECURITY
/* fatal */
# define SSL_AD_INTERNAL_ERROR TLS1_AD_INTERNAL_ERROR
# define SSL_AD_USER_CANCELLED TLS1_AD_USER_CANCELLED
# define SSL_AD_NO_RENEGOTIATION TLS1_AD_NO_RENEGOTIATION
# define SSL_AD_UNSUPPORTED_EXTENSION TLS1_AD_UNSUPPORTED_EXTENSION
# define SSL_AD_CERTIFICATE_UNOBTAINABLE TLS1_AD_CERTIFICATE_UNOBTAINABLE
# define SSL_AD_UNRECOGNIZED_NAME TLS1_AD_UNRECOGNIZED_NAME
# define SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE
# define SSL_AD_BAD_CERTIFICATE_HASH_VALUE TLS1_AD_BAD_CERTIFICATE_HASH_VALUE
/* fatal */
# define SSL_AD_UNKNOWN_PSK_IDENTITY TLS1_AD_UNKNOWN_PSK_IDENTITY
/* fatal */
# define SSL_AD_INAPPROPRIATE_FALLBACK TLS1_AD_INAPPROPRIATE_FALLBACK
# define SSL_ERROR_NONE 0
# define SSL_ERROR_SSL 1
# define SSL_ERROR_WANT_READ 2
# define SSL_ERROR_WANT_WRITE 3
# define SSL_ERROR_WANT_X509_LOOKUP 4
# define SSL_ERROR_SYSCALL 5/* look at error stack/return
* value/errno */
# define SSL_ERROR_ZERO_RETURN 6
# define SSL_ERROR_WANT_CONNECT 7
# define SSL_ERROR_WANT_ACCEPT 8
# define SSL_CTRL_NEED_TMP_RSA 1
# define SSL_CTRL_SET_TMP_RSA 2
# define SSL_CTRL_SET_TMP_DH 3
# define SSL_CTRL_SET_TMP_ECDH 4
# define SSL_CTRL_SET_TMP_RSA_CB 5
# define SSL_CTRL_SET_TMP_DH_CB 6
# define SSL_CTRL_SET_TMP_ECDH_CB 7
# define SSL_CTRL_GET_SESSION_REUSED 8
# define SSL_CTRL_GET_CLIENT_CERT_REQUEST 9
# define SSL_CTRL_GET_NUM_RENEGOTIATIONS 10
# define SSL_CTRL_CLEAR_NUM_RENEGOTIATIONS 11
# define SSL_CTRL_GET_TOTAL_RENEGOTIATIONS 12
# define SSL_CTRL_GET_FLAGS 13
# define SSL_CTRL_EXTRA_CHAIN_CERT 14
# define SSL_CTRL_SET_MSG_CALLBACK 15
# define SSL_CTRL_SET_MSG_CALLBACK_ARG 16
/* only applies to datagram connections */
# define SSL_CTRL_SET_MTU 17
/* Stats */
# define SSL_CTRL_SESS_NUMBER 20
# define SSL_CTRL_SESS_CONNECT 21
# define SSL_CTRL_SESS_CONNECT_GOOD 22
# define SSL_CTRL_SESS_CONNECT_RENEGOTIATE 23
# define SSL_CTRL_SESS_ACCEPT 24
# define SSL_CTRL_SESS_ACCEPT_GOOD 25
# define SSL_CTRL_SESS_ACCEPT_RENEGOTIATE 26
# define SSL_CTRL_SESS_HIT 27
# define SSL_CTRL_SESS_CB_HIT 28
# define SSL_CTRL_SESS_MISSES 29
# define SSL_CTRL_SESS_TIMEOUTS 30
# define SSL_CTRL_SESS_CACHE_FULL 31
# define SSL_CTRL_OPTIONS 32
# define SSL_CTRL_MODE 33
# define SSL_CTRL_GET_READ_AHEAD 40
# define SSL_CTRL_SET_READ_AHEAD 41
# define SSL_CTRL_SET_SESS_CACHE_SIZE 42
# define SSL_CTRL_GET_SESS_CACHE_SIZE 43
# define SSL_CTRL_SET_SESS_CACHE_MODE 44
# define SSL_CTRL_GET_SESS_CACHE_MODE 45
# define SSL_CTRL_GET_MAX_CERT_LIST 50
# define SSL_CTRL_SET_MAX_CERT_LIST 51
# define SSL_CTRL_SET_MAX_SEND_FRAGMENT 52
/* see tls1.h for macros based on these */
# ifndef OPENSSL_NO_TLSEXT
# define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
# define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
# define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
# define SSL_CTRL_SET_TLSEXT_DEBUG_CB 56
# define SSL_CTRL_SET_TLSEXT_DEBUG_ARG 57
# define SSL_CTRL_GET_TLSEXT_TICKET_KEYS 58
# define SSL_CTRL_SET_TLSEXT_TICKET_KEYS 59
# define SSL_CTRL_SET_TLSEXT_OPAQUE_PRF_INPUT 60
# define SSL_CTRL_SET_TLSEXT_OPAQUE_PRF_INPUT_CB 61
# define SSL_CTRL_SET_TLSEXT_OPAQUE_PRF_INPUT_CB_ARG 62
# define SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB 63
# define SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB_ARG 64
# define SSL_CTRL_SET_TLSEXT_STATUS_REQ_TYPE 65
# define SSL_CTRL_GET_TLSEXT_STATUS_REQ_EXTS 66
# define SSL_CTRL_SET_TLSEXT_STATUS_REQ_EXTS 67
# define SSL_CTRL_GET_TLSEXT_STATUS_REQ_IDS 68
# define SSL_CTRL_SET_TLSEXT_STATUS_REQ_IDS 69
# define SSL_CTRL_GET_TLSEXT_STATUS_REQ_OCSP_RESP 70
# define SSL_CTRL_SET_TLSEXT_STATUS_REQ_OCSP_RESP 71
# define SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB 72
# define SSL_CTRL_SET_TLS_EXT_SRP_USERNAME_CB 75
# define SSL_CTRL_SET_SRP_VERIFY_PARAM_CB 76
# define SSL_CTRL_SET_SRP_GIVE_CLIENT_PWD_CB 77
# define SSL_CTRL_SET_SRP_ARG 78
# define SSL_CTRL_SET_TLS_EXT_SRP_USERNAME 79
# define SSL_CTRL_SET_TLS_EXT_SRP_STRENGTH 80
# define SSL_CTRL_SET_TLS_EXT_SRP_PASSWORD 81
# ifndef OPENSSL_NO_HEARTBEATS
# define SSL_CTRL_TLS_EXT_SEND_HEARTBEAT 85
# define SSL_CTRL_GET_TLS_EXT_HEARTBEAT_PENDING 86
# define SSL_CTRL_SET_TLS_EXT_HEARTBEAT_NO_REQUESTS 87
# endif
# endif /* OPENSSL_NO_TLSEXT */
# define DTLS_CTRL_GET_TIMEOUT 73
# define DTLS_CTRL_HANDLE_TIMEOUT 74
# define DTLS_CTRL_LISTEN 75
# define SSL_CTRL_GET_RI_SUPPORT 76
# define SSL_CTRL_CLEAR_OPTIONS 77
# define SSL_CTRL_CLEAR_MODE 78
# define SSL_CTRL_GET_EXTRA_CHAIN_CERTS 82
# define SSL_CTRL_CLEAR_EXTRA_CHAIN_CERTS 83
# define SSL_CTRL_CHAIN 88
# define SSL_CTRL_CHAIN_CERT 89
# define SSL_CTRL_GET_CURVES 90
# define SSL_CTRL_SET_CURVES 91
# define SSL_CTRL_SET_CURVES_LIST 92
# define SSL_CTRL_GET_SHARED_CURVE 93
# define SSL_CTRL_SET_ECDH_AUTO 94
# define SSL_CTRL_SET_SIGALGS 97
# define SSL_CTRL_SET_SIGALGS_LIST 98
# define SSL_CTRL_CERT_FLAGS 99
# define SSL_CTRL_CLEAR_CERT_FLAGS 100
# define SSL_CTRL_SET_CLIENT_SIGALGS 101
# define SSL_CTRL_SET_CLIENT_SIGALGS_LIST 102
# define SSL_CTRL_GET_CLIENT_CERT_TYPES 103
# define SSL_CTRL_SET_CLIENT_CERT_TYPES 104
# define SSL_CTRL_BUILD_CERT_CHAIN 105
# define SSL_CTRL_SET_VERIFY_CERT_STORE 106
# define SSL_CTRL_SET_CHAIN_CERT_STORE 107
# define SSL_CTRL_GET_PEER_SIGNATURE_NID 108
# define SSL_CTRL_GET_SERVER_TMP_KEY 109
# define SSL_CTRL_GET_RAW_CIPHERLIST 110
# define SSL_CTRL_GET_EC_POINT_FORMATS 111
# define SSL_CTRL_GET_CHAIN_CERTS 115
# define SSL_CTRL_SELECT_CURRENT_CERT 116
# define SSL_CTRL_SET_CURRENT_CERT 117
# define SSL_CTRL_CHECK_PROTO_VERSION 119
# define DTLS_CTRL_SET_LINK_MTU 120
# define DTLS_CTRL_GET_LINK_MIN_MTU 121
# define SSL_CERT_SET_FIRST 1
# define SSL_CERT_SET_NEXT 2
# define SSL_CERT_SET_SERVER 3
# define DTLSv1_get_timeout(ssl, arg) \
SSL_ctrl(ssl,DTLS_CTRL_GET_TIMEOUT,0, (void *)arg)
# define DTLSv1_handle_timeout(ssl) \
SSL_ctrl(ssl,DTLS_CTRL_HANDLE_TIMEOUT,0, NULL)
# define DTLSv1_listen(ssl, peer) \
SSL_ctrl(ssl,DTLS_CTRL_LISTEN,0, (void *)peer)
# define SSL_session_reused(ssl) \
SSL_ctrl((ssl),SSL_CTRL_GET_SESSION_REUSED,0,NULL)
# define SSL_num_renegotiations(ssl) \
SSL_ctrl((ssl),SSL_CTRL_GET_NUM_RENEGOTIATIONS,0,NULL)
# define SSL_clear_num_renegotiations(ssl) \
SSL_ctrl((ssl),SSL_CTRL_CLEAR_NUM_RENEGOTIATIONS,0,NULL)
# define SSL_total_renegotiations(ssl) \
SSL_ctrl((ssl),SSL_CTRL_GET_TOTAL_RENEGOTIATIONS,0,NULL)
# define SSL_CTX_need_tmp_RSA(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_NEED_TMP_RSA,0,NULL)
# define SSL_CTX_set_tmp_rsa(ctx,rsa) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_TMP_RSA,0,(char *)rsa)
# define SSL_CTX_set_tmp_dh(ctx,dh) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_TMP_DH,0,(char *)dh)
# define SSL_CTX_set_tmp_ecdh(ctx,ecdh) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_TMP_ECDH,0,(char *)ecdh)
# define SSL_need_tmp_RSA(ssl) \
SSL_ctrl(ssl,SSL_CTRL_NEED_TMP_RSA,0,NULL)
# define SSL_set_tmp_rsa(ssl,rsa) \
SSL_ctrl(ssl,SSL_CTRL_SET_TMP_RSA,0,(char *)rsa)
# define SSL_set_tmp_dh(ssl,dh) \
SSL_ctrl(ssl,SSL_CTRL_SET_TMP_DH,0,(char *)dh)
# define SSL_set_tmp_ecdh(ssl,ecdh) \
SSL_ctrl(ssl,SSL_CTRL_SET_TMP_ECDH,0,(char *)ecdh)
# define SSL_CTX_add_extra_chain_cert(ctx,x509) \
SSL_CTX_ctrl(ctx,SSL_CTRL_EXTRA_CHAIN_CERT,0,(char *)x509)
# define SSL_CTX_get_extra_chain_certs(ctx,px509) \
SSL_CTX_ctrl(ctx,SSL_CTRL_GET_EXTRA_CHAIN_CERTS,0,px509)
# define SSL_CTX_get_extra_chain_certs_only(ctx,px509) \
SSL_CTX_ctrl(ctx,SSL_CTRL_GET_EXTRA_CHAIN_CERTS,1,px509)
# define SSL_CTX_clear_extra_chain_certs(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_CLEAR_EXTRA_CHAIN_CERTS,0,NULL)
# define SSL_CTX_set0_chain(ctx,sk) \
SSL_CTX_ctrl(ctx,SSL_CTRL_CHAIN,0,(char *)sk)
# define SSL_CTX_set1_chain(ctx,sk) \
SSL_CTX_ctrl(ctx,SSL_CTRL_CHAIN,1,(char *)sk)
# define SSL_CTX_add0_chain_cert(ctx,x509) \
SSL_CTX_ctrl(ctx,SSL_CTRL_CHAIN_CERT,0,(char *)x509)
# define SSL_CTX_add1_chain_cert(ctx,x509) \
SSL_CTX_ctrl(ctx,SSL_CTRL_CHAIN_CERT,1,(char *)x509)
# define SSL_CTX_get0_chain_certs(ctx,px509) \
SSL_CTX_ctrl(ctx,SSL_CTRL_GET_CHAIN_CERTS,0,px509)
# define SSL_CTX_clear_chain_certs(ctx) \
SSL_CTX_set0_chain(ctx,NULL)
# define SSL_CTX_build_cert_chain(ctx, flags) \
SSL_CTX_ctrl(ctx,SSL_CTRL_BUILD_CERT_CHAIN, flags, NULL)
# define SSL_CTX_select_current_cert(ctx,x509) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SELECT_CURRENT_CERT,0,(char *)x509)
# define SSL_CTX_set_current_cert(ctx, op) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CURRENT_CERT, op, NULL)
# define SSL_CTX_set0_verify_cert_store(ctx,st) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_VERIFY_CERT_STORE,0,(char *)st)
# define SSL_CTX_set1_verify_cert_store(ctx,st) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_VERIFY_CERT_STORE,1,(char *)st)
# define SSL_CTX_set0_chain_cert_store(ctx,st) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CHAIN_CERT_STORE,0,(char *)st)
# define SSL_CTX_set1_chain_cert_store(ctx,st) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CHAIN_CERT_STORE,1,(char *)st)
# define SSL_set0_chain(ctx,sk) \
SSL_ctrl(ctx,SSL_CTRL_CHAIN,0,(char *)sk)
# define SSL_set1_chain(ctx,sk) \
SSL_ctrl(ctx,SSL_CTRL_CHAIN,1,(char *)sk)
# define SSL_add0_chain_cert(ctx,x509) \
SSL_ctrl(ctx,SSL_CTRL_CHAIN_CERT,0,(char *)x509)
# define SSL_add1_chain_cert(ctx,x509) \
SSL_ctrl(ctx,SSL_CTRL_CHAIN_CERT,1,(char *)x509)
# define SSL_get0_chain_certs(ctx,px509) \
SSL_ctrl(ctx,SSL_CTRL_GET_CHAIN_CERTS,0,px509)
# define SSL_clear_chain_certs(ctx) \
SSL_set0_chain(ctx,NULL)
# define SSL_build_cert_chain(s, flags) \
SSL_ctrl(s,SSL_CTRL_BUILD_CERT_CHAIN, flags, NULL)
# define SSL_select_current_cert(ctx,x509) \
SSL_ctrl(ctx,SSL_CTRL_SELECT_CURRENT_CERT,0,(char *)x509)
# define SSL_set_current_cert(ctx,op) \
SSL_ctrl(ctx,SSL_CTRL_SET_CURRENT_CERT, op, NULL)
# define SSL_set0_verify_cert_store(s,st) \
SSL_ctrl(s,SSL_CTRL_SET_VERIFY_CERT_STORE,0,(char *)st)
# define SSL_set1_verify_cert_store(s,st) \
SSL_ctrl(s,SSL_CTRL_SET_VERIFY_CERT_STORE,1,(char *)st)
# define SSL_set0_chain_cert_store(s,st) \
SSL_ctrl(s,SSL_CTRL_SET_CHAIN_CERT_STORE,0,(char *)st)
# define SSL_set1_chain_cert_store(s,st) \
SSL_ctrl(s,SSL_CTRL_SET_CHAIN_CERT_STORE,1,(char *)st)
# define SSL_get1_curves(ctx, s) \
SSL_ctrl(ctx,SSL_CTRL_GET_CURVES,0,(char *)s)
# define SSL_CTX_set1_curves(ctx, clist, clistlen) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CURVES,clistlen,(char *)clist)
# define SSL_CTX_set1_curves_list(ctx, s) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CURVES_LIST,0,(char *)s)
# define SSL_set1_curves(ctx, clist, clistlen) \
SSL_ctrl(ctx,SSL_CTRL_SET_CURVES,clistlen,(char *)clist)
# define SSL_set1_curves_list(ctx, s) \
SSL_ctrl(ctx,SSL_CTRL_SET_CURVES_LIST,0,(char *)s)
# define SSL_get_shared_curve(s, n) \
SSL_ctrl(s,SSL_CTRL_GET_SHARED_CURVE,n,NULL)
# define SSL_CTX_set_ecdh_auto(ctx, onoff) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_ECDH_AUTO,onoff,NULL)
# define SSL_set_ecdh_auto(s, onoff) \
SSL_ctrl(s,SSL_CTRL_SET_ECDH_AUTO,onoff,NULL)
# define SSL_CTX_set1_sigalgs(ctx, slist, slistlen) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_SIGALGS,slistlen,(int *)slist)
# define SSL_CTX_set1_sigalgs_list(ctx, s) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_SIGALGS_LIST,0,(char *)s)
# define SSL_set1_sigalgs(ctx, slist, slistlen) \
SSL_ctrl(ctx,SSL_CTRL_SET_SIGALGS,slistlen,(int *)slist)
# define SSL_set1_sigalgs_list(ctx, s) \
SSL_ctrl(ctx,SSL_CTRL_SET_SIGALGS_LIST,0,(char *)s)
# define SSL_CTX_set1_client_sigalgs(ctx, slist, slistlen) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CLIENT_SIGALGS,slistlen,(int *)slist)
# define SSL_CTX_set1_client_sigalgs_list(ctx, s) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CLIENT_SIGALGS_LIST,0,(char *)s)
# define SSL_set1_client_sigalgs(ctx, slist, slistlen) \
SSL_ctrl(ctx,SSL_CTRL_SET_CLIENT_SIGALGS,clistlen,(int *)slist)
# define SSL_set1_client_sigalgs_list(ctx, s) \
SSL_ctrl(ctx,SSL_CTRL_SET_CLIENT_SIGALGS_LIST,0,(char *)s)
# define SSL_get0_certificate_types(s, clist) \
SSL_ctrl(s, SSL_CTRL_GET_CLIENT_CERT_TYPES, 0, (char *)clist)
# define SSL_CTX_set1_client_certificate_types(ctx, clist, clistlen) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CLIENT_CERT_TYPES,clistlen,(char *)clist)
# define SSL_set1_client_certificate_types(s, clist, clistlen) \
SSL_ctrl(s,SSL_CTRL_SET_CLIENT_CERT_TYPES,clistlen,(char *)clist)
# define SSL_get_peer_signature_nid(s, pn) \
SSL_ctrl(s,SSL_CTRL_GET_PEER_SIGNATURE_NID,0,pn)
# define SSL_get_server_tmp_key(s, pk) \
SSL_ctrl(s,SSL_CTRL_GET_SERVER_TMP_KEY,0,pk)
# define SSL_get0_raw_cipherlist(s, plst) \
SSL_ctrl(s,SSL_CTRL_GET_RAW_CIPHERLIST,0,(char *)plst)
# define SSL_get0_ec_point_formats(s, plst) \
SSL_ctrl(s,SSL_CTRL_GET_EC_POINT_FORMATS,0,(char *)plst)
# ifndef OPENSSL_NO_BIO
BIO_METHOD *BIO_f_ssl(void);
BIO *BIO_new_ssl(SSL_CTX *ctx, int client);
BIO *BIO_new_ssl_connect(SSL_CTX *ctx);
BIO *BIO_new_buffer_ssl_connect(SSL_CTX *ctx);
int BIO_ssl_copy_session_id(BIO *to, BIO *from);
void BIO_ssl_shutdown(BIO *ssl_bio);
# endif
int SSL_CTX_set_cipher_list(SSL_CTX *, const char *str);
SSL_CTX *SSL_CTX_new(const SSL_METHOD *meth);
void SSL_CTX_free(SSL_CTX *);
long SSL_CTX_set_timeout(SSL_CTX *ctx, long t);
long SSL_CTX_get_timeout(const SSL_CTX *ctx);
X509_STORE *SSL_CTX_get_cert_store(const SSL_CTX *);
void SSL_CTX_set_cert_store(SSL_CTX *, X509_STORE *);
int SSL_want(const SSL *s);
int SSL_clear(SSL *s);
void SSL_CTX_flush_sessions(SSL_CTX *ctx, long tm);
const SSL_CIPHER *SSL_get_current_cipher(const SSL *s);
int SSL_CIPHER_get_bits(const SSL_CIPHER *c, int *alg_bits);
char *SSL_CIPHER_get_version(const SSL_CIPHER *c);
const char *SSL_CIPHER_get_name(const SSL_CIPHER *c);
unsigned long SSL_CIPHER_get_id(const SSL_CIPHER *c);
int SSL_get_fd(const SSL *s);
int SSL_get_rfd(const SSL *s);
int SSL_get_wfd(const SSL *s);
const char *SSL_get_cipher_list(const SSL *s, int n);
char *SSL_get_shared_ciphers(const SSL *s, char *buf, int len);
int SSL_get_read_ahead(const SSL *s);
int SSL_pending(const SSL *s);
# ifndef OPENSSL_NO_SOCK
int SSL_set_fd(SSL *s, int fd);
int SSL_set_rfd(SSL *s, int fd);
int SSL_set_wfd(SSL *s, int fd);
# endif
# ifndef OPENSSL_NO_BIO
void SSL_set_bio(SSL *s, BIO *rbio, BIO *wbio);
BIO *SSL_get_rbio(const SSL *s);
BIO *SSL_get_wbio(const SSL *s);
# endif
int SSL_set_cipher_list(SSL *s, const char *str);
void SSL_set_read_ahead(SSL *s, int yes);
int SSL_get_verify_mode(const SSL *s);
int SSL_get_verify_depth(const SSL *s);
int (*SSL_get_verify_callback(const SSL *s)) (int, X509_STORE_CTX *);
void SSL_set_verify(SSL *s, int mode,
int (*callback) (int ok, X509_STORE_CTX *ctx));
void SSL_set_verify_depth(SSL *s, int depth);
void SSL_set_cert_cb(SSL *s, int (*cb) (SSL *ssl, void *arg), void *arg);
# ifndef OPENSSL_NO_RSA
int SSL_use_RSAPrivateKey(SSL *ssl, RSA *rsa);
# endif
int SSL_use_RSAPrivateKey_ASN1(SSL *ssl, unsigned char *d, long len);
int SSL_use_PrivateKey(SSL *ssl, EVP_PKEY *pkey);
int SSL_use_PrivateKey_ASN1(int pk, SSL *ssl, const unsigned char *d,
long len);
int SSL_use_certificate(SSL *ssl, X509 *x);
int SSL_use_certificate_ASN1(SSL *ssl, const unsigned char *d, int len);
# ifndef OPENSSL_NO_TLSEXT
/* Set serverinfo data for the current active cert. */
int SSL_CTX_use_serverinfo(SSL_CTX *ctx, const unsigned char *serverinfo,
size_t serverinfo_length);
# ifndef OPENSSL_NO_STDIO
int SSL_CTX_use_serverinfo_file(SSL_CTX *ctx, const char *file);
# endif /* NO_STDIO */
# endif
# ifndef OPENSSL_NO_STDIO
int SSL_use_RSAPrivateKey_file(SSL *ssl, const char *file, int type);
int SSL_use_PrivateKey_file(SSL *ssl, const char *file, int type);
int SSL_use_certificate_file(SSL *ssl, const char *file, int type);
int SSL_CTX_use_RSAPrivateKey_file(SSL_CTX *ctx, const char *file, int type);
int SSL_CTX_use_PrivateKey_file(SSL_CTX *ctx, const char *file, int type);
int SSL_CTX_use_certificate_file(SSL_CTX *ctx, const char *file, int type);
/* PEM type */
int SSL_CTX_use_certificate_chain_file(SSL_CTX *ctx, const char *file);
STACK_OF(X509_NAME) *SSL_load_client_CA_file(const char *file);
int SSL_add_file_cert_subjects_to_stack(STACK_OF(X509_NAME) *stackCAs,
const char *file);
# ifndef OPENSSL_SYS_VMS
/* XXXXX: Better scheme needed! [was: #ifndef MAC_OS_pre_X] */
# ifndef OPENSSL_SYS_MACINTOSH_CLASSIC
int SSL_add_dir_cert_subjects_to_stack(STACK_OF(X509_NAME) *stackCAs,
const char *dir);
# endif
# endif
# endif
void SSL_load_error_strings(void);
const char *SSL_state_string(const SSL *s);
const char *SSL_rstate_string(const SSL *s);
const char *SSL_state_string_long(const SSL *s);
const char *SSL_rstate_string_long(const SSL *s);
long SSL_SESSION_get_time(const SSL_SESSION *s);
long SSL_SESSION_set_time(SSL_SESSION *s, long t);
long SSL_SESSION_get_timeout(const SSL_SESSION *s);
long SSL_SESSION_set_timeout(SSL_SESSION *s, long t);
void SSL_copy_session_id(SSL *to, const SSL *from);
X509 *SSL_SESSION_get0_peer(SSL_SESSION *s);
int SSL_SESSION_set1_id_context(SSL_SESSION *s, const unsigned char *sid_ctx,
unsigned int sid_ctx_len);
SSL_SESSION *SSL_SESSION_new(void);
const unsigned char *SSL_SESSION_get_id(const SSL_SESSION *s,
unsigned int *len);
unsigned int SSL_SESSION_get_compress_id(const SSL_SESSION *s);
# ifndef OPENSSL_NO_FP_API
int SSL_SESSION_print_fp(FILE *fp, const SSL_SESSION *ses);
# endif
# ifndef OPENSSL_NO_BIO
int SSL_SESSION_print(BIO *fp, const SSL_SESSION *ses);
# endif
void SSL_SESSION_free(SSL_SESSION *ses);
int i2d_SSL_SESSION(SSL_SESSION *in, unsigned char **pp);
int SSL_set_session(SSL *to, SSL_SESSION *session);
int SSL_CTX_add_session(SSL_CTX *s, SSL_SESSION *c);
int SSL_CTX_remove_session(SSL_CTX *, SSL_SESSION *c);
int SSL_CTX_set_generate_session_id(SSL_CTX *, GEN_SESSION_CB);
int SSL_set_generate_session_id(SSL *, GEN_SESSION_CB);
int SSL_has_matching_session_id(const SSL *ssl, const unsigned char *id,
unsigned int id_len);
SSL_SESSION *d2i_SSL_SESSION(SSL_SESSION **a, const unsigned char **pp,
long length);
# ifdef HEADER_X509_H
X509 *SSL_get_peer_certificate(const SSL *s);
# endif
STACK_OF(X509) *SSL_get_peer_cert_chain(const SSL *s);
int SSL_CTX_get_verify_mode(const SSL_CTX *ctx);
int SSL_CTX_get_verify_depth(const SSL_CTX *ctx);
int (*SSL_CTX_get_verify_callback(const SSL_CTX *ctx)) (int,
X509_STORE_CTX *);
void SSL_CTX_set_verify(SSL_CTX *ctx, int mode,
int (*callback) (int, X509_STORE_CTX *));
void SSL_CTX_set_verify_depth(SSL_CTX *ctx, int depth);
void SSL_CTX_set_cert_verify_callback(SSL_CTX *ctx,
int (*cb) (X509_STORE_CTX *, void *),
void *arg);
void SSL_CTX_set_cert_cb(SSL_CTX *c, int (*cb) (SSL *ssl, void *arg),
void *arg);
# ifndef OPENSSL_NO_RSA
int SSL_CTX_use_RSAPrivateKey(SSL_CTX *ctx, RSA *rsa);
# endif
int SSL_CTX_use_RSAPrivateKey_ASN1(SSL_CTX *ctx, const unsigned char *d,
long len);
int SSL_CTX_use_PrivateKey(SSL_CTX *ctx, EVP_PKEY *pkey);
int SSL_CTX_use_PrivateKey_ASN1(int pk, SSL_CTX *ctx,
const unsigned char *d, long len);
int SSL_CTX_use_certificate(SSL_CTX *ctx, X509 *x);
int SSL_CTX_use_certificate_ASN1(SSL_CTX *ctx, int len,
const unsigned char *d);
void SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx, pem_password_cb *cb);
void SSL_CTX_set_default_passwd_cb_userdata(SSL_CTX *ctx, void *u);
int SSL_CTX_check_private_key(const SSL_CTX *ctx);
int SSL_check_private_key(const SSL *ctx);
int SSL_CTX_set_session_id_context(SSL_CTX *ctx, const unsigned char *sid_ctx,
unsigned int sid_ctx_len);
SSL *SSL_new(SSL_CTX *ctx);
int SSL_set_session_id_context(SSL *ssl, const unsigned char *sid_ctx,
unsigned int sid_ctx_len);
int SSL_CTX_set_purpose(SSL_CTX *s, int purpose);
int SSL_set_purpose(SSL *s, int purpose);
int SSL_CTX_set_trust(SSL_CTX *s, int trust);
int SSL_set_trust(SSL *s, int trust);
int SSL_CTX_set1_param(SSL_CTX *ctx, X509_VERIFY_PARAM *vpm);
int SSL_set1_param(SSL *ssl, X509_VERIFY_PARAM *vpm);
X509_VERIFY_PARAM *SSL_CTX_get0_param(SSL_CTX *ctx);
X509_VERIFY_PARAM *SSL_get0_param(SSL *ssl);
# ifndef OPENSSL_NO_SRP
int SSL_CTX_set_srp_username(SSL_CTX *ctx, char *name);
int SSL_CTX_set_srp_password(SSL_CTX *ctx, char *password);
int SSL_CTX_set_srp_strength(SSL_CTX *ctx, int strength);
int SSL_CTX_set_srp_client_pwd_callback(SSL_CTX *ctx,
char *(*cb) (SSL *, void *));
int SSL_CTX_set_srp_verify_param_callback(SSL_CTX *ctx,
int (*cb) (SSL *, void *));
int SSL_CTX_set_srp_username_callback(SSL_CTX *ctx,
int (*cb) (SSL *, int *, void *));
int SSL_CTX_set_srp_cb_arg(SSL_CTX *ctx, void *arg);
int SSL_set_srp_server_param(SSL *s, const BIGNUM *N, const BIGNUM *g,
BIGNUM *sa, BIGNUM *v, char *info);
int SSL_set_srp_server_param_pw(SSL *s, const char *user, const char *pass,
const char *grp);
BIGNUM *SSL_get_srp_g(SSL *s);
BIGNUM *SSL_get_srp_N(SSL *s);
char *SSL_get_srp_username(SSL *s);
char *SSL_get_srp_userinfo(SSL *s);
# endif
void SSL_certs_clear(SSL *s);
void SSL_free(SSL *ssl);
int SSL_accept(SSL *ssl);
int SSL_connect(SSL *ssl);
int SSL_read(SSL *ssl, void *buf, int num);
int SSL_peek(SSL *ssl, void *buf, int num);
int SSL_write(SSL *ssl, const void *buf, int num);
long SSL_ctrl(SSL *ssl, int cmd, long larg, void *parg);
long SSL_callback_ctrl(SSL *, int, void (*)(void));
long SSL_CTX_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg);
long SSL_CTX_callback_ctrl(SSL_CTX *, int, void (*)(void));
int SSL_get_error(const SSL *s, int ret_code);
const char *SSL_get_version(const SSL *s);
/* This sets the 'default' SSL version that SSL_new() will create */
int SSL_CTX_set_ssl_version(SSL_CTX *ctx, const SSL_METHOD *meth);
# ifndef OPENSSL_NO_SSL2_METHOD
const SSL_METHOD *SSLv2_method(void); /* SSLv2 */
const SSL_METHOD *SSLv2_server_method(void); /* SSLv2 */
const SSL_METHOD *SSLv2_client_method(void); /* SSLv2 */
# endif
# ifndef OPENSSL_NO_SSL3_METHOD
const SSL_METHOD *SSLv3_method(void); /* SSLv3 */
const SSL_METHOD *SSLv3_server_method(void); /* SSLv3 */
const SSL_METHOD *SSLv3_client_method(void); /* SSLv3 */
# endif
const SSL_METHOD *SSLv23_method(void); /* Negotiate highest available SSL/TLS
* version */
const SSL_METHOD *SSLv23_server_method(void); /* Negotiate highest available
* SSL/TLS version */
const SSL_METHOD *SSLv23_client_method(void); /* Negotiate highest available
* SSL/TLS version */
const SSL_METHOD *TLSv1_method(void); /* TLSv1.0 */
const SSL_METHOD *TLSv1_server_method(void); /* TLSv1.0 */
const SSL_METHOD *TLSv1_client_method(void); /* TLSv1.0 */
const SSL_METHOD *TLSv1_1_method(void); /* TLSv1.1 */
const SSL_METHOD *TLSv1_1_server_method(void); /* TLSv1.1 */
const SSL_METHOD *TLSv1_1_client_method(void); /* TLSv1.1 */
const SSL_METHOD *TLSv1_2_method(void); /* TLSv1.2 */
const SSL_METHOD *TLSv1_2_server_method(void); /* TLSv1.2 */
const SSL_METHOD *TLSv1_2_client_method(void); /* TLSv1.2 */
const SSL_METHOD *DTLSv1_method(void); /* DTLSv1.0 */
const SSL_METHOD *DTLSv1_server_method(void); /* DTLSv1.0 */
const SSL_METHOD *DTLSv1_client_method(void); /* DTLSv1.0 */
const SSL_METHOD *DTLSv1_2_method(void); /* DTLSv1.2 */
const SSL_METHOD *DTLSv1_2_server_method(void); /* DTLSv1.2 */
const SSL_METHOD *DTLSv1_2_client_method(void); /* DTLSv1.2 */
const SSL_METHOD *DTLS_method(void); /* DTLS 1.0 and 1.2 */
const SSL_METHOD *DTLS_server_method(void); /* DTLS 1.0 and 1.2 */
const SSL_METHOD *DTLS_client_method(void); /* DTLS 1.0 and 1.2 */
STACK_OF(SSL_CIPHER) *SSL_get_ciphers(const SSL *s);
int SSL_do_handshake(SSL *s);
int SSL_renegotiate(SSL *s);
int SSL_renegotiate_abbreviated(SSL *s);
int SSL_renegotiate_pending(SSL *s);
int SSL_shutdown(SSL *s);
const SSL_METHOD *SSL_CTX_get_ssl_method(SSL_CTX *ctx);
const SSL_METHOD *SSL_get_ssl_method(SSL *s);
int SSL_set_ssl_method(SSL *s, const SSL_METHOD *method);
const char *SSL_alert_type_string_long(int value);
const char *SSL_alert_type_string(int value);
const char *SSL_alert_desc_string_long(int value);
const char *SSL_alert_desc_string(int value);
void SSL_set_client_CA_list(SSL *s, STACK_OF(X509_NAME) *name_list);
void SSL_CTX_set_client_CA_list(SSL_CTX *ctx, STACK_OF(X509_NAME) *name_list);
STACK_OF(X509_NAME) *SSL_get_client_CA_list(const SSL *s);
STACK_OF(X509_NAME) *SSL_CTX_get_client_CA_list(const SSL_CTX *s);
int SSL_add_client_CA(SSL *ssl, X509 *x);
int SSL_CTX_add_client_CA(SSL_CTX *ctx, X509 *x);
void SSL_set_connect_state(SSL *s);
void SSL_set_accept_state(SSL *s);
long SSL_get_default_timeout(const SSL *s);
int SSL_library_init(void);
char *SSL_CIPHER_description(const SSL_CIPHER *, char *buf, int size);
STACK_OF(X509_NAME) *SSL_dup_CA_list(STACK_OF(X509_NAME) *sk);
SSL *SSL_dup(SSL *ssl);
X509 *SSL_get_certificate(const SSL *ssl);
/*
* EVP_PKEY
*/ struct evp_pkey_st *SSL_get_privatekey(const SSL *ssl);
X509 *SSL_CTX_get0_certificate(const SSL_CTX *ctx);
EVP_PKEY *SSL_CTX_get0_privatekey(const SSL_CTX *ctx);
void SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx, int mode);
int SSL_CTX_get_quiet_shutdown(const SSL_CTX *ctx);
void SSL_set_quiet_shutdown(SSL *ssl, int mode);
int SSL_get_quiet_shutdown(const SSL *ssl);
void SSL_set_shutdown(SSL *ssl, int mode);
int SSL_get_shutdown(const SSL *ssl);
int SSL_version(const SSL *ssl);
int SSL_CTX_set_default_verify_paths(SSL_CTX *ctx);
int SSL_CTX_load_verify_locations(SSL_CTX *ctx, const char *CAfile,
const char *CApath);
# define SSL_get0_session SSL_get_session/* just peek at pointer */
SSL_SESSION *SSL_get_session(const SSL *ssl);
SSL_SESSION *SSL_get1_session(SSL *ssl); /* obtain a reference count */
SSL_CTX *SSL_get_SSL_CTX(const SSL *ssl);
SSL_CTX *SSL_set_SSL_CTX(SSL *ssl, SSL_CTX *ctx);
void SSL_set_info_callback(SSL *ssl,
void (*cb) (const SSL *ssl, int type, int val));
void (*SSL_get_info_callback(const SSL *ssl)) (const SSL *ssl, int type,
int val);
int SSL_state(const SSL *ssl);
void SSL_set_state(SSL *ssl, int state);
void SSL_set_verify_result(SSL *ssl, long v);
long SSL_get_verify_result(const SSL *ssl);
int SSL_set_ex_data(SSL *ssl, int idx, void *data);
void *SSL_get_ex_data(const SSL *ssl, int idx);
int SSL_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func,
CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func);
int SSL_SESSION_set_ex_data(SSL_SESSION *ss, int idx, void *data);
void *SSL_SESSION_get_ex_data(const SSL_SESSION *ss, int idx);
int SSL_SESSION_get_ex_new_index(long argl, void *argp,
CRYPTO_EX_new *new_func,
CRYPTO_EX_dup *dup_func,
CRYPTO_EX_free *free_func);
int SSL_CTX_set_ex_data(SSL_CTX *ssl, int idx, void *data);
void *SSL_CTX_get_ex_data(const SSL_CTX *ssl, int idx);
int SSL_CTX_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func,
CRYPTO_EX_dup *dup_func,
CRYPTO_EX_free *free_func);
int SSL_get_ex_data_X509_STORE_CTX_idx(void);
# define SSL_CTX_sess_set_cache_size(ctx,t) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_SESS_CACHE_SIZE,t,NULL)
# define SSL_CTX_sess_get_cache_size(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_GET_SESS_CACHE_SIZE,0,NULL)
# define SSL_CTX_set_session_cache_mode(ctx,m) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_SESS_CACHE_MODE,m,NULL)
# define SSL_CTX_get_session_cache_mode(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_GET_SESS_CACHE_MODE,0,NULL)
# define SSL_CTX_get_default_read_ahead(ctx) SSL_CTX_get_read_ahead(ctx)
# define SSL_CTX_set_default_read_ahead(ctx,m) SSL_CTX_set_read_ahead(ctx,m)
# define SSL_CTX_get_read_ahead(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_GET_READ_AHEAD,0,NULL)
# define SSL_CTX_set_read_ahead(ctx,m) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_READ_AHEAD,m,NULL)
# define SSL_CTX_get_max_cert_list(ctx) \
SSL_CTX_ctrl(ctx,SSL_CTRL_GET_MAX_CERT_LIST,0,NULL)
# define SSL_CTX_set_max_cert_list(ctx,m) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_MAX_CERT_LIST,m,NULL)
# define SSL_get_max_cert_list(ssl) \
SSL_ctrl(ssl,SSL_CTRL_GET_MAX_CERT_LIST,0,NULL)
# define SSL_set_max_cert_list(ssl,m) \
SSL_ctrl(ssl,SSL_CTRL_SET_MAX_CERT_LIST,m,NULL)
# define SSL_CTX_set_max_send_fragment(ctx,m) \
SSL_CTX_ctrl(ctx,SSL_CTRL_SET_MAX_SEND_FRAGMENT,m,NULL)
# define SSL_set_max_send_fragment(ssl,m) \
SSL_ctrl(ssl,SSL_CTRL_SET_MAX_SEND_FRAGMENT,m,NULL)
/* NB: the keylength is only applicable when is_export is true */
# ifndef OPENSSL_NO_RSA
void SSL_CTX_set_tmp_rsa_callback(SSL_CTX *ctx,
RSA *(*cb) (SSL *ssl, int is_export,
int keylength));
void SSL_set_tmp_rsa_callback(SSL *ssl,
RSA *(*cb) (SSL *ssl, int is_export,
int keylength));
# endif
# ifndef OPENSSL_NO_DH
void SSL_CTX_set_tmp_dh_callback(SSL_CTX *ctx,
DH *(*dh) (SSL *ssl, int is_export,
int keylength));
void SSL_set_tmp_dh_callback(SSL *ssl,
DH *(*dh) (SSL *ssl, int is_export,
int keylength));
# endif
# ifndef OPENSSL_NO_ECDH
void SSL_CTX_set_tmp_ecdh_callback(SSL_CTX *ctx,
EC_KEY *(*ecdh) (SSL *ssl, int is_export,
int keylength));
void SSL_set_tmp_ecdh_callback(SSL *ssl,
EC_KEY *(*ecdh) (SSL *ssl, int is_export,
int keylength));
# endif
const COMP_METHOD *SSL_get_current_compression(SSL *s);
const COMP_METHOD *SSL_get_current_expansion(SSL *s);
const char *SSL_COMP_get_name(const COMP_METHOD *comp);
STACK_OF(SSL_COMP) *SSL_COMP_get_compression_methods(void);
STACK_OF(SSL_COMP) *SSL_COMP_set0_compression_methods(STACK_OF(SSL_COMP)
*meths);
void SSL_COMP_free_compression_methods(void);
int SSL_COMP_add_compression_method(int id, COMP_METHOD *cm);
const SSL_CIPHER *SSL_CIPHER_find(SSL *ssl, const unsigned char *ptr);
/* TLS extensions functions */
int SSL_set_session_ticket_ext(SSL *s, void *ext_data, int ext_len);
int SSL_set_session_ticket_ext_cb(SSL *s, tls_session_ticket_ext_cb_fn cb,
void *arg);
/* Pre-shared secret session resumption functions */
int SSL_set_session_secret_cb(SSL *s,
tls_session_secret_cb_fn tls_session_secret_cb,
void *arg);
void SSL_set_debug(SSL *s, int debug);
int SSL_cache_hit(SSL *s);
int SSL_is_server(SSL *s);
SSL_CONF_CTX *SSL_CONF_CTX_new(void);
int SSL_CONF_CTX_finish(SSL_CONF_CTX *cctx);
void SSL_CONF_CTX_free(SSL_CONF_CTX *cctx);
unsigned int SSL_CONF_CTX_set_flags(SSL_CONF_CTX *cctx, unsigned int flags);
unsigned int SSL_CONF_CTX_clear_flags(SSL_CONF_CTX *cctx, unsigned int flags);
int SSL_CONF_CTX_set1_prefix(SSL_CONF_CTX *cctx, const char *pre);
void SSL_CONF_CTX_set_ssl(SSL_CONF_CTX *cctx, SSL *ssl);
void SSL_CONF_CTX_set_ssl_ctx(SSL_CONF_CTX *cctx, SSL_CTX *ctx);
int SSL_CONF_cmd(SSL_CONF_CTX *cctx, const char *cmd, const char *value);
int SSL_CONF_cmd_argv(SSL_CONF_CTX *cctx, int *pargc, char ***pargv);
int SSL_CONF_cmd_value_type(SSL_CONF_CTX *cctx, const char *cmd);
# ifndef OPENSSL_NO_SSL_TRACE
void SSL_trace(int write_p, int version, int content_type,
const void *buf, size_t len, SSL *ssl, void *arg);
const char *SSL_CIPHER_standard_name(const SSL_CIPHER *c);
# endif
# ifndef OPENSSL_NO_UNIT_TEST
const struct openssl_ssl_test_functions *SSL_test_functions(void);
# endif
/* BEGIN ERROR CODES */
/*
* The following lines are auto generated by the script mkerr.pl. Any changes
* made after this point may be overwritten when the script is next run.
*/
void ERR_load_SSL_strings(void);
/* Error codes for the SSL functions. */
/* Function codes. */
# define SSL_F_CHECK_SUITEB_CIPHER_LIST 331
# define SSL_F_CLIENT_CERTIFICATE 100
# define SSL_F_CLIENT_FINISHED 167
# define SSL_F_CLIENT_HELLO 101
# define SSL_F_CLIENT_MASTER_KEY 102
# define SSL_F_D2I_SSL_SESSION 103
# define SSL_F_DO_DTLS1_WRITE 245
# define SSL_F_DO_SSL3_WRITE 104
# define SSL_F_DTLS1_ACCEPT 246
# define SSL_F_DTLS1_ADD_CERT_TO_BUF 295
# define SSL_F_DTLS1_BUFFER_RECORD 247
# define SSL_F_DTLS1_CHECK_TIMEOUT_NUM 316
# define SSL_F_DTLS1_CLIENT_HELLO 248
# define SSL_F_DTLS1_CONNECT 249
# define SSL_F_DTLS1_ENC 250
# define SSL_F_DTLS1_GET_HELLO_VERIFY 251
# define SSL_F_DTLS1_GET_MESSAGE 252
# define SSL_F_DTLS1_GET_MESSAGE_FRAGMENT 253
# define SSL_F_DTLS1_GET_RECORD 254
# define SSL_F_DTLS1_HANDLE_TIMEOUT 297
# define SSL_F_DTLS1_HEARTBEAT 305
# define SSL_F_DTLS1_OUTPUT_CERT_CHAIN 255
# define SSL_F_DTLS1_PREPROCESS_FRAGMENT 288
# define SSL_F_DTLS1_PROCESS_BUFFERED_RECORDS 424
# define SSL_F_DTLS1_PROCESS_OUT_OF_SEQ_MESSAGE 256
# define SSL_F_DTLS1_PROCESS_RECORD 257
# define SSL_F_DTLS1_READ_BYTES 258
# define SSL_F_DTLS1_READ_FAILED 259
# define SSL_F_DTLS1_SEND_CERTIFICATE_REQUEST 260
# define SSL_F_DTLS1_SEND_CLIENT_CERTIFICATE 261
# define SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE 262
# define SSL_F_DTLS1_SEND_CLIENT_VERIFY 263
# define SSL_F_DTLS1_SEND_HELLO_VERIFY_REQUEST 264
# define SSL_F_DTLS1_SEND_SERVER_CERTIFICATE 265
# define SSL_F_DTLS1_SEND_SERVER_HELLO 266
# define SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE 267
# define SSL_F_DTLS1_WRITE_APP_DATA_BYTES 268
# define SSL_F_GET_CLIENT_FINISHED 105
# define SSL_F_GET_CLIENT_HELLO 106
# define SSL_F_GET_CLIENT_MASTER_KEY 107
# define SSL_F_GET_SERVER_FINISHED 108
# define SSL_F_GET_SERVER_HELLO 109
# define SSL_F_GET_SERVER_STATIC_DH_KEY 340
# define SSL_F_GET_SERVER_VERIFY 110
# define SSL_F_I2D_SSL_SESSION 111
# define SSL_F_READ_N 112
# define SSL_F_REQUEST_CERTIFICATE 113
# define SSL_F_SERVER_FINISH 239
# define SSL_F_SERVER_HELLO 114
# define SSL_F_SERVER_VERIFY 240
# define SSL_F_SSL23_ACCEPT 115
# define SSL_F_SSL23_CLIENT_HELLO 116
# define SSL_F_SSL23_CONNECT 117
# define SSL_F_SSL23_GET_CLIENT_HELLO 118
# define SSL_F_SSL23_GET_SERVER_HELLO 119
# define SSL_F_SSL23_PEEK 237
# define SSL_F_SSL23_READ 120
# define SSL_F_SSL23_WRITE 121
# define SSL_F_SSL2_ACCEPT 122
# define SSL_F_SSL2_CONNECT 123
# define SSL_F_SSL2_ENC_INIT 124
# define SSL_F_SSL2_GENERATE_KEY_MATERIAL 241
# define SSL_F_SSL2_PEEK 234
# define SSL_F_SSL2_READ 125
# define SSL_F_SSL2_READ_INTERNAL 236
# define SSL_F_SSL2_SET_CERTIFICATE 126
# define SSL_F_SSL2_WRITE 127
# define SSL_F_SSL3_ACCEPT 128
# define SSL_F_SSL3_ADD_CERT_TO_BUF 296
# define SSL_F_SSL3_CALLBACK_CTRL 233
# define SSL_F_SSL3_CHANGE_CIPHER_STATE 129
# define SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM 130
# define SSL_F_SSL3_CHECK_CLIENT_HELLO 304
# define SSL_F_SSL3_CHECK_FINISHED 339
# define SSL_F_SSL3_CLIENT_HELLO 131
# define SSL_F_SSL3_CONNECT 132
# define SSL_F_SSL3_CTRL 213
# define SSL_F_SSL3_CTX_CTRL 133
# define SSL_F_SSL3_DIGEST_CACHED_RECORDS 293
# define SSL_F_SSL3_DO_CHANGE_CIPHER_SPEC 292
# define SSL_F_SSL3_ENC 134
# define SSL_F_SSL3_GENERATE_KEY_BLOCK 238
# define SSL_F_SSL3_GENERATE_MASTER_SECRET 388
# define SSL_F_SSL3_GET_CERTIFICATE_REQUEST 135
# define SSL_F_SSL3_GET_CERT_STATUS 289
# define SSL_F_SSL3_GET_CERT_VERIFY 136
# define SSL_F_SSL3_GET_CLIENT_CERTIFICATE 137
# define SSL_F_SSL3_GET_CLIENT_HELLO 138
# define SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE 139
# define SSL_F_SSL3_GET_FINISHED 140
# define SSL_F_SSL3_GET_KEY_EXCHANGE 141
# define SSL_F_SSL3_GET_MESSAGE 142
# define SSL_F_SSL3_GET_NEW_SESSION_TICKET 283
# define SSL_F_SSL3_GET_NEXT_PROTO 306
# define SSL_F_SSL3_GET_RECORD 143
# define SSL_F_SSL3_GET_SERVER_CERTIFICATE 144
# define SSL_F_SSL3_GET_SERVER_DONE 145
# define SSL_F_SSL3_GET_SERVER_HELLO 146
# define SSL_F_SSL3_HANDSHAKE_MAC 285
# define SSL_F_SSL3_NEW_SESSION_TICKET 287
# define SSL_F_SSL3_OUTPUT_CERT_CHAIN 147
# define SSL_F_SSL3_PEEK 235
# define SSL_F_SSL3_READ_BYTES 148
# define SSL_F_SSL3_READ_N 149
# define SSL_F_SSL3_SEND_CERTIFICATE_REQUEST 150
# define SSL_F_SSL3_SEND_CLIENT_CERTIFICATE 151
# define SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE 152
# define SSL_F_SSL3_SEND_CLIENT_VERIFY 153
# define SSL_F_SSL3_SEND_SERVER_CERTIFICATE 154
# define SSL_F_SSL3_SEND_SERVER_HELLO 242
# define SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE 155
# define SSL_F_SSL3_SETUP_KEY_BLOCK 157
# define SSL_F_SSL3_SETUP_READ_BUFFER 156
# define SSL_F_SSL3_SETUP_WRITE_BUFFER 291
# define SSL_F_SSL3_WRITE_BYTES 158
# define SSL_F_SSL3_WRITE_PENDING 159
# define SSL_F_SSL_ADD_CERT_CHAIN 318
# define SSL_F_SSL_ADD_CERT_TO_BUF 319
# define SSL_F_SSL_ADD_CLIENTHELLO_RENEGOTIATE_EXT 298
# define SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT 277
# define SSL_F_SSL_ADD_CLIENTHELLO_USE_SRTP_EXT 307
# define SSL_F_SSL_ADD_DIR_CERT_SUBJECTS_TO_STACK 215
# define SSL_F_SSL_ADD_FILE_CERT_SUBJECTS_TO_STACK 216
# define SSL_F_SSL_ADD_SERVERHELLO_RENEGOTIATE_EXT 299
# define SSL_F_SSL_ADD_SERVERHELLO_TLSEXT 278
# define SSL_F_SSL_ADD_SERVERHELLO_USE_SRTP_EXT 308
# define SSL_F_SSL_BAD_METHOD 160
# define SSL_F_SSL_BUILD_CERT_CHAIN 332
# define SSL_F_SSL_BYTES_TO_CIPHER_LIST 161
# define SSL_F_SSL_CERT_DUP 221
# define SSL_F_SSL_CERT_INST 222
# define SSL_F_SSL_CERT_INSTANTIATE 214
# define SSL_F_SSL_CERT_NEW 162
# define SSL_F_SSL_CHECK_PRIVATE_KEY 163
# define SSL_F_SSL_CHECK_SERVERHELLO_TLSEXT 280
# define SSL_F_SSL_CHECK_SRVR_ECC_CERT_AND_ALG 279
# define SSL_F_SSL_CIPHER_PROCESS_RULESTR 230
# define SSL_F_SSL_CIPHER_STRENGTH_SORT 231
# define SSL_F_SSL_CLEAR 164
# define SSL_F_SSL_COMP_ADD_COMPRESSION_METHOD 165
# define SSL_F_SSL_CONF_CMD 334
# define SSL_F_SSL_CREATE_CIPHER_LIST 166
# define SSL_F_SSL_CTRL 232
# define SSL_F_SSL_CTX_CHECK_PRIVATE_KEY 168
# define SSL_F_SSL_CTX_MAKE_PROFILES 309
# define SSL_F_SSL_CTX_NEW 169
# define SSL_F_SSL_CTX_SET_CIPHER_LIST 269
# define SSL_F_SSL_CTX_SET_CLIENT_CERT_ENGINE 290
# define SSL_F_SSL_CTX_SET_PURPOSE 226
# define SSL_F_SSL_CTX_SET_SESSION_ID_CONTEXT 219
# define SSL_F_SSL_CTX_SET_SSL_VERSION 170
# define SSL_F_SSL_CTX_SET_TRUST 229
# define SSL_F_SSL_CTX_USE_CERTIFICATE 171
# define SSL_F_SSL_CTX_USE_CERTIFICATE_ASN1 172
# define SSL_F_SSL_CTX_USE_CERTIFICATE_CHAIN_FILE 220
# define SSL_F_SSL_CTX_USE_CERTIFICATE_FILE 173
# define SSL_F_SSL_CTX_USE_PRIVATEKEY 174
# define SSL_F_SSL_CTX_USE_PRIVATEKEY_ASN1 175
# define SSL_F_SSL_CTX_USE_PRIVATEKEY_FILE 176
# define SSL_F_SSL_CTX_USE_PSK_IDENTITY_HINT 272
# define SSL_F_SSL_CTX_USE_RSAPRIVATEKEY 177
# define SSL_F_SSL_CTX_USE_RSAPRIVATEKEY_ASN1 178
# define SSL_F_SSL_CTX_USE_RSAPRIVATEKEY_FILE 179
# define SSL_F_SSL_CTX_USE_SERVERINFO 336
# define SSL_F_SSL_CTX_USE_SERVERINFO_FILE 337
# define SSL_F_SSL_DO_HANDSHAKE 180
# define SSL_F_SSL_GET_NEW_SESSION 181
# define SSL_F_SSL_GET_PREV_SESSION 217
# define SSL_F_SSL_GET_SERVER_CERT_INDEX 322
# define SSL_F_SSL_GET_SERVER_SEND_CERT 182
# define SSL_F_SSL_GET_SERVER_SEND_PKEY 317
# define SSL_F_SSL_GET_SIGN_PKEY 183
# define SSL_F_SSL_INIT_WBIO_BUFFER 184
# define SSL_F_SSL_LOAD_CLIENT_CA_FILE 185
# define SSL_F_SSL_NEW 186
# define SSL_F_SSL_PARSE_CLIENTHELLO_RENEGOTIATE_EXT 300
# define SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT 302
# define SSL_F_SSL_PARSE_CLIENTHELLO_USE_SRTP_EXT 310
# define SSL_F_SSL_PARSE_SERVERHELLO_RENEGOTIATE_EXT 301
# define SSL_F_SSL_PARSE_SERVERHELLO_TLSEXT 303
# define SSL_F_SSL_PARSE_SERVERHELLO_USE_SRTP_EXT 311
# define SSL_F_SSL_PEEK 270
# define SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT 281
# define SSL_F_SSL_PREPARE_SERVERHELLO_TLSEXT 282
# define SSL_F_SSL_READ 223
# define SSL_F_SSL_RSA_PRIVATE_DECRYPT 187
# define SSL_F_SSL_RSA_PUBLIC_ENCRYPT 188
# define SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT 320
# define SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT 321
# define SSL_F_SSL_SESSION_DUP 348
# define SSL_F_SSL_SESSION_NEW 189
# define SSL_F_SSL_SESSION_PRINT_FP 190
# define SSL_F_SSL_SESSION_SET1_ID_CONTEXT 312
# define SSL_F_SSL_SESS_CERT_NEW 225
# define SSL_F_SSL_SET_CERT 191
# define SSL_F_SSL_SET_CIPHER_LIST 271
# define SSL_F_SSL_SET_FD 192
# define SSL_F_SSL_SET_PKEY 193
# define SSL_F_SSL_SET_PURPOSE 227
# define SSL_F_SSL_SET_RFD 194
# define SSL_F_SSL_SET_SESSION 195
# define SSL_F_SSL_SET_SESSION_ID_CONTEXT 218
# define SSL_F_SSL_SET_SESSION_TICKET_EXT 294
# define SSL_F_SSL_SET_TRUST 228
# define SSL_F_SSL_SET_WFD 196
# define SSL_F_SSL_SHUTDOWN 224
# define SSL_F_SSL_SRP_CTX_INIT 313
# define SSL_F_SSL_UNDEFINED_CONST_FUNCTION 243
# define SSL_F_SSL_UNDEFINED_FUNCTION 197
# define SSL_F_SSL_UNDEFINED_VOID_FUNCTION 244
# define SSL_F_SSL_USE_CERTIFICATE 198
# define SSL_F_SSL_USE_CERTIFICATE_ASN1 199
# define SSL_F_SSL_USE_CERTIFICATE_FILE 200
# define SSL_F_SSL_USE_PRIVATEKEY 201
# define SSL_F_SSL_USE_PRIVATEKEY_ASN1 202
# define SSL_F_SSL_USE_PRIVATEKEY_FILE 203
# define SSL_F_SSL_USE_PSK_IDENTITY_HINT 273
# define SSL_F_SSL_USE_RSAPRIVATEKEY 204
# define SSL_F_SSL_USE_RSAPRIVATEKEY_ASN1 205
# define SSL_F_SSL_USE_RSAPRIVATEKEY_FILE 206
# define SSL_F_SSL_VERIFY_CERT_CHAIN 207
# define SSL_F_SSL_WRITE 208
# define SSL_F_TLS12_CHECK_PEER_SIGALG 333
# define SSL_F_TLS1_CERT_VERIFY_MAC 286
# define SSL_F_TLS1_CHANGE_CIPHER_STATE 209
# define SSL_F_TLS1_CHECK_SERVERHELLO_TLSEXT 274
# define SSL_F_TLS1_ENC 210
# define SSL_F_TLS1_EXPORT_KEYING_MATERIAL 314
# define SSL_F_TLS1_GET_CURVELIST 338
# define SSL_F_TLS1_HEARTBEAT 315
# define SSL_F_TLS1_PREPARE_CLIENTHELLO_TLSEXT 275
# define SSL_F_TLS1_PREPARE_SERVERHELLO_TLSEXT 276
# define SSL_F_TLS1_PRF 284
# define SSL_F_TLS1_SETUP_KEY_BLOCK 211
# define SSL_F_TLS1_SET_SERVER_SIGALGS 335
# define SSL_F_WRITE_PENDING 212
/* Reason codes. */
# define SSL_R_APP_DATA_IN_HANDSHAKE 100
# define SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT 272
# define SSL_R_BAD_ALERT_RECORD 101
# define SSL_R_BAD_AUTHENTICATION_TYPE 102
# define SSL_R_BAD_CHANGE_CIPHER_SPEC 103
# define SSL_R_BAD_CHECKSUM 104
# define SSL_R_BAD_DATA 390
# define SSL_R_BAD_DATA_RETURNED_BY_CALLBACK 106
# define SSL_R_BAD_DECOMPRESSION 107
# define SSL_R_BAD_DH_G_LENGTH 108
# define SSL_R_BAD_DH_G_VALUE 375
# define SSL_R_BAD_DH_PUB_KEY_LENGTH 109
# define SSL_R_BAD_DH_PUB_KEY_VALUE 393
# define SSL_R_BAD_DH_P_LENGTH 110
# define SSL_R_BAD_DH_P_VALUE 395
# define SSL_R_BAD_DIGEST_LENGTH 111
# define SSL_R_BAD_DSA_SIGNATURE 112
# define SSL_R_BAD_ECC_CERT 304
# define SSL_R_BAD_ECDSA_SIGNATURE 305
# define SSL_R_BAD_ECPOINT 306
# define SSL_R_BAD_HANDSHAKE_LENGTH 332
# define SSL_R_BAD_HELLO_REQUEST 105
# define SSL_R_BAD_LENGTH 271
# define SSL_R_BAD_MAC_DECODE 113
# define SSL_R_BAD_MAC_LENGTH 333
# define SSL_R_BAD_MESSAGE_TYPE 114
# define SSL_R_BAD_PACKET_LENGTH 115
# define SSL_R_BAD_PROTOCOL_VERSION_NUMBER 116
# define SSL_R_BAD_PSK_IDENTITY_HINT_LENGTH 316
# define SSL_R_BAD_RESPONSE_ARGUMENT 117
# define SSL_R_BAD_RSA_DECRYPT 118
# define SSL_R_BAD_RSA_ENCRYPT 119
# define SSL_R_BAD_RSA_E_LENGTH 120
# define SSL_R_BAD_RSA_MODULUS_LENGTH 121
# define SSL_R_BAD_RSA_SIGNATURE 122
# define SSL_R_BAD_SIGNATURE 123
# define SSL_R_BAD_SRP_A_LENGTH 347
# define SSL_R_BAD_SRP_B_LENGTH 348
# define SSL_R_BAD_SRP_G_LENGTH 349
# define SSL_R_BAD_SRP_N_LENGTH 350
# define SSL_R_BAD_SRP_PARAMETERS 371
# define SSL_R_BAD_SRP_S_LENGTH 351
# define SSL_R_BAD_SRTP_MKI_VALUE 352
# define SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST 353
# define SSL_R_BAD_SSL_FILETYPE 124
# define SSL_R_BAD_SSL_SESSION_ID_LENGTH 125
# define SSL_R_BAD_STATE 126
# define SSL_R_BAD_VALUE 384
# define SSL_R_BAD_WRITE_RETRY 127
# define SSL_R_BIO_NOT_SET 128
# define SSL_R_BLOCK_CIPHER_PAD_IS_WRONG 129
# define SSL_R_BN_LIB 130
# define SSL_R_CA_DN_LENGTH_MISMATCH 131
# define SSL_R_CA_DN_TOO_LONG 132
# define SSL_R_CCS_RECEIVED_EARLY 133
# define SSL_R_CERTIFICATE_VERIFY_FAILED 134
# define SSL_R_CERT_CB_ERROR 377
# define SSL_R_CERT_LENGTH_MISMATCH 135
# define SSL_R_CHALLENGE_IS_DIFFERENT 136
# define SSL_R_CIPHER_CODE_WRONG_LENGTH 137
# define SSL_R_CIPHER_OR_HASH_UNAVAILABLE 138
# define SSL_R_CIPHER_TABLE_SRC_ERROR 139
# define SSL_R_CLIENTHELLO_TLSEXT 226
# define SSL_R_COMPRESSED_LENGTH_TOO_LONG 140
# define SSL_R_COMPRESSION_DISABLED 343
# define SSL_R_COMPRESSION_FAILURE 141
# define SSL_R_COMPRESSION_ID_NOT_WITHIN_PRIVATE_RANGE 307
# define SSL_R_COMPRESSION_LIBRARY_ERROR 142
# define SSL_R_CONNECTION_ID_IS_DIFFERENT 143
# define SSL_R_CONNECTION_TYPE_NOT_SET 144
# define SSL_R_COOKIE_MISMATCH 308
# define SSL_R_DATA_BETWEEN_CCS_AND_FINISHED 145
# define SSL_R_DATA_LENGTH_TOO_LONG 146
# define SSL_R_DECRYPTION_FAILED 147
# define SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC 281
# define SSL_R_DH_KEY_TOO_SMALL 372
# define SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG 148
# define SSL_R_DIGEST_CHECK_FAILED 149
# define SSL_R_DTLS_MESSAGE_TOO_BIG 334
# define SSL_R_DUPLICATE_COMPRESSION_ID 309
# define SSL_R_ECC_CERT_NOT_FOR_KEY_AGREEMENT 317
# define SSL_R_ECC_CERT_NOT_FOR_SIGNING 318
# define SSL_R_ECC_CERT_SHOULD_HAVE_RSA_SIGNATURE 322
# define SSL_R_ECC_CERT_SHOULD_HAVE_SHA1_SIGNATURE 323
# define SSL_R_ECDH_REQUIRED_FOR_SUITEB_MODE 374
# define SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER 310
# define SSL_R_EMPTY_SRTP_PROTECTION_PROFILE_LIST 354
# define SSL_R_ENCRYPTED_LENGTH_TOO_LONG 150
# define SSL_R_ERROR_GENERATING_TMP_RSA_KEY 282
# define SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST 151
# define SSL_R_EXCESSIVE_MESSAGE_SIZE 152
# define SSL_R_EXTRA_DATA_IN_MESSAGE 153
# define SSL_R_GOT_A_FIN_BEFORE_A_CCS 154
# define SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS 355
# define SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION 356
# define SSL_R_HTTPS_PROXY_REQUEST 155
# define SSL_R_HTTP_REQUEST 156
# define SSL_R_ILLEGAL_PADDING 283
# define SSL_R_ILLEGAL_SUITEB_DIGEST 380
# define SSL_R_INAPPROPRIATE_FALLBACK 373
# define SSL_R_INCONSISTENT_COMPRESSION 340
# define SSL_R_INVALID_CHALLENGE_LENGTH 158
# define SSL_R_INVALID_COMMAND 280
# define SSL_R_INVALID_COMPRESSION_ALGORITHM 341
# define SSL_R_INVALID_NULL_CMD_NAME 385
# define SSL_R_INVALID_PURPOSE 278
# define SSL_R_INVALID_SERVERINFO_DATA 388
# define SSL_R_INVALID_SRP_USERNAME 357
# define SSL_R_INVALID_STATUS_RESPONSE 328
# define SSL_R_INVALID_TICKET_KEYS_LENGTH 325
# define SSL_R_INVALID_TRUST 279
# define SSL_R_KEY_ARG_TOO_LONG 284
# define SSL_R_KRB5 285
# define SSL_R_KRB5_C_CC_PRINC 286
# define SSL_R_KRB5_C_GET_CRED 287
# define SSL_R_KRB5_C_INIT 288
# define SSL_R_KRB5_C_MK_REQ 289
# define SSL_R_KRB5_S_BAD_TICKET 290
# define SSL_R_KRB5_S_INIT 291
# define SSL_R_KRB5_S_RD_REQ 292
# define SSL_R_KRB5_S_TKT_EXPIRED 293
# define SSL_R_KRB5_S_TKT_NYV 294
# define SSL_R_KRB5_S_TKT_SKEW 295
# define SSL_R_LENGTH_MISMATCH 159
# define SSL_R_LENGTH_TOO_SHORT 160
# define SSL_R_LIBRARY_BUG 274
# define SSL_R_LIBRARY_HAS_NO_CIPHERS 161
# define SSL_R_MESSAGE_TOO_LONG 296
# define SSL_R_MISSING_DH_DSA_CERT 162
# define SSL_R_MISSING_DH_KEY 163
# define SSL_R_MISSING_DH_RSA_CERT 164
# define SSL_R_MISSING_DSA_SIGNING_CERT 165
# define SSL_R_MISSING_ECDH_CERT 382
# define SSL_R_MISSING_ECDSA_SIGNING_CERT 381
# define SSL_R_MISSING_EXPORT_TMP_DH_KEY 166
# define SSL_R_MISSING_EXPORT_TMP_RSA_KEY 167
# define SSL_R_MISSING_RSA_CERTIFICATE 168
# define SSL_R_MISSING_RSA_ENCRYPTING_CERT 169
# define SSL_R_MISSING_RSA_SIGNING_CERT 170
# define SSL_R_MISSING_SRP_PARAM 358
# define SSL_R_MISSING_TMP_DH_KEY 171
# define SSL_R_MISSING_TMP_ECDH_KEY 311
# define SSL_R_MISSING_TMP_RSA_KEY 172
# define SSL_R_MISSING_TMP_RSA_PKEY 173
# define SSL_R_MISSING_VERIFY_MESSAGE 174
# define SSL_R_MULTIPLE_SGC_RESTARTS 346
# define SSL_R_NON_SSLV2_INITIAL_PACKET 175
# define SSL_R_NO_CERTIFICATES_RETURNED 176
# define SSL_R_NO_CERTIFICATE_ASSIGNED 177
# define SSL_R_NO_CERTIFICATE_RETURNED 178
# define SSL_R_NO_CERTIFICATE_SET 179
# define SSL_R_NO_CERTIFICATE_SPECIFIED 180
# define SSL_R_NO_CIPHERS_AVAILABLE 181
# define SSL_R_NO_CIPHERS_PASSED 182
# define SSL_R_NO_CIPHERS_SPECIFIED 183
# define SSL_R_NO_CIPHER_LIST 184
# define SSL_R_NO_CIPHER_MATCH 185
# define SSL_R_NO_CLIENT_CERT_METHOD 331
# define SSL_R_NO_CLIENT_CERT_RECEIVED 186
# define SSL_R_NO_COMPRESSION_SPECIFIED 187
# define SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER 330
# define SSL_R_NO_METHOD_SPECIFIED 188
# define SSL_R_NO_PEM_EXTENSIONS 389
# define SSL_R_NO_PRIVATEKEY 189
# define SSL_R_NO_PRIVATE_KEY_ASSIGNED 190
# define SSL_R_NO_PROTOCOLS_AVAILABLE 191
# define SSL_R_NO_PUBLICKEY 192
# define SSL_R_NO_RENEGOTIATION 339
# define SSL_R_NO_REQUIRED_DIGEST 324
# define SSL_R_NO_SHARED_CIPHER 193
# define SSL_R_NO_SHARED_SIGATURE_ALGORITHMS 376
# define SSL_R_NO_SRTP_PROFILES 359
# define SSL_R_NO_VERIFY_CALLBACK 194
# define SSL_R_NULL_SSL_CTX 195
# define SSL_R_NULL_SSL_METHOD_PASSED 196
# define SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED 197
# define SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED 344
# define SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE 387
# define SSL_R_ONLY_TLS_1_2_ALLOWED_IN_SUITEB_MODE 379
# define SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE 297
# define SSL_R_OPAQUE_PRF_INPUT_TOO_LONG 327
# define SSL_R_PACKET_LENGTH_TOO_LONG 198
# define SSL_R_PARSE_TLSEXT 227
# define SSL_R_PATH_TOO_LONG 270
# define SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE 199
# define SSL_R_PEER_ERROR 200
# define SSL_R_PEER_ERROR_CERTIFICATE 201
# define SSL_R_PEER_ERROR_NO_CERTIFICATE 202
# define SSL_R_PEER_ERROR_NO_CIPHER 203
# define SSL_R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE 204
# define SSL_R_PEM_NAME_BAD_PREFIX 391
# define SSL_R_PEM_NAME_TOO_SHORT 392
# define SSL_R_PRE_MAC_LENGTH_TOO_LONG 205
# define SSL_R_PROBLEMS_MAPPING_CIPHER_FUNCTIONS 206
# define SSL_R_PROTOCOL_IS_SHUTDOWN 207
# define SSL_R_PSK_IDENTITY_NOT_FOUND 223
# define SSL_R_PSK_NO_CLIENT_CB 224
# define SSL_R_PSK_NO_SERVER_CB 225
# define SSL_R_PUBLIC_KEY_ENCRYPT_ERROR 208
# define SSL_R_PUBLIC_KEY_IS_NOT_RSA 209
# define SSL_R_PUBLIC_KEY_NOT_RSA 210
# define SSL_R_READ_BIO_NOT_SET 211
# define SSL_R_READ_TIMEOUT_EXPIRED 312
# define SSL_R_READ_WRONG_PACKET_TYPE 212
# define SSL_R_RECORD_LENGTH_MISMATCH 213
# define SSL_R_RECORD_TOO_LARGE 214
# define SSL_R_RECORD_TOO_SMALL 298
# define SSL_R_RENEGOTIATE_EXT_TOO_LONG 335
# define SSL_R_RENEGOTIATION_ENCODING_ERR 336
# define SSL_R_RENEGOTIATION_MISMATCH 337
# define SSL_R_REQUIRED_CIPHER_MISSING 215
# define SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING 342
# define SSL_R_REUSE_CERT_LENGTH_NOT_ZERO 216
# define SSL_R_REUSE_CERT_TYPE_NOT_ZERO 217
# define SSL_R_REUSE_CIPHER_LIST_NOT_ZERO 218
# define SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING 345
# define SSL_R_SERVERHELLO_TLSEXT 275
# define SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED 277
# define SSL_R_SHORT_READ 219
# define SSL_R_SHUTDOWN_WHILE_IN_INIT 407
# define SSL_R_SIGNATURE_ALGORITHMS_ERROR 360
# define SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE 220
# define SSL_R_SRP_A_CALC 361
# define SSL_R_SRTP_COULD_NOT_ALLOCATE_PROFILES 362
# define SSL_R_SRTP_PROTECTION_PROFILE_LIST_TOO_LONG 363
# define SSL_R_SRTP_UNKNOWN_PROTECTION_PROFILE 364
# define SSL_R_SSL23_DOING_SESSION_ID_REUSE 221
# define SSL_R_SSL2_CONNECTION_ID_TOO_LONG 299
# define SSL_R_SSL3_EXT_INVALID_ECPOINTFORMAT 321
# define SSL_R_SSL3_EXT_INVALID_SERVERNAME 319
# define SSL_R_SSL3_EXT_INVALID_SERVERNAME_TYPE 320
# define SSL_R_SSL3_SESSION_ID_TOO_LONG 300
# define SSL_R_SSL3_SESSION_ID_TOO_SHORT 222
# define SSL_R_SSLV3_ALERT_BAD_CERTIFICATE 1042
# define SSL_R_SSLV3_ALERT_BAD_RECORD_MAC 1020
# define SSL_R_SSLV3_ALERT_CERTIFICATE_EXPIRED 1045
# define SSL_R_SSLV3_ALERT_CERTIFICATE_REVOKED 1044
# define SSL_R_SSLV3_ALERT_CERTIFICATE_UNKNOWN 1046
# define SSL_R_SSLV3_ALERT_DECOMPRESSION_FAILURE 1030
# define SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE 1040
# define SSL_R_SSLV3_ALERT_ILLEGAL_PARAMETER 1047
# define SSL_R_SSLV3_ALERT_NO_CERTIFICATE 1041
# define SSL_R_SSLV3_ALERT_UNEXPECTED_MESSAGE 1010
# define SSL_R_SSLV3_ALERT_UNSUPPORTED_CERTIFICATE 1043
# define SSL_R_SSL_CTX_HAS_NO_DEFAULT_SSL_VERSION 228
# define SSL_R_SSL_HANDSHAKE_FAILURE 229
# define SSL_R_SSL_LIBRARY_HAS_NO_CIPHERS 230
# define SSL_R_SSL_SESSION_ID_CALLBACK_FAILED 301
# define SSL_R_SSL_SESSION_ID_CONFLICT 302
# define SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG 273
# define SSL_R_SSL_SESSION_ID_HAS_BAD_LENGTH 303
# define SSL_R_SSL_SESSION_ID_IS_DIFFERENT 231
# define SSL_R_TLSV1_ALERT_ACCESS_DENIED 1049
# define SSL_R_TLSV1_ALERT_DECODE_ERROR 1050
# define SSL_R_TLSV1_ALERT_DECRYPTION_FAILED 1021
# define SSL_R_TLSV1_ALERT_DECRYPT_ERROR 1051
# define SSL_R_TLSV1_ALERT_EXPORT_RESTRICTION 1060
# define SSL_R_TLSV1_ALERT_INAPPROPRIATE_FALLBACK 1086
# define SSL_R_TLSV1_ALERT_INSUFFICIENT_SECURITY 1071
# define SSL_R_TLSV1_ALERT_INTERNAL_ERROR 1080
# define SSL_R_TLSV1_ALERT_NO_RENEGOTIATION 1100
# define SSL_R_TLSV1_ALERT_PROTOCOL_VERSION 1070
# define SSL_R_TLSV1_ALERT_RECORD_OVERFLOW 1022
# define SSL_R_TLSV1_ALERT_UNKNOWN_CA 1048
# define SSL_R_TLSV1_ALERT_USER_CANCELLED 1090
# define SSL_R_TLSV1_BAD_CERTIFICATE_HASH_VALUE 1114
# define SSL_R_TLSV1_BAD_CERTIFICATE_STATUS_RESPONSE 1113
# define SSL_R_TLSV1_CERTIFICATE_UNOBTAINABLE 1111
# define SSL_R_TLSV1_UNRECOGNIZED_NAME 1112
# define SSL_R_TLSV1_UNSUPPORTED_EXTENSION 1110
# define SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER 232
# define SSL_R_TLS_HEARTBEAT_PEER_DOESNT_ACCEPT 365
# define SSL_R_TLS_HEARTBEAT_PENDING 366
# define SSL_R_TLS_ILLEGAL_EXPORTER_LABEL 367
# define SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST 157
# define SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST 233
# define SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG 234
# define SSL_R_TOO_MANY_WARN_ALERTS 409
# define SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER 235
# define SSL_R_UNABLE_TO_DECODE_DH_CERTS 236
# define SSL_R_UNABLE_TO_DECODE_ECDH_CERTS 313
# define SSL_R_UNABLE_TO_EXTRACT_PUBLIC_KEY 237
# define SSL_R_UNABLE_TO_FIND_DH_PARAMETERS 238
# define SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS 314
# define SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS 239
# define SSL_R_UNABLE_TO_FIND_SSL_METHOD 240
# define SSL_R_UNABLE_TO_LOAD_SSL2_MD5_ROUTINES 241
# define SSL_R_UNABLE_TO_LOAD_SSL3_MD5_ROUTINES 242
# define SSL_R_UNABLE_TO_LOAD_SSL3_SHA1_ROUTINES 243
# define SSL_R_UNEXPECTED_MESSAGE 244
# define SSL_R_UNEXPECTED_RECORD 245
# define SSL_R_UNINITIALIZED 276
# define SSL_R_UNKNOWN_ALERT_TYPE 246
# define SSL_R_UNKNOWN_CERTIFICATE_TYPE 247
# define SSL_R_UNKNOWN_CIPHER_RETURNED 248
# define SSL_R_UNKNOWN_CIPHER_TYPE 249
# define SSL_R_UNKNOWN_CMD_NAME 386
# define SSL_R_UNKNOWN_DIGEST 368
# define SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE 250
# define SSL_R_UNKNOWN_PKEY_TYPE 251
# define SSL_R_UNKNOWN_PROTOCOL 252
# define SSL_R_UNKNOWN_REMOTE_ERROR_TYPE 253
# define SSL_R_UNKNOWN_SSL_VERSION 254
# define SSL_R_UNKNOWN_STATE 255
# define SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED 338
# define SSL_R_UNSUPPORTED_CIPHER 256
# define SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM 257
# define SSL_R_UNSUPPORTED_DIGEST_TYPE 326
# define SSL_R_UNSUPPORTED_ELLIPTIC_CURVE 315
# define SSL_R_UNSUPPORTED_PROTOCOL 258
# define SSL_R_UNSUPPORTED_SSL_VERSION 259
# define SSL_R_UNSUPPORTED_STATUS_TYPE 329
# define SSL_R_USE_SRTP_NOT_NEGOTIATED 369
# define SSL_R_WRITE_BIO_NOT_SET 260
# define SSL_R_WRONG_CERTIFICATE_TYPE 383
# define SSL_R_WRONG_CIPHER_RETURNED 261
# define SSL_R_WRONG_CURVE 378
# define SSL_R_WRONG_MESSAGE_TYPE 262
# define SSL_R_WRONG_NUMBER_OF_KEY_BITS 263
# define SSL_R_WRONG_SIGNATURE_LENGTH 264
# define SSL_R_WRONG_SIGNATURE_SIZE 265
# define SSL_R_WRONG_SIGNATURE_TYPE 370
# define SSL_R_WRONG_SSL_VERSION 266
# define SSL_R_WRONG_VERSION_NUMBER 267
# define SSL_R_X509_LIB 268
# define SSL_R_X509_VERIFICATION_SETUP_PROBLEMS 269
#ifdef __cplusplus
}
#endif
#endif
|
898fb884b706aaeb283de4812340bb0bde8476dc
|
https://github.com/openssl/openssl
|
settings.php
|
php
|
<?php
$tmpl = new OCP\Template( 'user_openid', 'settings');
$identity=OCP\Config::getUserValue(OCP\USER::getUser(),'user_openid','identity','');
$tmpl->assign('identity',$identity);
OCP\Util::addscript('user_openid','settings');
return $tmpl->fetchPage();
?>
|
<?php
$tmpl = new OCP\Template( 'user_openid', 'settings');
$identity=OCP\Config::getUserValue(OCP\USER::getUser(),'user_openid','identity','');
$tmpl->assign('identity',htmlentities($identity));
OCP\Util::addscript('user_openid','settings');
return $tmpl->fetchPage();
?>
|
cc653a8a408adfb4d0cd532145668aacd85ad96c
|
https://github.com/owncloud/core
|
settings.tpl.php
|
php
|
<h1 class="attr-header">Mobile Options</h1>
<form action="" method="post" ng-non-bindable>
<?php include(erLhcoreClassDesign::designtpl('lhkernel/csfr_token.tpl.php'));?>
<?php if (isset($updated) && $updated == 'done') : $msg = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Settings updated'); ?>
<?php include(erLhcoreClassDesign::designtpl('lhkernel/alert_success.tpl.php'));?>
<?php endif; ?>
<div class="form-group">
<label><input type="checkbox" value="on" name="notifications" <?php isset($mb_options['notifications']) && ($mb_options['notifications'] == true) ? print 'checked="checked"' : ''?> /> Enable notifications</label><br/>
</div>
<div class="form-group">
<label>FCM Key</label>
<input type="text" class="form-control" name="fcm_key" value="<?php isset($mb_options['fcm_key']) ? print $mb_options['fcm_key'] : ''?>" />
</div>
<input type="submit" class="btn btn-secondary" name="StoreOptions" value="<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('system/buttons','Save'); ?>" />
</form>
|
<h1 class="attr-header">Mobile Options</h1>
<form action="" method="post" ng-non-bindable>
<?php include(erLhcoreClassDesign::designtpl('lhkernel/csfr_token.tpl.php'));?>
<?php if (isset($updated) && $updated == 'done') : $msg = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Settings updated'); ?>
<?php include(erLhcoreClassDesign::designtpl('lhkernel/alert_success.tpl.php'));?>
<?php endif; ?>
<div class="form-group">
<label><input type="checkbox" value="on" name="notifications" <?php isset($mb_options['notifications']) && ($mb_options['notifications'] == true) ? print 'checked="checked"' : ''?> /> Enable notifications</label><br/>
</div>
<div class="form-group">
<label>FCM Key</label>
<input type="text" class="form-control" name="fcm_key" value="<?php isset($mb_options['fcm_key']) ? print htmlspecialchars($mb_options['fcm_key']) : ''?>" />
</div>
<input type="submit" class="btn btn-secondary" name="StoreOptions" value="<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('system/buttons','Save'); ?>" />
</form>
|
162892013eb07b21461ceffe6702140acc0fef57
|
https://github.com/livehelperchat/livehelperchat
|
filebrowser.php
|
php
|
<?php
/**
* Basic File Browser for CKEditor
*
* Displays and selects file link to insert into CKEditor
*
* @package GetSimple
* @subpackage Files
*
* Version: 1.1 (2011-03-12)
*/
// Setup inclusions
include('inc/common.php');
login_cookie_check();
$filesSorted=null;$dirsSorted=null;
$path = (isset($_GET['path'])) ? "../data/uploads/".$_GET['path'] : "../data/uploads/";
$subPath = (isset($_GET['path'])) ? $_GET['path'] : "";
if(!path_is_safe($path,GSDATAUPLOADPATH)) die();
$returnid = isset($_GET['returnid']) ? var_out($_GET['returnid']) : "";
$func = (isset($_GET['func'])) ? $_GET['func'] : "";
$path = tsl($path);
// check if host uses Linux (used for displaying permissions
$isUnixHost = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? false : true);
$CKEditorFuncNum = isset($_GET['CKEditorFuncNum']) ? var_out($_GET['CKEditorFuncNum']) : '';
$sitepath = suggest_site_path();
$fullPath = $sitepath . "data/uploads/";
$type = isset($_GET['type']) ? var_out($_GET['type']) : '';
global $LANG;
$LANG_header = preg_replace('/(?:(?<=([a-z]{2}))).*/', '', $LANG);
?>
<!DOCTYPE html>
<html lang="<?php echo $LANG_header; ?>">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title><?php echo i18n_r('FILE_BROWSER'); ?></title>
<link rel="shortcut icon" href="favicon.png" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="template/style.php?v=<?php echo GSVERSION; ?>" media="screen" />
<style>
.wrapper, #maincontent, #imageTable { width: 100% }
</style>
<script type='text/javascript'>
function submitLink($funcNum, $url) {
<?php if (isset($_GET['returnid'])){ ?>
if(window.opener){
window.opener.document.getElementById('<?php echo $returnid; ?>').focus();
window.opener.document.getElementById('<?php echo $returnid; ?>').value=$url;
}
<?php
if (isset($_GET['func'])){
$func = @$_GET['func'];
?>
if(window.opener){
if(typeof window.opener.<?php echo $func; ?> == 'function') {
window.opener.<?php echo $func; ?>('<?php echo $returnid; ?>');
}
}
<?php
}
}
else { ?>
if(window.opener){
window.opener.CKEDITOR.tools.callFunction($funcNum, $url);
}
<?php } ?>
window.close();
}
</script>
</head>
<body id="filebrowser" >
<div class="wrapper">
<div id="maincontent">
<div class="main" style="border:none;">
<h3><?php echo i18n('UPLOADED_FILES'); ?><span id="filetypetoggle"> / <?php echo ($type == 'images' ? i18n('IMAGES') : i18n('SHOW_ALL') ); ?></span></h3>
<?php
$count="0";
$dircount="0";
$counter = "0";
$totalsize = 0;
$filesArray = array();
$dirsArray = array();
$filenames = getFiles($path);
if (count($filenames) != 0) {
foreach ($filenames as $file) {
if ($file == "." || $file == ".." || $file == ".htaccess" ){
// not a upload file
} elseif (is_dir($path . $file)) {
$dirsArray[$dircount]['name'] = $file;
$dircount++;
} else {
$filesArray[$count]['name'] = $file;
$ext = substr($file, strrpos($file, '.') + 1);
$extention = get_FileType($ext);
$filesArray[$count]['type'] = $extention;
clearstatcache();
$ss = @stat($path . $file);
$filesArray[$count]['date'] = @date('M j, Y',$ss['mtime']);
$filesArray[$count]['size'] = fSize($ss['size']);
$totalsize = $totalsize + $ss['size'];
$count++;
}
}
$filesSorted = subval_sort($filesArray,'name');
$dirsSorted = subval_sort($dirsArray,'name');
}
$pathParts=explode("/",$subPath);
$urlPath="";
echo '<div class="h5">/ <a href="?CKEditorFuncNum='.$CKEditorFuncNum.'&type='.$type.'">uploads</a> / ';
foreach ($pathParts as $pathPart){
if ($pathPart!=''){
$urlPath.=$pathPart."/";
echo '<a href="?path='.$urlPath.'&CKEditorFuncNum='.$CKEditorFuncNum.'&type='.$type.'&func='.$func.'">'.$pathPart.'</a> / ';
}
}
echo "</div>";
echo '<table class="highlight" id="imageTable">';
if (count($dirsSorted) != 0) {
foreach ($dirsSorted as $upload) {
echo '<tr class="All" >';
echo '<td class="" colspan="5">';
$adm = substr($path . $upload['name'] , 16);
if ($returnid!='') {
$returnlink = '&returnid='.$returnid;
} else {
$returnlink='';
}
if ($func!='') {
$funct = '&func='.$func;
} else {
$funct='';
}
echo '<img src="template/images/folder.png" width="11" /> <a href="filebrowser.php?path='.$adm.'&CKEditorFuncNum='.$CKEditorFuncNum.'&type='.$type.$returnlink.'&'.$funct.'" title="'. $upload['name'] .'" ><strong>'.$upload['name'].'</strong></a>';
echo '</td>';
echo '</tr>';
}
}
if (count($filesSorted) != 0) {
foreach ($filesSorted as $upload) {
$upload['name'] = rawurlencode($upload['name']);
$thumb = null; $thumbnailLink = null;
$subDir = ($subPath == '' ? '' : $subPath.'/');
$selectLink = 'title="'.i18n_r('SELECT_FILE').': '. htmlspecialchars($upload['name']) .'" href="javascript:void(0)" onclick="submitLink('.$CKEditorFuncNum.',\''.$fullPath.$subDir.$upload['name'].'\')"';
if ($type == 'images') {
if ($upload['type'] == i18n_r('IMAGES') .' Images') {
# get internal thumbnail to show beside link in table
$thumb = '<td class="imgthumb" style="display:table-cell" >';
$thumbLink = $urlPath.'thumbsm.'.$upload['name'];
if (file_exists('../data/thumbs/'.$thumbLink)) {
$imgSrc='<img src="../data/thumbs/'. $thumbLink .'" />';
} else {
$imgSrc='<img src="inc/thumb.php?src='. $urlPath . $upload['name'] .'&dest='. $thumbLink .'&x=65&f=1" />';
}
$thumb .= '<a '.$selectLink.' >'.$imgSrc.'</a>';
$thumb .= '</td>';
# get external thumbnail link
$thumbLinkExternal = 'data/thumbs/'.$urlPath.'thumbnail.'.$upload['name'];
if (file_exists('../'.$thumbLinkExternal)) {
$thumbnailLink = '<span> – </span><a href="javascript:void(0)" onclick="submitLink('.$CKEditorFuncNum.',\''.$sitepath.$thumbLinkExternal.'\')">'.i18n_r('THUMBNAIL').'</a>';
}
}
else { continue; }
}
$counter++;
echo '<tr class="All '.$upload['type'].'" >';
echo ($thumb=='' ? '<td style="display: none"></td>' : $thumb);
echo '<td><a '.$selectLink.' class="primarylink">'.htmlspecialchars($upload['name']) .'</a>'.$thumbnailLink.'</td>';
echo '<td style="width:80px;text-align:right;" ><span>'. $upload['size'] .'</span></td>';
// get the file permissions.
if ($isUnixHost && isDebug() && function_exists('posix_getpwuid')) {
$filePerms = substr(sprintf('%o', fileperms($path.$upload['name'])), -4);
$fileOwner = posix_getpwuid(fileowner($path.$upload['name']));
echo '<td style="width:70px;text-align:right;"><span>'.$fileOwner['name'].'/'.$filePerms.'</span></td>';
}
echo '<td style="width:85px;text-align:right;" ><span>'. shtDate($upload['date']) .'</span></td>';
echo '</tr>';
}
}
echo '</table>';
echo '<p><em><b>'. $counter .'</b> '.i18n_r('TOTAL_FILES').' ('. fSize($totalsize) .')</em></p>';
?>
</div>
</div>
</div>
</body>
</html>
|
<?php
/**
* Basic File Browser for CKEditor
*
* Displays and selects file link to insert into CKEditor
*
* @package GetSimple
* @subpackage Files
*
* Version: 1.1 (2011-03-12)
*/
// Setup inclusions
include('inc/common.php');
login_cookie_check();
$filesSorted=null;$dirsSorted=null;
$path = (isset($_GET['path'])) ? "../data/uploads/".$_GET['path'] : "../data/uploads/";
$subPath = (isset($_GET['path'])) ? $_GET['path'] : "";
if(!path_is_safe($path,GSDATAUPLOADPATH)) die();
$returnid = isset($_GET['returnid']) ? var_out($_GET['returnid']) : "";
$func = (isset($_GET['func'])) ? var_out($_GET['func']) : "";
$path = tsl($path);
// check if host uses Linux (used for displaying permissions
$isUnixHost = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? false : true);
$CKEditorFuncNum = isset($_GET['CKEditorFuncNum']) ? var_out($_GET['CKEditorFuncNum']) : '';
$sitepath = suggest_site_path();
$fullPath = $sitepath . "data/uploads/";
$type = isset($_GET['type']) ? var_out($_GET['type']) : '';
global $LANG;
$LANG_header = preg_replace('/(?:(?<=([a-z]{2}))).*/', '', $LANG);
?>
<!DOCTYPE html>
<html lang="<?php echo $LANG_header; ?>">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title><?php echo i18n_r('FILE_BROWSER'); ?></title>
<link rel="shortcut icon" href="favicon.png" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="template/style.php?v=<?php echo GSVERSION; ?>" media="screen" />
<style>
.wrapper, #maincontent, #imageTable { width: 100% }
</style>
<script type='text/javascript'>
function submitLink($funcNum, $url) {
<?php if (isset($_GET['returnid'])){ ?>
if(window.opener){
window.opener.document.getElementById('<?php echo $returnid; ?>').focus();
window.opener.document.getElementById('<?php echo $returnid; ?>').value=$url;
}
<?php
if (isset($_GET['func'])){
?>
if(window.opener){
if(typeof window.opener.<?php echo $func; ?> == 'function') {
window.opener.<?php echo $func; ?>('<?php echo $returnid; ?>');
}
}
<?php
}
}
else { ?>
if(window.opener){
window.opener.CKEDITOR.tools.callFunction($funcNum, $url);
}
<?php } ?>
window.close();
}
</script>
</head>
<body id="filebrowser" >
<div class="wrapper">
<div id="maincontent">
<div class="main" style="border:none;">
<h3><?php echo i18n('UPLOADED_FILES'); ?><span id="filetypetoggle"> / <?php echo ($type == 'images' ? i18n('IMAGES') : i18n('SHOW_ALL') ); ?></span></h3>
<?php
$count="0";
$dircount="0";
$counter = "0";
$totalsize = 0;
$filesArray = array();
$dirsArray = array();
$filenames = getFiles($path);
if (count($filenames) != 0) {
foreach ($filenames as $file) {
if ($file == "." || $file == ".." || $file == ".htaccess" ){
// not a upload file
} elseif (is_dir($path . $file)) {
$dirsArray[$dircount]['name'] = $file;
$dircount++;
} else {
$filesArray[$count]['name'] = $file;
$ext = substr($file, strrpos($file, '.') + 1);
$extention = get_FileType($ext);
$filesArray[$count]['type'] = $extention;
clearstatcache();
$ss = @stat($path . $file);
$filesArray[$count]['date'] = @date('M j, Y',$ss['mtime']);
$filesArray[$count]['size'] = fSize($ss['size']);
$totalsize = $totalsize + $ss['size'];
$count++;
}
}
$filesSorted = subval_sort($filesArray,'name');
$dirsSorted = subval_sort($dirsArray,'name');
}
$pathParts=explode("/",$subPath);
$urlPath="";
echo '<div class="h5">/ <a href="?CKEditorFuncNum='.$CKEditorFuncNum.'&type='.$type.'">uploads</a> / ';
foreach ($pathParts as $pathPart){
if ($pathPart!=''){
$urlPath.=$pathPart."/";
echo '<a href="?path='.$urlPath.'&CKEditorFuncNum='.$CKEditorFuncNum.'&type='.$type.'&func='.$func.'">'.$pathPart.'</a> / ';
}
}
echo "</div>";
echo '<table class="highlight" id="imageTable">';
if (count($dirsSorted) != 0) {
foreach ($dirsSorted as $upload) {
echo '<tr class="All" >';
echo '<td class="" colspan="5">';
$adm = substr($path . $upload['name'] , 16);
if ($returnid!='') {
$returnlink = '&returnid='.$returnid;
} else {
$returnlink='';
}
if ($func!='') {
$funct = '&func='.$func;
} else {
$funct='';
}
echo '<img src="template/images/folder.png" width="11" /> <a href="filebrowser.php?path='.$adm.'&CKEditorFuncNum='.$CKEditorFuncNum.'&type='.$type.$returnlink.'&'.$funct.'" title="'. $upload['name'] .'" ><strong>'.$upload['name'].'</strong></a>';
echo '</td>';
echo '</tr>';
}
}
if (count($filesSorted) != 0) {
foreach ($filesSorted as $upload) {
$upload['name'] = rawurlencode($upload['name']);
$thumb = null; $thumbnailLink = null;
$subDir = ($subPath == '' ? '' : $subPath.'/');
$selectLink = 'title="'.i18n_r('SELECT_FILE').': '. htmlspecialchars($upload['name']) .'" href="javascript:void(0)" onclick="submitLink('.$CKEditorFuncNum.',\''.$fullPath.$subDir.$upload['name'].'\')"';
if ($type == 'images') {
if ($upload['type'] == i18n_r('IMAGES') .' Images') {
# get internal thumbnail to show beside link in table
$thumb = '<td class="imgthumb" style="display:table-cell" >';
$thumbLink = $urlPath.'thumbsm.'.$upload['name'];
if (file_exists('../data/thumbs/'.$thumbLink)) {
$imgSrc='<img src="../data/thumbs/'. $thumbLink .'" />';
} else {
$imgSrc='<img src="inc/thumb.php?src='. $urlPath . $upload['name'] .'&dest='. $thumbLink .'&x=65&f=1" />';
}
$thumb .= '<a '.$selectLink.' >'.$imgSrc.'</a>';
$thumb .= '</td>';
# get external thumbnail link
$thumbLinkExternal = 'data/thumbs/'.$urlPath.'thumbnail.'.$upload['name'];
if (file_exists('../'.$thumbLinkExternal)) {
$thumbnailLink = '<span> – </span><a href="javascript:void(0)" onclick="submitLink('.$CKEditorFuncNum.',\''.$sitepath.$thumbLinkExternal.'\')">'.i18n_r('THUMBNAIL').'</a>';
}
}
else { continue; }
}
$counter++;
echo '<tr class="All '.$upload['type'].'" >';
echo ($thumb=='' ? '<td style="display: none"></td>' : $thumb);
echo '<td><a '.$selectLink.' class="primarylink">'.htmlspecialchars($upload['name']) .'</a>'.$thumbnailLink.'</td>';
echo '<td style="width:80px;text-align:right;" ><span>'. $upload['size'] .'</span></td>';
// get the file permissions.
if ($isUnixHost && isDebug() && function_exists('posix_getpwuid')) {
$filePerms = substr(sprintf('%o', fileperms($path.$upload['name'])), -4);
$fileOwner = posix_getpwuid(fileowner($path.$upload['name']));
echo '<td style="width:70px;text-align:right;"><span>'.$fileOwner['name'].'/'.$filePerms.'</span></td>';
}
echo '<td style="width:85px;text-align:right;" ><span>'. shtDate($upload['date']) .'</span></td>';
echo '</tr>';
}
}
echo '</table>';
echo '<p><em><b>'. $counter .'</b> '.i18n_r('TOTAL_FILES').' ('. fSize($totalsize) .')</em></p>';
?>
</div>
</div>
</div>
</body>
</html>
|
cb1845743bd11ba74a49b6b522c080df86a17d51
|
https://github.com/getsimplecms/getsimplecms
|
new_framework_defaults_7_0.rb
|
ruby
|
# Be sure to restart your server when you modify this file.
#
# This file eases your Rails 7.0 framework defaults upgrade.
#
# Uncomment each configuration one by one to switch to the new default.
# Once your application is ready to run with all new defaults, you can remove
# this file and set the `config.load_defaults` to `7.0`.
#
# Read the Guide for Upgrading Ruby on Rails for more info on each option.
# https://guides.rubyonrails.org/upgrading_ruby_on_rails.html
# `button_to` view helper will render `<button>` element, regardless of whether
# or not the content is passed as the first argument or as a block.
# Rails.application.config.action_view.button_to_generates_button_tag = true
# `stylesheet_link_tag` view helper will not render the media attribute by default.
# Rails.application.config.action_view.apply_stylesheet_media_default = false
# Change the digest class for the key generators to `OpenSSL::Digest::SHA256`.
# Changing this default means invalidate all encrypted messages generated by
# your application and, all the encrypted cookies. Only change this after you
# rotated all the messages using the key rotator.
#
# See upgrading guide for more information on how to build a rotator.
# https://guides.rubyonrails.org/v7.0/upgrading_ruby_on_rails.html
# Rails.application.config.active_support.key_generator_hash_digest_class = OpenSSL::Digest::SHA256
# Change the digest class for ActiveSupport::Digest.
# Changing this default means that for example Etags change and
# various cache keys leading to cache invalidation.
# Rails.application.config.active_support.hash_digest_class = OpenSSL::Digest::SHA256
# Don't override ActiveSupport::TimeWithZone.name and use the default Ruby
# implementation.
# Rails.application.config.active_support.remove_deprecated_time_with_zone_name = true
# Change the format of the cache entry.
# Changing this default means that all new cache entries added to the cache
# will have a different format that is not supported by Rails 6.1 applications.
# Only change this value after your application is fully deployed to Rails 7.0
# and you have no plans to rollback.
# Rails.application.config.active_support.cache_format_version = 7.0
# Calls `Rails.application.executor.wrap` around test cases.
# This makes test cases behave closer to an actual request or job.
# Several features that are normally disabled in test, such as Active Record query cache
# and asynchronous queries will then be enabled.
# Rails.application.config.active_support.executor_around_test_case = true
# Define the isolation level of most of Rails internal state.
# If you use a fiber based server or job processor, you should set it to `:fiber`.
# Otherwise the default of `:thread` if preferable.
# Rails.application.config.active_support.isolation_level = :thread
# Set both the `:open_timeout` and `:read_timeout` values for `:smtp` delivery method.
# Rails.application.config.action_mailer.smtp_timeout = 5
# The ActiveStorage video previewer will now use scene change detection to generate
# better preview images (rather than the previous default of using the first frame
# of the video).
# Rails.application.config.active_storage.video_preview_arguments =
# "-vf 'select=eq(n\\,0)+eq(key\\,1)+gt(scene\\,0.015),loop=loop=-1:size=2,trim=start_frame=1' -frames:v 1 -f image2"
# Automatically infer `inverse_of` for associations with a scope.
# Rails.application.config.active_record.automatic_scope_inversing = true
# Raise when running tests if fixtures contained foreign key violations
# Rails.application.config.active_record.verify_foreign_keys_for_fixtures = true
# Disable partial inserts.
# This default means that all columns will be referenced in INSERT queries
# regardless of whether they have a default or not.
# Rails.application.config.active_record.partial_inserts = false
#
# Protect from open redirect attacks in `redirect_back_or_to` and `redirect_to`.
# Rails.application.config.action_controller.raise_on_open_redirects = true
# Change the variant processor for Active Storage.
# Changing this default means updating all places in your code that
# generate variants to use image processing macros and ruby-vips
# operations. See the upgrading guide for detail on the changes required.
# The `:mini_magick` option is not deprecated; it's fine to keep using it.
# Rails.application.config.active_storage.variant_processor = :vips
# If you're upgrading and haven't set `cookies_serializer` previously, your cookie serializer
# was `:marshal`. Convert all cookies to JSON, using the `:hybrid` formatter.
#
# If you're confident all your cookies are JSON formatted, you can switch to the `:json` formatter.
#
# Continue to use `:marshal` for backward-compatibility with old cookies.
#
# If you have configured the serializer elsewhere, you can remove this.
#
# See https://guides.rubyonrails.org/action_controller_overview.html#cookies for more information.
Rails.application.config.action_dispatch.cookies_serializer = :hybrid
# Enable parameter wrapping for JSON.
# Previously this was set in an initializer. It's fine to keep using that initializer if you've customized it.
# To disable parameter wrapping entirely, set this config to `false`.
# Rails.application.config.action_controller.wrap_parameters_by_default = true
# Specifies whether generated namespaced UUIDs follow the RFC 4122 standard for namespace IDs provided as a
# `String` to `Digest::UUID.uuid_v3` or `Digest::UUID.uuid_v5` method calls.
#
# See https://guides.rubyonrails.org/configuring.html#config-active-support-use-rfc4122-namespaced-uuids for
# more information.
# Rails.application.config.active_support.use_rfc4122_namespaced_uuids = true
# Change the default headers to disable browsers' flawed legacy XSS protection.
# Rails.application.config.action_dispatch.default_headers = {
# "X-Frame-Options" => "SAMEORIGIN",
# "X-XSS-Protection" => "0",
# "X-Content-Type-Options" => "nosniff",
# "X-Download-Options" => "noopen",
# "X-Permitted-Cross-Domain-Policies" => "none",
# "Referrer-Policy" => "strict-origin-when-cross-origin"
# }
|
# Be sure to restart your server when you modify this file.
#
# This file eases your Rails 7.0 framework defaults upgrade.
#
# Uncomment each configuration one by one to switch to the new default.
# Once your application is ready to run with all new defaults, you can remove
# this file and set the `config.load_defaults` to `7.0`.
#
# Read the Guide for Upgrading Ruby on Rails for more info on each option.
# https://guides.rubyonrails.org/upgrading_ruby_on_rails.html
# `button_to` view helper will render `<button>` element, regardless of whether
# or not the content is passed as the first argument or as a block.
# Rails.application.config.action_view.button_to_generates_button_tag = true
# `stylesheet_link_tag` view helper will not render the media attribute by default.
# Rails.application.config.action_view.apply_stylesheet_media_default = false
# Change the digest class for the key generators to `OpenSSL::Digest::SHA256`.
# Changing this default means invalidate all encrypted messages generated by
# your application and, all the encrypted cookies. Only change this after you
# rotated all the messages using the key rotator.
#
# See upgrading guide for more information on how to build a rotator.
# https://guides.rubyonrails.org/v7.0/upgrading_ruby_on_rails.html
# Rails.application.config.active_support.key_generator_hash_digest_class = OpenSSL::Digest::SHA256
# Change the digest class for ActiveSupport::Digest.
# Changing this default means that for example Etags change and
# various cache keys leading to cache invalidation.
# Rails.application.config.active_support.hash_digest_class = OpenSSL::Digest::SHA256
# Don't override ActiveSupport::TimeWithZone.name and use the default Ruby
# implementation.
# Rails.application.config.active_support.remove_deprecated_time_with_zone_name = true
# Change the format of the cache entry.
# Changing this default means that all new cache entries added to the cache
# will have a different format that is not supported by Rails 6.1 applications.
# Only change this value after your application is fully deployed to Rails 7.0
# and you have no plans to rollback.
# Rails.application.config.active_support.cache_format_version = 7.0
# Calls `Rails.application.executor.wrap` around test cases.
# This makes test cases behave closer to an actual request or job.
# Several features that are normally disabled in test, such as Active Record query cache
# and asynchronous queries will then be enabled.
# Rails.application.config.active_support.executor_around_test_case = true
# Define the isolation level of most of Rails internal state.
# If you use a fiber based server or job processor, you should set it to `:fiber`.
# Otherwise the default of `:thread` if preferable.
# Rails.application.config.active_support.isolation_level = :thread
# Set both the `:open_timeout` and `:read_timeout` values for `:smtp` delivery method.
# Rails.application.config.action_mailer.smtp_timeout = 5
# The ActiveStorage video previewer will now use scene change detection to generate
# better preview images (rather than the previous default of using the first frame
# of the video).
# Rails.application.config.active_storage.video_preview_arguments =
# "-vf 'select=eq(n\\,0)+eq(key\\,1)+gt(scene\\,0.015),loop=loop=-1:size=2,trim=start_frame=1' -frames:v 1 -f image2"
# Automatically infer `inverse_of` for associations with a scope.
# Rails.application.config.active_record.automatic_scope_inversing = true
# Raise when running tests if fixtures contained foreign key violations
# Rails.application.config.active_record.verify_foreign_keys_for_fixtures = true
# Disable partial inserts.
# This default means that all columns will be referenced in INSERT queries
# regardless of whether they have a default or not.
# Rails.application.config.active_record.partial_inserts = false
#
# Protect from open redirect attacks in `redirect_back_or_to` and `redirect_to`.
# Rails.application.config.action_controller.raise_on_open_redirects = true
# Change the variant processor for Active Storage.
# Changing this default means updating all places in your code that
# generate variants to use image processing macros and ruby-vips
# operations. See the upgrading guide for detail on the changes required.
# The `:mini_magick` option is not deprecated; it's fine to keep using it.
# Rails.application.config.active_storage.variant_processor = :vips
# If you're upgrading and haven't set `cookies_serializer` previously, your cookie serializer
# was `:marshal`. Convert all cookies to JSON, using the `:hybrid` formatter.
#
# If you're confident all your cookies are JSON formatted, you can switch to the `:json` formatter.
#
# Continue to use `:marshal` for backward-compatibility with old cookies.
#
# If you have configured the serializer elsewhere, you can remove this.
#
# See https://guides.rubyonrails.org/action_controller_overview.html#cookies for more information.
Rails.application.config.action_dispatch.cookies_serializer = :json
# Enable parameter wrapping for JSON.
# Previously this was set in an initializer. It's fine to keep using that initializer if you've customized it.
# To disable parameter wrapping entirely, set this config to `false`.
# Rails.application.config.action_controller.wrap_parameters_by_default = true
# Specifies whether generated namespaced UUIDs follow the RFC 4122 standard for namespace IDs provided as a
# `String` to `Digest::UUID.uuid_v3` or `Digest::UUID.uuid_v5` method calls.
#
# See https://guides.rubyonrails.org/configuring.html#config-active-support-use-rfc4122-namespaced-uuids for
# more information.
# Rails.application.config.active_support.use_rfc4122_namespaced_uuids = true
# Change the default headers to disable browsers' flawed legacy XSS protection.
# Rails.application.config.action_dispatch.default_headers = {
# "X-Frame-Options" => "SAMEORIGIN",
# "X-XSS-Protection" => "0",
# "X-Content-Type-Options" => "nosniff",
# "X-Download-Options" => "noopen",
# "X-Permitted-Cross-Domain-Policies" => "none",
# "Referrer-Policy" => "strict-origin-when-cross-origin"
# }
|
b067372f3ee26fe1b657121f0f41883ff4461a06
|
https://github.com/abhilash1985/predictapp
|
view_filters_page.php
|
php
|
<?php
# MantisBT - A PHP based bugtracking system
# MantisBT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# MantisBT 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 MantisBT. If not, see <http://www.gnu.org/licenses/>.
/**
* View Filters Page
*
* @package MantisBT
* @copyright Copyright 2000 - 2002 Kenzaburo Ito - kenito@300baud.org
* @copyright Copyright 2002 MantisBT Team - mantisbt-dev@lists.sourceforge.net
* @link http://www.mantisbt.org
*
* @uses core.php
* @uses access_api.php
* @uses authentication_api.php
* @uses compress_api.php
* @uses config_api.php
* @uses constant_inc.php
* @uses current_user_api.php
* @uses custom_field_api.php
* @uses filter_api.php
* @uses filter_constants_inc.php
* @uses gpc_api.php
* @uses helper_api.php
* @uses html_api.php
* @uses lang_api.php
* @uses print_api.php
* @uses string_api.php
* @uses version_api.php
*/
require_once( 'core.php' );
require_api( 'access_api.php' );
require_api( 'authentication_api.php' );
require_api( 'compress_api.php' );
require_api( 'config_api.php' );
require_api( 'constant_inc.php' );
require_api( 'current_user_api.php' );
require_api( 'custom_field_api.php' );
require_api( 'filter_api.php' );
require_api( 'filter_constants_inc.php' );
require_api( 'gpc_api.php' );
require_api( 'helper_api.php' );
require_api( 'html_api.php' );
require_api( 'lang_api.php' );
require_api( 'print_api.php' );
require_api( 'string_api.php' );
require_api( 'version_api.php' );
auth_ensure_user_authenticated();
compress_enable();
layout_page_header();
layout_page_begin();
$f_filter_id = gpc_get( 'filter_id', null );
if( null === $f_filter_id ) {
$t_filter = current_user_get_bug_filter();
$t_named_filter = false;
} else {
$c_filter_id = (int)$f_filter_id;
$t_filter_string = filter_db_get_filter( $c_filter_id );
if( !$t_filter_string ) {
access_denied();
} else {
$t_filter = filter_deserialize( $t_filter_string );
$t_named_filter = true;
filter_cache_row( $c_filter_id );
}
}
$f_for_screen = gpc_get_bool( 'for_screen', true );
$t_action = 'view_all_set.php?f=3';
if( $f_for_screen == false ) {
$t_action = 'view_all_set.php';
}
$f_static = gpc_get_bool( 'static', false );
$f_view_type = gpc_get_string( 'view_type', $t_filter['_view_type'] );
$t_filter['_view_type'] = $f_view_type;
$t_filter = filter_ensure_valid_filter( $t_filter );
?>
<div class="space-10"></div>
<div class="col-md-12 col-xs-12">
<form method="post" name="filters" id="filters_form_open" class="form-control" action="<?php echo $t_action; ?>">
<?php # CSRF protection not required here - form does not result in modifications ?>
<input type="hidden" name="type" value="1" />
<input type="hidden" name="view_type" value="<?php echo $f_view_type; ?>" />
<?php
if( $f_for_screen == false ) {
print '<input type="hidden" name="print" value="1" />';
print '<input type="hidden" name="offset" value="0" />';
}
?>
<div class="widget-box widget-color-blue2">
<div class="widget-header widget-header-small">
<h4 class="widget-title lighter">
<i class="ace-icon fa fa-filter"></i>
<?php echo lang_get('filters') ?>
</h4>
<div class="widget-toolbar">
<div class="widget-menu">
<a href="#" data-action="settings" data-toggle="dropdown">
<i class="ace-icon fa fa-bars bigger-125"></i>
</a>
<ul class="dropdown-menu dropdown-menu-right dropdown-yellow dropdown-caret dropdown-closer">
<?php
$t_url = 'view_filters_page.php?static=' . (int)$f_static;
if( $t_named_filter ) {
$t_url .= '&filter_id=' . $f_filter_id;
}
$t_url .= '&view_type=';
filter_print_view_type_toggle( $t_url, $t_filter['_view_type'] );
?>
</ul>
</div>
</div>
</div>
<div class="widget-body">
<div class="widget-main no-padding">
<div class="table-responsive">
<?php
filter_form_draw_inputs( $t_filter, $f_for_screen, $f_static );
?>
</div>
<div class="widget-toolbox padding-8 clearfix">
<div class="btn-toolbar pull-left">
<div class="form-inline">
<label><?php echo lang_get( 'search' ) ?>
<input type="text" id="filter-search-txt" class="input-sm" size="16"
name="<?php echo FILTER_PROPERTY_SEARCH ?>"
value="<?php echo string_attribute( $t_filter[FILTER_PROPERTY_SEARCH] ) ?>">
</label>
</div>
</div>
<div class="btn-toolbar pull-right">
<div class="form-inline">
<input type="submit" class="btn btn-primary btn-sm btn-white btn-round no-float" name="filter" value="<?php echo lang_get( 'use_query' )?>" />
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<?php
layout_page_end();
|
<?php
# MantisBT - A PHP based bugtracking system
# MantisBT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# MantisBT 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 MantisBT. If not, see <http://www.gnu.org/licenses/>.
/**
* View Filters Page
*
* @package MantisBT
* @copyright Copyright 2000 - 2002 Kenzaburo Ito - kenito@300baud.org
* @copyright Copyright 2002 MantisBT Team - mantisbt-dev@lists.sourceforge.net
* @link http://www.mantisbt.org
*
* @uses core.php
* @uses access_api.php
* @uses authentication_api.php
* @uses compress_api.php
* @uses config_api.php
* @uses constant_inc.php
* @uses current_user_api.php
* @uses custom_field_api.php
* @uses filter_api.php
* @uses filter_constants_inc.php
* @uses gpc_api.php
* @uses helper_api.php
* @uses html_api.php
* @uses lang_api.php
* @uses print_api.php
* @uses string_api.php
* @uses version_api.php
*/
require_once( 'core.php' );
require_api( 'access_api.php' );
require_api( 'authentication_api.php' );
require_api( 'compress_api.php' );
require_api( 'config_api.php' );
require_api( 'constant_inc.php' );
require_api( 'current_user_api.php' );
require_api( 'custom_field_api.php' );
require_api( 'filter_api.php' );
require_api( 'filter_constants_inc.php' );
require_api( 'gpc_api.php' );
require_api( 'helper_api.php' );
require_api( 'html_api.php' );
require_api( 'lang_api.php' );
require_api( 'print_api.php' );
require_api( 'string_api.php' );
require_api( 'version_api.php' );
auth_ensure_user_authenticated();
compress_enable();
layout_page_header();
layout_page_begin();
$f_filter_id = gpc_get( 'filter_id', null );
if( null === $f_filter_id ) {
$t_filter = current_user_get_bug_filter();
$t_named_filter = false;
} else {
$c_filter_id = (int)$f_filter_id;
$t_filter_string = filter_db_get_filter( $c_filter_id );
if( !$t_filter_string ) {
access_denied();
} else {
$t_filter = filter_deserialize( $t_filter_string );
$t_named_filter = true;
filter_cache_row( $c_filter_id );
}
}
$f_for_screen = gpc_get_bool( 'for_screen', true );
$t_action = 'view_all_set.php?f=3';
if( $f_for_screen == false ) {
$t_action = 'view_all_set.php';
}
$f_static = gpc_get_bool( 'static', false );
$f_view_type = gpc_get_string( 'view_type', $t_filter['_view_type'] );
$t_filter['_view_type'] = $f_view_type;
$t_filter = filter_ensure_valid_filter( $t_filter );
?>
<div class="space-10"></div>
<div class="col-md-12 col-xs-12">
<form method="post" name="filters" id="filters_form_open" class="form-control" action="<?php echo $t_action; ?>">
<?php # CSRF protection not required here - form does not result in modifications ?>
<input type="hidden" name="type" value="1" />
<input type="hidden" name="view_type" value="<?php echo $t_filter['_view_type']; ?>" />
<?php
if( $f_for_screen == false ) {
print '<input type="hidden" name="print" value="1" />';
print '<input type="hidden" name="offset" value="0" />';
}
?>
<div class="widget-box widget-color-blue2">
<div class="widget-header widget-header-small">
<h4 class="widget-title lighter">
<i class="ace-icon fa fa-filter"></i>
<?php echo lang_get('filters') ?>
</h4>
<div class="widget-toolbar">
<div class="widget-menu">
<a href="#" data-action="settings" data-toggle="dropdown">
<i class="ace-icon fa fa-bars bigger-125"></i>
</a>
<ul class="dropdown-menu dropdown-menu-right dropdown-yellow dropdown-caret dropdown-closer">
<?php
$t_url = 'view_filters_page.php?static=' . (int)$f_static;
if( $t_named_filter ) {
$t_url .= '&filter_id=' . $f_filter_id;
}
$t_url .= '&view_type=';
filter_print_view_type_toggle( $t_url, $t_filter['_view_type'] );
?>
</ul>
</div>
</div>
</div>
<div class="widget-body">
<div class="widget-main no-padding">
<div class="table-responsive">
<?php
filter_form_draw_inputs( $t_filter, $f_for_screen, $f_static );
?>
</div>
<div class="widget-toolbox padding-8 clearfix">
<div class="btn-toolbar pull-left">
<div class="form-inline">
<label><?php echo lang_get( 'search' ) ?>
<input type="text" id="filter-search-txt" class="input-sm" size="16"
name="<?php echo FILTER_PROPERTY_SEARCH ?>"
value="<?php echo string_attribute( $t_filter[FILTER_PROPERTY_SEARCH] ) ?>">
</label>
</div>
</div>
<div class="btn-toolbar pull-right">
<div class="form-inline">
<input type="submit" class="btn btn-primary btn-sm btn-white btn-round no-float" name="filter" value="<?php echo lang_get( 'use_query' )?>" />
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<?php
layout_page_end();
|
1677251434b6e8b2be8f1d4376a3e78f7be14d95
|
https://github.com/mantisbt/mantisbt
|
class_parser.php
|
php
|
<?php
/**
* MyBB 1.6
* Copyright 2010 MyBB Group, All Rights Reserved
*
* Website: http://mybb.com
* License: http://mybb.com/about/license
*
* $Id$
*/
/*
options = array(
allow_html
allow_smilies
allow_mycode
nl2br
filter_badwords
me_username
shorten_urls
highlight
)
*/
class postParser
{
/**
* Internal cache of MyCode.
*
* @access public
* @var mixed
*/
public $mycode_cache = 0;
/**
* Internal cache of smilies
*
* @access public
* @var mixed
*/
public $smilies_cache = 0;
/**
* Internal cache of badwords filters
*
* @access public
* @var mixed
*/
public $badwords_cache = 0;
/**
* Base URL for smilies
*
* @access public
* @var string
*/
public $base_url;
/**
* Parsed Highlights cache
*
* @access public
* @var array
*/
public $highlight_cache = array();
/**
* Options for this parsed message (Private - set by parse_message argument)
*
* @access public
* @var array
*/
public $options;
/**
* Parses a message with the specified options.
*
* @param string The message to be parsed.
* @param array Array of yes/no options - allow_html,filter_badwords,allow_mycode,allow_smilies,nl2br,me_username.
* @return string The parsed message.
*/
function parse_message($message, $options=array())
{
global $plugins, $mybb;
// Set base URL for parsing smilies
$this->base_url = $mybb->settings['bburl'];
if($this->base_url != "")
{
if(my_substr($this->base_url, my_strlen($this->base_url) -1) != "/")
{
$this->base_url = $this->base_url."/";
}
}
// Set the options
$this->options = $options;
$message = $plugins->run_hooks("parse_message_start", $message);
// Get rid of cartridge returns for they are the workings of the devil
$message = str_replace("\r", "", $message);
// Filter bad words if requested.
if($this->options['filter_badwords'])
{
$message = $this->parse_badwords($message);
}
if($this->options['allow_html'] != 1)
{
$message = $this->parse_html($message);
}
else
{
while(preg_match("#<s(cript|tyle)(.*)>(.*)</s(cript|tyle)(.*)>#is", $message))
{
$message = preg_replace("#<s(cript|tyle)(.*)>(.*)</s(cript|tyle)(.*)>#is", "<s$1$2>$3</s$4$5>", $message);
}
$find = array('<?php', '<!--', '-->', '?>', "<br />\n", "<br>\n");
$replace = array('<?php', '<!--', '-->', '?>', "\n", "\n");
$message = str_replace($find, $replace, $message);
}
// If MyCode needs to be replaced, first filter out [code] and [php] tags.
if($this->options['allow_mycode'])
{
preg_match_all("#\[(code|php)\](.*?)\[/\\1\](\r\n?|\n?)#si", $message, $code_matches, PREG_SET_ORDER);
$message = preg_replace("#\[(code|php)\](.*?)\[/\\1\](\r\n?|\n?)#si", "<mybb-code>\n", $message);
}
// Always fix bad Javascript in the message.
$message = $this->fix_javascript($message);
// Replace "me" code and slaps if we have a username
if($this->options['me_username'])
{
global $lang;
$message = preg_replace('#(>|^|\r|\n)/me ([^\r\n<]*)#i', "\\1<span style=\"color: red;\">* {$this->options['me_username']} \\2</span>", $message);
$message = preg_replace('#(>|^|\r|\n)/slap ([^\r\n<]*)#i', "\\1<span style=\"color: red;\">* {$this->options['me_username']} {$lang->slaps} \\2 {$lang->with_trout}</span>", $message);
}
// If we can, parse smilies
if($this->options['allow_smilies'])
{
$message = $this->parse_smilies($message, $this->options['allow_html']);
}
// Replace MyCode if requested.
if($this->options['allow_mycode'])
{
$message = $this->parse_mycode($message, $this->options);
}
// Parse Highlights
if(!empty($this->options['highlight']))
{
$message = $this->highlight_message($message, $this->options['highlight']);
}
// Run plugin hooks
$message = $plugins->run_hooks("parse_message", $message);
if($this->options['allow_mycode'])
{
// Now that we're done, if we split up any code tags, parse them and glue it all back together
if(count($code_matches) > 0)
{
foreach($code_matches as $text)
{
// Fix up HTML inside the code tags so it is clean
if($options['allow_html'] != 0)
{
$text[2] = $this->parse_html($text[2]);
}
if(my_strtolower($text[1]) == "code")
{
$code = $this->mycode_parse_code($text[2]);
}
elseif(my_strtolower($text[1]) == "php")
{
$code = $this->mycode_parse_php($text[2]);
}
$message = preg_replace("#\<mybb-code>\n?#", $code, $message, 1);
}
}
}
// Replace meta and base tags in our post - these are > dangerous <
if($this->options['allow_html'])
{
$message = preg_replace_callback("#<((m[^a])|(b[^diloru>])|(s[^aemptu>]))(\s*[^>]*)>#si", create_function(
'$matches',
'return htmlspecialchars_uni($matches[0]);'
), $message);
}
if(!isset($options['nl2br']) || $options['nl2br'] != 0)
{
$message = nl2br($message);
// Fix up new lines and block level elements
$message = preg_replace("#(</?(?:html|head|body|div|p|form|table|thead|tbody|tfoot|tr|td|th|ul|ol|li|div|p|blockquote|cite|hr)[^>]*>)\s*<br />#i", "$1", $message);
$message = preg_replace("#( )+(</?(?:html|head|body|div|p|form|table|thead|tbody|tfoot|tr|td|th|ul|ol|li|div|p|blockquote|cite|hr)[^>]*>)#i", "$2", $message);
}
$message = my_wordwrap($message);
$message = $plugins->run_hooks("parse_message_end", $message);
return $message;
}
/**
* Converts HTML in a message to their specific entities whilst allowing unicode characters.
*
* @param string The message to be parsed.
* @return string The formatted message.
*/
function parse_html($message)
{
$message = preg_replace("#&(?!\#[0-9]+;)#si", "&", $message); // fix & but allow unicode
$message = str_replace("<","<",$message);
$message = str_replace(">",">",$message);
return $message;
}
/**
* Generates a cache of MyCode, both standard and custom.
*
* @access private
*/
private function cache_mycode()
{
global $cache, $lang;
$this->mycode_cache = array();
$standard_mycode = $callback_mycode = array();
$standard_mycode['b']['regex'] = "#\[b\](.*?)\[/b\]#si";
$standard_mycode['b']['replacement'] = "<span style=\"font-weight: bold;\">$1</span>";
$standard_mycode['u']['regex'] = "#\[u\](.*?)\[/u\]#si";
$standard_mycode['u']['replacement'] = "<span style=\"text-decoration: underline;\">$1</span>";
$standard_mycode['i']['regex'] = "#\[i\](.*?)\[/i\]#si";
$standard_mycode['i']['replacement'] = "<span style=\"font-style: italic;\">$1</span>";
$standard_mycode['s']['regex'] = "#\[s\](.*?)\[/s\]#si";
$standard_mycode['s']['replacement'] = "<del>$1</del>";
$standard_mycode['copy']['regex'] = "#\(c\)#i";
$standard_mycode['copy']['replacement'] = "©";
$standard_mycode['tm']['regex'] = "#\(tm\)#i";
$standard_mycode['tm']['replacement'] = "™";
$standard_mycode['reg']['regex'] = "#\(r\)#i";
$standard_mycode['reg']['replacement'] = "®";
$callback_mycode['url_simple']['regex'] = "#\[url\]([a-z]+?://)([^\r\n\"<]+?)\[/url\]#si";
$callback_mycode['url_simple']['replacement'] = array($this, 'mycode_parse_url_callback1');
$callback_mycode['url_simple2']['regex'] = "#\[url\]([^\r\n\"<]+?)\[/url\]#i";
$callback_mycode['url_simple2']['replacement'] = array($this, 'mycode_parse_url_callback2');
$callback_mycode['url_complex']['regex'] = "#\[url=([a-z]+?://)([^\r\n\"<]+?)\](.+?)\[/url\]#si";
$callback_mycode['url_complex']['replacement'] = array($this, 'mycode_parse_url_callback1');
$callback_mycode['url_complex2']['regex'] = "#\[url=([^\r\n\"<&\(\)]+?)\](.+?)\[/url\]#si";
$callback_mycode['url_complex2']['replacement'] = array($this, 'mycode_parse_url_callback2');
$callback_mycode['email_simple']['regex'] = "#\[email\](.*?)\[/email\]#i";
$callback_mycode['email_simple']['replacement'] = array($this, 'mycode_parse_email_callback');
$callback_mycode['email_complex']['regex'] = "#\[email=(.*?)\](.*?)\[/email\]#i";
$callback_mycode['email_complex']['replacement'] = array($this, 'mycode_parse_email_callback');
$standard_mycode['hr']['regex'] = "#\[hr\]#si";
$standard_mycode['hr']['replacement'] = "<hr />";
$nestable_mycode['color']['regex'] = "#\[color=([a-zA-Z]*|\#?[0-9a-fA-F]{6})](.*?)\[/color\]#si";
$nestable_mycode['color']['replacement'] = "<span style=\"color: $1;\">$2</span>";
$nestable_mycode['size']['regex'] = "#\[size=(xx-small|x-small|small|medium|large|x-large|xx-large)\](.*?)\[/size\]#si";
$nestable_mycode['size']['replacement'] = "<span style=\"font-size: $1;\">$2</span>";
$callback_mycode['size_int']['regex'] = "#\[size=([0-9\+\-]+?)\](.*?)\[/size\]#si";
$callback_mycode['size_int']['replacement'] = array($this, 'mycode_handle_size_callback');
$nestable_mycode['font']['regex'] = "#\[font=([a-z ]+?)\](.+?)\[/font\]#si";
$nestable_mycode['font']['replacement'] = "<span style=\"font-family: $1;\">$2</span>";
$nestable_mycode['align']['regex'] = "#\[align=(left|center|right|justify)\](.*?)\[/align\]#si";
$nestable_mycode['align']['replacement'] = "<div style=\"text-align: $1;\">$2</div>";
$custom_mycode = $cache->read("mycode");
// If there is custom MyCode, load it.
if(is_array($custom_mycode))
{
foreach($custom_mycode as $key => $mycode)
{
$mycode['regex'] = str_replace("\x0", "", $mycode['regex']);
$custom_mycode[$key]['regex'] = "#".$mycode['regex']."#si";
}
$mycode = array_merge($standard_mycode, $custom_mycode);
}
else
{
$mycode = $standard_mycode;
}
// Assign the MyCode to the cache.
foreach($mycode as $code)
{
$this->mycode_cache['standard']['find'][] = $code['regex'];
$this->mycode_cache['standard']['replacement'][] = $code['replacement'];
}
// Assign the nestable MyCode to the cache.
foreach($nestable_mycode as $code)
{
$this->mycode_cache['nestable'][] = array('find' => $code['regex'], 'replacement' => $code['replacement']);
}
// Assign the nestable MyCode to the cache.
foreach($callback_mycode as $code)
{
$this->mycode_cache['callback'][] = array('find' => $code['regex'], 'replacement' => $code['replacement']);
}
}
/**
* Parses MyCode tags in a specific message with the specified options.
*
* @param string The message to be parsed.
* @param array Array of options in yes/no format. Options are allow_imgcode.
* @return string The parsed message.
*/
function parse_mycode($message, $options=array())
{
global $lang;
// Cache the MyCode globally if needed.
if($this->mycode_cache == 0)
{
$this->cache_mycode();
}
// Parse quotes first
$message = $this->mycode_parse_quotes($message);
$message = $this->mycode_auto_url($message);
$message = str_replace('$', '$', $message);
// Replace the rest
$message = preg_replace($this->mycode_cache['standard']['find'], $this->mycode_cache['standard']['replacement'], $message);
foreach($this->mycode_cache['callback'] as $replace)
{
$message = preg_replace_callback($replace['find'], $replace['replacement'], $message);
}
// Replace the nestable mycode's
foreach($this->mycode_cache['nestable'] as $mycode)
{
while(preg_match($mycode['find'], $message))
{
$message = preg_replace($mycode['find'], $mycode['replacement'], $message);
}
}
// Special code requiring special attention
while(preg_match("#\[list\](.*?)\[/list\]#si", $message))
{
$message = preg_replace_callback("#\s?\[list\](.*?)\[/list\](\r\n?|\n?)#si", array($this, 'mycode_parse_list_callback'), $message);
}
// Replace lists.
while(preg_match("#\[list=(a|A|i|I|1)\](.*?)\[/list\](\r\n?|\n?)#si", $message))
{
$message = preg_replace_callback("#\s?\[list=(a|A|i|I|1)\](.*?)\[/list\]#si", array($this, 'mycode_parse_list_callback_type'), $message);
}
// Convert images when allowed.
if($options['allow_imgcode'] != 0)
{
$message = preg_replace_callback("#\[img\](\r\n?|\n?)(https?://([^<>\"']+?))\[/img\]#is", array($this, 'mycode_parse_img_callback1'), $message);
$message = preg_replace_callback("#\[img=([0-9]{1,3})x([0-9]{1,3})\](\r\n?|\n?)(https?://([^<>\"']+?))\[/img\]#is", array($this, 'mycode_parse_img_callback2'), $message);
$message = preg_replace_callback("#\[img align=([a-z]+)\](\r\n?|\n?)(https?://([^<>\"']+?))\[/img\]#is", array($this, 'mycode_parse_img_callback3'), $message);
$message = preg_replace_callback("#\[img=([0-9]{1,3})x([0-9]{1,3}) align=([a-z]+)\](\r\n?|\n?)(https?://([^<>\"']+?))\[/img\]#is", array($this, 'mycode_parse_img_callback4'), $message);
}
// Convert videos when allow.
if($options['allow_videocode'] != 0)
{
$message = preg_replace_callback("#\[video=(.*?)\](.*?)\[/video\]#i", array($this, 'mycode_parse_video_callback'), $message);
}
return $message;
}
/**
* Generates a cache of smilies
*
* @access private
*/
private function cache_smilies()
{
global $cache, $mybb;
$this->smilies_cache = array();
$smilies = $cache->read("smilies");
if(is_array($smilies))
{
foreach($smilies as $sid => $smilie)
{
if(defined("IN_ARCHIVE") && substr($smilie['image'], 0, 4) != "http")
{
// We're in the archive and not using an outside image, add in our address
$smilie['image'] = $mybb->settings['bburl']."/".$smilie['image'];
}
$this->smilies_cache[$smilie['find']] = "<img src=\"{$smilie['image']}\" style=\"vertical-align: middle;\" border=\"0\" alt=\"{$smilie['name']}\" title=\"{$smilie['name']}\" />";
}
}
}
/**
* Parses smilie code in the specified message.
*
* @param string The message being parsed.
* @param string Base URL for the image tags created by smilies.
* @param string Yes/No if HTML is allowed in the post
* @return string The parsed message.
*/
function parse_smilies($message, $allow_html=0)
{
if($this->smilies_cache == 0)
{
$this->cache_smilies();
}
$message = ' ' . $message . ' ';
// First we take out any of the tags we don't want parsed between (url= etc)
preg_match_all("#\[(url(=[^\]]*)?\]|quote=([^\]]*)?\])#i", $message, $bad_matches, PREG_PATTERN_ORDER);
$message = preg_replace("#\[(url(=[^\]]*)?\]|quote=([^\]]*)?\])#si", "<mybb-bad-sm>", $message);
// Impose a hard limit of 500 smilies per message as to not overload the parser
$remaining = 500;
if(is_array($this->smilies_cache))
{
foreach($this->smilies_cache as $find => $replace)
{
$orig_message = $message;
$find = $this->parse_html($find);
$find = preg_quote($find, "#");
$replace = strip_tags($replace, "<img>");
// Fix issues for smileys starting with a ";"
$orig_find = $find;
if(substr($find, 0, 1) == ";")
{
$find = "(?<!>|<|&)".$find;
}
$message = @preg_replace("#(?<=[^\"])".$find."(?=.\W|\"|\W.|\W$)#si", $replace, $message, $remaining, $replacements);
if($message == null)
{
$message = preg_replace("#(?<=[^&;\"])".$orig_find."(?=.\W|\"|\W.|\W$)#si", $replace, $orig_message, $remaining);
}
$remaining -= $replacements;
if($remaining <= 0)
{
break; // Reached the limit
}
}
unset($orig_message, $orig_find);
}
// If we matched any tags previously, swap them back in
if(count($bad_matches[0]) > 0)
{
foreach($bad_matches[0] as $match)
{
$match = str_replace('$', '\$', $match);
$message = preg_replace("#<mybb-bad-sm>#", $match, $message, 1);
}
}
return trim($message);
}
/**
* Generates a cache of badwords filters.
*
* @access private
*/
private function cache_badwords()
{
global $cache;
$this->badwords_cache = array();
$this->badwords_cache = $cache->read("badwords");
}
/**
* Parses a list of filtered/badwords in the specified message.
*
* @param string The message to be parsed.
* @param array Array of parser options in yes/no format.
* @return string The parsed message.
*/
function parse_badwords($message, $options=array())
{
if($this->badwords_cache == 0)
{
$this->cache_badwords();
}
if(is_array($this->badwords_cache))
{
reset($this->badwords_cache);
foreach($this->badwords_cache as $bid => $badword)
{
if(!$badword['replacement'])
{
$badword['replacement'] = "*****";
}
// Take into account the position offset for our last replacement.
$index = substr_count($badword['badword'], '*')+2;
$badword['badword'] = str_replace('\*', '([a-zA-Z0-9_]{1})', preg_quote($badword['badword'], "#"));
// Ensure we run the replacement enough times but not recursively (i.e. not while(preg_match..))
$count = preg_match_all("#(^|\W)".$badword['badword']."(\W|$)#i", $message, $matches);
for($i=0; $i < $count; ++$i)
{
$message = preg_replace("#(^|\W)".$badword['badword']."(\W|$)#i", "\\1".$badword['replacement'].'\\'.$index, $message);
}
}
}
if(isset($options['strip_tags']) && $options['strip_tags'] == 1)
{
$message = strip_tags($message);
}
return $message;
}
/**
* Attempts to move any javascript references in the specified message.
*
* @param string The message to be parsed.
* @return string The parsed message.
*/
function fix_javascript($message)
{
$js_array = array(
"#(&\#(0*)106;?|&\#(0*)74;?|&\#x(0*)4a;?|&\#x(0*)6a;?|j)((&\#(0*)97;?|&\#(0*)65;?|a)(&\#(0*)118;?|&\#(0*)86;?|v)(&\#(0*)97;?|&\#(0*)65;?|a)(\s)?(&\#(0*)115;?|&\#(0*)83;?|s)(&\#(0*)99;?|&\#(0*)67;?|c)(&\#(0*)114;?|&\#(0*)82;?|r)(&\#(0*)105;?|&\#(0*)73;?|i)(&\#112;?|&\#(0*)80;?|p)(&\#(0*)116;?|&\#(0*)84;?|t)(&\#(0*)58;?|\:))#i",
"#(o)(nmouseover\s?=)#i",
"#(o)(nmouseout\s?=)#i",
"#(o)(nmousedown\s?=)#i",
"#(o)(nmousemove\s?=)#i",
"#(o)(nmouseup\s?=)#i",
"#(o)(nclick\s?=)#i",
"#(o)(ndblclick\s?=)#i",
"#(o)(nload\s?=)#i",
"#(o)(nsubmit\s?=)#i",
"#(o)(nblur\s?=)#i",
"#(o)(nchange\s?=)#i",
"#(o)(nfocus\s?=)#i",
"#(o)(nselect\s?=)#i",
"#(o)(nunload\s?=)#i",
"#(o)(nkeypress\s?=)#i",
"#(o)(nerror\s?=)#i",
"#(o)(nreset\s?=)#i",
"#(o)(nabort\s?=)#i"
);
$message = preg_replace($js_array, "$1<strong></strong>$2$4", $message);
return $message;
}
/**
* Handles fontsize.
*
* @param string The original size.
* @param string The text within a size tag.
* @return string The parsed text.
*/
function mycode_handle_size($size, $text)
{
$size = intval($size)+10;
if($size > 50)
{
$size = 50;
}
$text = "<span style=\"font-size: {$size}pt;\">".str_replace("\'", "'", $text)."</span>";
return $text;
}
/**
* Handles fontsize.
*
* @param array Matches.
* @return string The parsed text.
*/
function mycode_handle_size_callback($matches)
{
return $this->mycode_handle_size($matches[1], $matches[2]);
}
/**
* Parses quote MyCode.
*
* @param string The message to be parsed
* @param boolean Are we formatting as text?
* @return string The parsed message.
*/
function mycode_parse_quotes($message, $text_only=false)
{
global $lang, $templates, $theme, $mybb;
// Assign pattern and replace values.
$pattern = "#\[quote\](.*?)\[\/quote\](\r\n?|\n?)#si";
$pattern_callback = "#\[quote=([\"']|"|)(.*?)(?:\\1)(.*?)(?:[\"']|")?\](.*?)\[/quote\](\r\n?|\n?)#si";
if($text_only == false)
{
$replace = "<blockquote><cite>$lang->quote</cite>$1</blockquote>\n";
$replace_callback = array($this, 'mycode_parse_post_quotes_callback1');
}
else
{
$replace = "\n{$lang->quote}\n--\n$1\n--\n";
$replace_callback = array($this, 'mycode_parse_post_quotes_callback2');
}
do
{
// preg_replace has erased the message? Restore it...
$previous_message = $message;
$message = preg_replace($pattern, $replace, $message, -1, $count);
$message = preg_replace_callback($pattern_callback, $replace_callback, $message, -1, $count_callback);
if(!$message)
{
$message = $previous_message;
break;
}
} while($count || $count_callback);
if($text_only == false)
{
$find = array(
"#(\r\n*|\n*)<\/cite>(\r\n*|\n*)#",
"#(\r\n*|\n*)<\/blockquote>#"
);
$replace = array(
"</cite><br />",
"</blockquote>"
);
$message = preg_replace($find, $replace, $message);
}
return $message;
}
/**
* Parses quotes with post id and/or dateline.
*
* @param string The message to be parsed
* @param string The username to be parsed
* @param boolean Are we formatting as text?
* @return string The parsed message.
*/
function mycode_parse_post_quotes($message, $username, $text_only=false)
{
global $lang, $templates, $theme, $mybb;
$linkback = $date = "";
$message = trim($message);
$message = preg_replace("#(^<br(\s?)(\/?)>|<br(\s?)(\/?)>$)#i", "", $message);
if(!$message) return '';
$message = str_replace('\"', '"', $message);
$username = str_replace('\"', '"', $username)."'";
$delete_quote = true;
preg_match("#pid=(?:"|\"|')?([0-9]+)[\"']?(?:"|\"|')?#i", $username, $match);
if(intval($match[1]))
{
$pid = intval($match[1]);
$url = $mybb->settings['bburl']."/".get_post_link($pid)."#pid$pid";
if(defined("IN_ARCHIVE"))
{
$linkback = " <a href=\"{$url}\">[ -> ]</a>";
}
else
{
eval("\$linkback = \" ".$templates->get("postbit_gotopost", 1, 0)."\";");
}
$username = preg_replace("#(?:"|\"|')? pid=(?:"|\"|')?[0-9]+[\"']?(?:"|\"|')?#i", '', $username);
$delete_quote = false;
}
unset($match);
preg_match("#dateline=(?:"|\"|')?([0-9]+)(?:"|\"|')?#i", $username, $match);
if(intval($match[1]))
{
if($match[1] < TIME_NOW)
{
$postdate = my_date($mybb->settings['dateformat'], intval($match[1]));
$posttime = my_date($mybb->settings['timeformat'], intval($match[1]));
$date = " ({$postdate} {$posttime})";
}
$username = preg_replace("#(?:"|\"|')? dateline=(?:"|\"|')?[0-9]+(?:"|\"|')?#i", '', $username);
$delete_quote = false;
}
if($delete_quote)
{
$username = my_substr($username, 0, my_strlen($username)-1);
}
if($text_only)
{
return "\n".htmlspecialchars_uni($username)." $lang->wrote{$date}\n--\n{$message}\n--\n";
}
else
{
$span = "";
if(!$delete_quote)
{
$span = "<span>{$date}</span>";
}
return "<blockquote><cite>{$span}".htmlspecialchars_uni($username)." $lang->wrote{$linkback}</cite>{$message}</blockquote>\n";
}
}
/**
* Parses quotes with post id and/or dateline.
*
* @param array Matches.
* @return string The parsed message.
*/
function mycode_parse_post_quotes_callback1($matches)
{
return $this->mycode_parse_post_quotes($matches[4],$matches[2].$matches[3]);
}
/**
* Parses quotes with post id and/or dateline.
*
* @param array Matches.
* @return string The parsed message.
*/
function mycode_parse_post_quotes_callback2($matches)
{
return $this->mycode_parse_post_quotes($matches[4],$matches[2].$matches[3], true);
}
/**
* Parses code MyCode.
*
* @param string The message to be parsed
* @param boolean Are we formatting as text?
* @return string The parsed message.
*/
function mycode_parse_code($code, $text_only=false)
{
global $lang;
if($text_only == true)
{
return "\n{$lang->code}\n--\n{$code}\n--\n";
}
// Clean the string before parsing.
$code = preg_replace('#^(\t*)(\n|\r|\0|\x0B| )*#', '\\1', $code);
$code = rtrim($code);
$original = preg_replace('#^\t*#', '', $code);
if(empty($original))
{
return;
}
$code = str_replace('$', '$', $code);
$code = preg_replace('#\$([0-9])#', '\\\$\\1', $code);
$code = str_replace('\\', '\', $code);
$code = str_replace("\t", ' ', $code);
$code = str_replace(" ", ' ', $code);
return "<div class=\"codeblock\">\n<div class=\"title\">".$lang->code."\n</div><div class=\"body\" dir=\"ltr\"><code>".$code."</code></div></div>\n";
}
/**
* Parses code MyCode.
*
* @param array Matches.
* @return string The parsed message.
*/
function mycode_parse_code_callback($matches)
{
return $this->mycode_parse_code($matches[1], true);
}
/**
* Parses PHP code MyCode.
*
* @param string The message to be parsed
* @param boolean Whether or not it should return it as pre-wrapped in a div or not.
* @param boolean Are we formatting as text?
* @return string The parsed message.
*/
function mycode_parse_php($str, $bare_return = false, $text_only = false)
{
global $lang;
if($text_only == true)
{
return "\n{$lang->php_code}\n--\n$str\n--\n";
}
// Clean the string before parsing except tab spaces.
$str = preg_replace('#^(\t*)(\n|\r|\0|\x0B| )*#', '\\1', $str);
$str = rtrim($str);
$original = preg_replace('#^\t*#', '', $str);
if(empty($original))
{
return;
}
$str = str_replace('&', '&', $str);
$str = str_replace('<', '<', $str);
$str = str_replace('>', '>', $str);
// See if open and close tags are provided.
$added_open_tag = false;
if(!preg_match("#^\s*<\?#si", $str))
{
$added_open_tag = true;
$str = "<?php \n".$str;
}
$added_end_tag = false;
if(!preg_match("#\?>\s*$#si", $str))
{
$added_end_tag = true;
$str = $str." \n?>";
}
$code = @highlight_string($str, true);
// Do the actual replacing.
$code = preg_replace('#<code>\s*<span style="color: \#000000">\s*#i', "<code>", $code);
$code = preg_replace("#</span>\s*</code>#", "</code>", $code);
$code = preg_replace("#</span>(\r\n?|\n?)</code>#", "</span></code>", $code);
$code = str_replace("\\", '\', $code);
$code = str_replace('$', '$', $code);
$code = preg_replace("#&\#([0-9]+);#si", "&#$1;", $code);
if($added_open_tag)
{
$code = preg_replace("#<code><span style=\"color: \#([A-Z0-9]{6})\"><\?php( | )(<br />?)#", "<code><span style=\"color: #$1\">", $code);
}
if($added_end_tag)
{
$code = str_replace("?></span></code>", "</span></code>", $code);
// Wait a minute. It fails highlighting? Stupid highlighter.
$code = str_replace("?></code>", "</code>", $code);
}
$code = preg_replace("#<span style=\"color: \#([A-Z0-9]{6})\"></span>#", "", $code);
$code = str_replace("<code>", "<div dir=\"ltr\"><code>", $code);
$code = str_replace("</code>", "</code></div>", $code);
$code = preg_replace("# *$#", "", $code);
if($bare_return)
{
return $code;
}
// Send back the code all nice and pretty
return "<div class=\"codeblock phpcodeblock\"><div class=\"title\">$lang->php_code\n</div><div class=\"body\">".$code."</div></div>\n";
}
/**
* Parses PHP code MyCode.
*
* @param array Matches.
* @return string The parsed message.
*/
function mycode_parse_php_callback($matches)
{
return $this->mycode_parse_php($matches[1], false, true);
}
/**
* Parses URL MyCode.
*
* @param string The URL to link to.
* @param string The name of the link.
* @return string The built-up link.
*/
function mycode_parse_url($url, $name="")
{
if(!preg_match("#^[a-z0-9]+://#i", $url))
{
$url = "http://".$url;
}
$fullurl = $url;
$url = str_replace('&', '&', $url);
$name = str_replace('&', '&', $name);
if(!$name)
{
$name = $url;
}
$name = str_replace("\'", "'", $name);
$url = str_replace("\'", "'", $url);
$fullurl = str_replace("\'", "'", $fullurl);
if($name == $url && (!isset($this->options['shorten_urls']) || $this->options['shorten_urls'] != 0))
{
if(my_strlen($url) > 55)
{
$name = my_substr($url, 0, 40)."...".my_substr($url, -10);
}
}
$nofollow = '';
if(isset($this->options['nofollow_on']))
{
$nofollow = " rel=\"nofollow\"";
}
// Fix some entities in URLs
$entities = array('$' => '%24', '$' => '%24', '^' => '%5E', '`' => '%60', '[' => '%5B', ']' => '%5D', '{' => '%7B', '}' => '%7D', '"' => '%22', '<' => '%3C', '>' => '%3E', ' ' => '%20');
$fullurl = str_replace(array_keys($entities), array_values($entities), $fullurl);
$name = preg_replace("#&\#([0-9]+);#si", "&#$1;", $name); // Fix & but allow unicode
$link = "<a href=\"$fullurl\" target=\"_blank\"{$nofollow}>$name</a>";
return $link;
}
/**
* Parses URL MyCode.
*
* @param array Matches.
* @return string The built-up link.
*/
function mycode_parse_url_callback1($matches)
{
if(!isset($matches[3]))
{
$matches[3] = '';
}
return $this->mycode_parse_url($matches[1].$matches[2], $matches[3]);
}
/**
* Parses URL MyCode.
*
* @param array Matches.
* @return string The built-up link.
*/
function mycode_parse_url_callback2($matches)
{
if(!isset($matches[2]))
{
$matches[2] = '';
}
return $this->mycode_parse_url($matches[1], $matches[2]);
}
/**
* Parses IMG MyCode.
*
* @param string The URL to the image
* @param array Optional array of dimensions
*/
function mycode_parse_img($url, $dimensions=array(), $align='')
{
global $lang;
$url = trim($url);
$url = str_replace("\n", "", $url);
$url = str_replace("\r", "", $url);
if($align == "right")
{
$css_align = " style=\"float: right;\"";
}
else if($align == "left")
{
$css_align = " style=\"float: left;\"";
}
$alt = htmlspecialchars_uni(basename($url));
if(my_strlen($alt) > 55)
{
$alt = my_substr($alt, 0, 40)."...".my_substr($alt, -10);
}
$alt = $lang->sprintf($lang->posted_image, $alt);
if($dimensions[0] > 0 && $dimensions[1] > 0)
{
return "<img src=\"{$url}\" width=\"{$dimensions[0]}\" height=\"{$dimensions[1]}\" border=\"0\" alt=\"{$alt}\"{$css_align} />";
}
else
{
return "<img src=\"{$url}\" border=\"0\" alt=\"{$alt}\"{$css_align} />";
}
}
/**
* Parses IMG MyCode.
*
* @param array Matches.
* @return string Image code.
*/
function mycode_parse_img_callback1($matches)
{
return $this->mycode_parse_img($matches[2]);
}
/**
* Parses IMG MyCode.
*
* @param array Matches.
* @return string Image code.
*/
function mycode_parse_img_callback2($matches)
{
return $this->mycode_parse_img($matches[4], array($matches[1], $matches[2]));
}
/**
* Parses IMG MyCode.
*
* @param array Matches.
* @return string Image code.
*/
function mycode_parse_img_callback3($matches)
{
return $this->mycode_parse_img($matches[3], array(), $matches[1]);
}
/**
* Parses IMG MyCode.
*
* @param array Matches.
* @return string Image code.
*/
function mycode_parse_img_callback4($matches)
{
return $this->mycode_parse_img($matches[5], array($matches[1], $matches[2]), $matches[3]);
}
/**
* Parses email MyCode.
*
* @param string The email address to link to.
* @param string The name for the link.
* @return string The built-up email link.
*/
function mycode_parse_email($email, $name="")
{
$name = str_replace("\\'", "'", $name);
$email = str_replace("\\'", "'", $email);
if(!$name)
{
$name = $email;
}
if(preg_match("/^([a-zA-Z0-9-_\+\.]+?)@[a-zA-Z0-9-]+\.[a-zA-Z0-9\.-]+$/si", $email))
{
return "<a href=\"mailto:$email\">".$name."</a>";
}
else
{
return $email;
}
}
/**
* Parses email MyCode.
*
* @param array Matches
* @return string The built-up email link.
*/
function mycode_parse_email_callback($matches)
{
if(!isset($matches[2]))
{
$matches[2] = '';
}
return $this->mycode_parse_email($matches[1], $matches[2]);
}
/**
* Parses video MyCode.
*
* @param string The video provider.
* @param string The video to link to.
* @return string The built-up video code.
*/
function mycode_parse_video($video, $url)
{
global $templates;
if(empty($video) || empty($url))
{
return "[video={$video}]{$url}[/video]";
}
$parsed_url = @parse_url(urldecode($url));
if($parsed_url == false)
{
return "[video={$video}]{$url}[/video]";
}
$fragments = array();
if($parsed_url['fragment'])
{
$fragments = explode("&", $parsed_url['fragment']);
}
$queries = explode("&", $parsed_url['query']);
$input = array();
foreach($queries as $query)
{
list($key, $value) = explode("=", $query);
$key = str_replace("amp;", "", $key);
$input[$key] = $value;
}
$path = explode('/', $parsed_url['path']);
switch($video)
{
case "dailymotion":
list($id, ) = split("_", $path[2], 1); // http://www.dailymotion.com/video/fds123_title-goes-here
break;
case "metacafe":
$id = $path[2]; // http://www.metacafe.com/watch/fds123/title_goes_here/
$title = htmlspecialchars_uni($path[3]);
break;
case "myspacetv":
$id = $path[4]; // http://www.myspace.com/video/fds/fds/123
break;
case "yahoo":
$id = $path[1]; // http://xy.screen.yahoo.com/fds-123.html
// Support for localized portals
$domain = explode('.', $parsed_url['host']);
if($domain[0] != 'screen')
{
$local = $domain[0].'.';
}
else
{
$local = '';
}
break;
case "vimeo":
$id = $path[1]; // http://vimeo.com/fds123
break;
case "youtube":
if($fragments[0])
{
$id = str_replace('!v=', '', $fragments[0]); // http://www.youtube.com/watch#!v=fds123
}
elseif($input['v'])
{
$id = $input['v']; // http://www.youtube.com/watch?v=fds123
}
else
{
$id = $path[1]; // http://www.youtu.be/fds123
}
break;
default:
return "[video={$video}]{$url}[/video]";
}
if(empty($id))
{
return "[video={$video}]{$url}[/video]";
}
$id = htmlspecialchars_uni($id);
eval("\$video_code = \"".$templates->get("video_{$video}_embed")."\";");
return $video_code;
}
/**
* Parses video MyCode.
*
* @param array Matches.
* @return string The built-up video code.
*/
function mycode_parse_video_callback($matches)
{
return $this->mycode_parse_video($matches[1], $matches[2]);
}
/**
* Parses URLs automatically.
*
* @param string The message to be parsed
* @return string The parsed message.
*/
function mycode_auto_url($message)
{
$message = " ".$message;
$message = preg_replace("#([\>\s\(\)])(http|https|ftp|news){1}://([^\/\"\s\<\[\.]+\.([^\/\"\s\<\[\.]+\.)*[\w]+(:[0-9]+)?(/[^\"\s<\[]*)?)#i", "$1[url]$2://$3[/url]", $message);
$message = preg_replace("#([\>\s\(\)])(www|ftp)\.(([^\/\"\s\<\[\.]+\.)*[\w]+(:[0-9]+)?(/[^\"\s<\[]*)?)#i", "$1[url]$2.$3[/url]", $message);
$message = my_substr($message, 1);
return $message;
}
/**
* Parses list MyCode.
*
* @param string The message to be parsed
* @param string The list type
* @return string The parsed message.
*/
function mycode_parse_list($message, $type="")
{
$message = str_replace('\"', '"', $message);
$message = preg_replace("#\s*\[\*\]\s*#", "</li>\n<li>", $message);
$message .= "</li>";
if($type)
{
$list = "\n<ol type=\"$type\">$message</ol>\n";
}
else
{
$list = "<ul>$message</ul>\n";
}
$list = preg_replace("#<(ol type=\"$type\"|ul)>\s*</li>#", "<$1>", $list);
return $list;
}
/**
* Parses list MyCode.
*
* @param array Matches
* @return string The parsed message.
*/
function mycode_parse_list_callback($matches)
{
return $this->mycode_parse_list($matches[1]);
}
/**
* Parses list MyCode.
*
* @param array Matches
* @return string The parsed message.
*/
function mycode_parse_list_callback_type($matches)
{
return $this->mycode_parse_list($matches[2], $matches[1]);
}
/**
* Strips smilies from a string
*
* @param string The message for smilies to be stripped from
* @return string The message with smilies stripped
*/
function strip_smilies($message)
{
if($this->smilies_cache == 0)
{
$this->cache_smilies();
}
if(is_array($this->smilies_cache))
{
$message = str_replace($this->smilies_cache, array_keys($this->smilies_cache), $message);
}
return $message;
}
/**
* Highlights a string
*
* @param string The message to be highligted
* @param string The highlight keywords
* @return string The message with highlight bbcodes
*/
function highlight_message($message, $highlight)
{
if(empty($this->highlight_cache))
{
$this->highlight_cache = build_highlight_array($highlight);
}
if(is_array($this->highlight_cache) && !empty($this->highlight_cache))
{
$message = preg_replace(array_keys($this->highlight_cache), $this->highlight_cache, $message);
}
return $message;
}
/**
* Parses message to plain text equivalents of MyCode.
*
* @param string The message to be parsed
* @return string The parsed message.
*/
function text_parse_message($message, $options=array())
{
global $plugins;
// Filter bad words if requested.
if($options['filter_badwords'] != 0)
{
$message = $this->parse_badwords($message);
}
// Parse quotes first
$message = $this->mycode_parse_quotes($message, true);
$message = preg_replace_callback("#\[php\](.*?)\[/php\](\r\n?|\n?)#is", array($this, 'mycode_parse_php_callback'), $message);
$message = preg_replace_callback("#\[code\](.*?)\[/code\](\r\n?|\n?)#is", array($this, 'mycode_parse_code_callback'), $message);
$find = array(
"#\[(b|u|i|s|url|email|color|img)\](.*?)\[/\\1\]#is",
"#\[img=([0-9]{1,3})x([0-9]{1,3})\](\r\n?|\n?)(https?://([^<>\"']+?))\[/img\]#is",
"#\[url=([a-z]+?://)([^\r\n\"<]+?)\](.+?)\[/url\]#si",
"#\[url=([^\r\n\"<&\(\)]+?)\](.+?)\[/url\]#si",
);
$replace = array(
"$2",
"$4",
"$3 ($1$2)",
"$2 ($1)",
);
$message = preg_replace($find, $replace, $message);
// Replace "me" code and slaps if we have a username
if($options['me_username'])
{
global $lang;
$message = preg_replace('#(>|^|\r|\n)/me ([^\r\n<]*)#i', "\\1* {$options['me_username']} \\2", $message);
$message = preg_replace('#(>|^|\r|\n)/slap ([^\r\n<]*)#i', "\\1* {$options['me_username']} {$lang->slaps} \\2 {$lang->with_trout}", $message);
}
// Special code requiring special attention
while(preg_match("#\[list\](.*?)\[/list\]#si", $message))
{
$message = preg_replace_callback("#\s?\[list\](.*?)\[/list\](\r\n?|\n?)#si", array($this, 'mycode_parse_list_callback'), $message);
}
// Replace lists.
while(preg_match("#\[list=(a|A|i|I|1)\](.*?)\[/list\](\r\n?|\n?)#si", $message))
{
$message = preg_replace_callback("#\s?\[list=(a|A|i|I|1)\](.*?)\[/list\]#si", array($this, 'mycode_parse_list_callback_type'), $message);
}
// Run plugin hooks
$message = $plugins->run_hooks("text_parse_message", $message);
return $message;
}
}
?>
|
<?php
/**
* MyBB 1.6
* Copyright 2010 MyBB Group, All Rights Reserved
*
* Website: http://mybb.com
* License: http://mybb.com/about/license
*
* $Id$
*/
/*
options = array(
allow_html
allow_smilies
allow_mycode
nl2br
filter_badwords
me_username
shorten_urls
highlight
)
*/
class postParser
{
/**
* Internal cache of MyCode.
*
* @access public
* @var mixed
*/
public $mycode_cache = 0;
/**
* Internal cache of smilies
*
* @access public
* @var mixed
*/
public $smilies_cache = 0;
/**
* Internal cache of badwords filters
*
* @access public
* @var mixed
*/
public $badwords_cache = 0;
/**
* Base URL for smilies
*
* @access public
* @var string
*/
public $base_url;
/**
* Parsed Highlights cache
*
* @access public
* @var array
*/
public $highlight_cache = array();
/**
* Options for this parsed message (Private - set by parse_message argument)
*
* @access public
* @var array
*/
public $options;
/**
* Parses a message with the specified options.
*
* @param string The message to be parsed.
* @param array Array of yes/no options - allow_html,filter_badwords,allow_mycode,allow_smilies,nl2br,me_username.
* @return string The parsed message.
*/
function parse_message($message, $options=array())
{
global $plugins, $mybb;
// Set base URL for parsing smilies
$this->base_url = $mybb->settings['bburl'];
if($this->base_url != "")
{
if(my_substr($this->base_url, my_strlen($this->base_url) -1) != "/")
{
$this->base_url = $this->base_url."/";
}
}
// Set the options
$this->options = $options;
$message = $plugins->run_hooks("parse_message_start", $message);
// Get rid of cartridge returns for they are the workings of the devil
$message = str_replace("\r", "", $message);
// Filter bad words if requested.
if($this->options['filter_badwords'])
{
$message = $this->parse_badwords($message);
}
if($this->options['allow_html'] != 1)
{
$message = $this->parse_html($message);
}
else
{
while(preg_match("#<s(cript|tyle)(.*)>(.*)</s(cript|tyle)(.*)>#is", $message))
{
$message = preg_replace("#<s(cript|tyle)(.*)>(.*)</s(cript|tyle)(.*)>#is", "<s$1$2>$3</s$4$5>", $message);
}
$find = array('<?php', '<!--', '-->', '?>', "<br />\n", "<br>\n");
$replace = array('<?php', '<!--', '-->', '?>', "\n", "\n");
$message = str_replace($find, $replace, $message);
}
// If MyCode needs to be replaced, first filter out [code] and [php] tags.
if($this->options['allow_mycode'])
{
preg_match_all("#\[(code|php)\](.*?)\[/\\1\](\r\n?|\n?)#si", $message, $code_matches, PREG_SET_ORDER);
$message = preg_replace("#\[(code|php)\](.*?)\[/\\1\](\r\n?|\n?)#si", "<mybb-code>\n", $message);
}
// Always fix bad Javascript in the message.
$message = $this->fix_javascript($message);
// Replace "me" code and slaps if we have a username
if($this->options['me_username'])
{
global $lang;
$message = preg_replace('#(>|^|\r|\n)/me ([^\r\n<]*)#i', "\\1<span style=\"color: red;\">* {$this->options['me_username']} \\2</span>", $message);
$message = preg_replace('#(>|^|\r|\n)/slap ([^\r\n<]*)#i', "\\1<span style=\"color: red;\">* {$this->options['me_username']} {$lang->slaps} \\2 {$lang->with_trout}</span>", $message);
}
// If we can, parse smilies
if($this->options['allow_smilies'])
{
$message = $this->parse_smilies($message, $this->options['allow_html']);
}
// Replace MyCode if requested.
if($this->options['allow_mycode'])
{
$message = $this->parse_mycode($message, $this->options);
}
// Parse Highlights
if(!empty($this->options['highlight']))
{
$message = $this->highlight_message($message, $this->options['highlight']);
}
// Run plugin hooks
$message = $plugins->run_hooks("parse_message", $message);
if($this->options['allow_mycode'])
{
// Now that we're done, if we split up any code tags, parse them and glue it all back together
if(count($code_matches) > 0)
{
foreach($code_matches as $text)
{
// Fix up HTML inside the code tags so it is clean
if($options['allow_html'] != 0)
{
$text[2] = $this->parse_html($text[2]);
}
if(my_strtolower($text[1]) == "code")
{
$code = $this->mycode_parse_code($text[2]);
}
elseif(my_strtolower($text[1]) == "php")
{
$code = $this->mycode_parse_php($text[2]);
}
$message = preg_replace("#\<mybb-code>\n?#", $code, $message, 1);
}
}
}
// Replace meta and base tags in our post - these are > dangerous <
if($this->options['allow_html'])
{
$message = preg_replace_callback("#<((m[^a])|(b[^diloru>])|(s[^aemptu>]))(\s*[^>]*)>#si", create_function(
'$matches',
'return htmlspecialchars_uni($matches[0]);'
), $message);
}
if(!isset($options['nl2br']) || $options['nl2br'] != 0)
{
$message = nl2br($message);
// Fix up new lines and block level elements
$message = preg_replace("#(</?(?:html|head|body|div|p|form|table|thead|tbody|tfoot|tr|td|th|ul|ol|li|div|p|blockquote|cite|hr)[^>]*>)\s*<br />#i", "$1", $message);
$message = preg_replace("#( )+(</?(?:html|head|body|div|p|form|table|thead|tbody|tfoot|tr|td|th|ul|ol|li|div|p|blockquote|cite|hr)[^>]*>)#i", "$2", $message);
}
$message = my_wordwrap($message);
$message = $plugins->run_hooks("parse_message_end", $message);
return $message;
}
/**
* Converts HTML in a message to their specific entities whilst allowing unicode characters.
*
* @param string The message to be parsed.
* @return string The formatted message.
*/
function parse_html($message)
{
$message = preg_replace("#&(?!\#[0-9]+;)#si", "&", $message); // fix & but allow unicode
$message = str_replace("<","<",$message);
$message = str_replace(">",">",$message);
return $message;
}
/**
* Generates a cache of MyCode, both standard and custom.
*
* @access private
*/
private function cache_mycode()
{
global $cache, $lang;
$this->mycode_cache = array();
$standard_mycode = $callback_mycode = array();
$standard_mycode['b']['regex'] = "#\[b\](.*?)\[/b\]#si";
$standard_mycode['b']['replacement'] = "<span style=\"font-weight: bold;\">$1</span>";
$standard_mycode['u']['regex'] = "#\[u\](.*?)\[/u\]#si";
$standard_mycode['u']['replacement'] = "<span style=\"text-decoration: underline;\">$1</span>";
$standard_mycode['i']['regex'] = "#\[i\](.*?)\[/i\]#si";
$standard_mycode['i']['replacement'] = "<span style=\"font-style: italic;\">$1</span>";
$standard_mycode['s']['regex'] = "#\[s\](.*?)\[/s\]#si";
$standard_mycode['s']['replacement'] = "<del>$1</del>";
$standard_mycode['copy']['regex'] = "#\(c\)#i";
$standard_mycode['copy']['replacement'] = "©";
$standard_mycode['tm']['regex'] = "#\(tm\)#i";
$standard_mycode['tm']['replacement'] = "™";
$standard_mycode['reg']['regex'] = "#\(r\)#i";
$standard_mycode['reg']['replacement'] = "®";
$callback_mycode['url_simple']['regex'] = "#\[url\]([a-z]+?://)([^\r\n\"<]+?)\[/url\]#si";
$callback_mycode['url_simple']['replacement'] = array($this, 'mycode_parse_url_callback1');
$callback_mycode['url_simple2']['regex'] = "#\[url\]([^\r\n\"<]+?)\[/url\]#i";
$callback_mycode['url_simple2']['replacement'] = array($this, 'mycode_parse_url_callback2');
$callback_mycode['url_complex']['regex'] = "#\[url=([a-z]+?://)([^\r\n\"<]+?)\](.+?)\[/url\]#si";
$callback_mycode['url_complex']['replacement'] = array($this, 'mycode_parse_url_callback1');
$callback_mycode['url_complex2']['regex'] = "#\[url=([^\r\n\"<&\(\)]+?)\](.+?)\[/url\]#si";
$callback_mycode['url_complex2']['replacement'] = array($this, 'mycode_parse_url_callback2');
$callback_mycode['email_simple']['regex'] = "#\[email\](.*?)\[/email\]#i";
$callback_mycode['email_simple']['replacement'] = array($this, 'mycode_parse_email_callback');
$callback_mycode['email_complex']['regex'] = "#\[email=(.*?)\](.*?)\[/email\]#i";
$callback_mycode['email_complex']['replacement'] = array($this, 'mycode_parse_email_callback');
$standard_mycode['hr']['regex'] = "#\[hr\]#si";
$standard_mycode['hr']['replacement'] = "<hr />";
$nestable_mycode['color']['regex'] = "#\[color=([a-zA-Z]*|\#?[0-9a-fA-F]{6})](.*?)\[/color\]#si";
$nestable_mycode['color']['replacement'] = "<span style=\"color: $1;\">$2</span>";
$nestable_mycode['size']['regex'] = "#\[size=(xx-small|x-small|small|medium|large|x-large|xx-large)\](.*?)\[/size\]#si";
$nestable_mycode['size']['replacement'] = "<span style=\"font-size: $1;\">$2</span>";
$callback_mycode['size_int']['regex'] = "#\[size=([0-9\+\-]+?)\](.*?)\[/size\]#si";
$callback_mycode['size_int']['replacement'] = array($this, 'mycode_handle_size_callback');
$nestable_mycode['font']['regex'] = "#\[font=([a-z ]+?)\](.+?)\[/font\]#si";
$nestable_mycode['font']['replacement'] = "<span style=\"font-family: $1;\">$2</span>";
$nestable_mycode['align']['regex'] = "#\[align=(left|center|right|justify)\](.*?)\[/align\]#si";
$nestable_mycode['align']['replacement'] = "<div style=\"text-align: $1;\">$2</div>";
$custom_mycode = $cache->read("mycode");
// If there is custom MyCode, load it.
if(is_array($custom_mycode))
{
foreach($custom_mycode as $key => $mycode)
{
$mycode['regex'] = str_replace("\x0", "", $mycode['regex']);
$custom_mycode[$key]['regex'] = "#".$mycode['regex']."#si";
}
$mycode = array_merge($standard_mycode, $custom_mycode);
}
else
{
$mycode = $standard_mycode;
}
// Assign the MyCode to the cache.
foreach($mycode as $code)
{
$this->mycode_cache['standard']['find'][] = $code['regex'];
$this->mycode_cache['standard']['replacement'][] = $code['replacement'];
}
// Assign the nestable MyCode to the cache.
foreach($nestable_mycode as $code)
{
$this->mycode_cache['nestable'][] = array('find' => $code['regex'], 'replacement' => $code['replacement']);
}
// Assign the nestable MyCode to the cache.
foreach($callback_mycode as $code)
{
$this->mycode_cache['callback'][] = array('find' => $code['regex'], 'replacement' => $code['replacement']);
}
}
/**
* Parses MyCode tags in a specific message with the specified options.
*
* @param string The message to be parsed.
* @param array Array of options in yes/no format. Options are allow_imgcode.
* @return string The parsed message.
*/
function parse_mycode($message, $options=array())
{
global $lang;
// Cache the MyCode globally if needed.
if($this->mycode_cache == 0)
{
$this->cache_mycode();
}
// Parse quotes first
$message = $this->mycode_parse_quotes($message);
$message = $this->mycode_auto_url($message);
$message = str_replace('$', '$', $message);
// Replace the rest
$message = preg_replace($this->mycode_cache['standard']['find'], $this->mycode_cache['standard']['replacement'], $message);
foreach($this->mycode_cache['callback'] as $replace)
{
$message = preg_replace_callback($replace['find'], $replace['replacement'], $message);
}
// Replace the nestable mycode's
foreach($this->mycode_cache['nestable'] as $mycode)
{
while(preg_match($mycode['find'], $message))
{
$message = preg_replace($mycode['find'], $mycode['replacement'], $message);
}
}
// Special code requiring special attention
while(preg_match("#\[list\](.*?)\[/list\]#si", $message))
{
$message = preg_replace_callback("#\s?\[list\](.*?)\[/list\](\r\n?|\n?)#si", array($this, 'mycode_parse_list_callback'), $message);
}
// Replace lists.
while(preg_match("#\[list=(a|A|i|I|1)\](.*?)\[/list\](\r\n?|\n?)#si", $message))
{
$message = preg_replace_callback("#\s?\[list=(a|A|i|I|1)\](.*?)\[/list\]#si", array($this, 'mycode_parse_list_callback_type'), $message);
}
// Convert images when allowed.
if($options['allow_imgcode'] != 0)
{
$message = preg_replace_callback("#\[img\](\r\n?|\n?)(https?://([^<>\"']+?))\[/img\]#is", array($this, 'mycode_parse_img_callback1'), $message);
$message = preg_replace_callback("#\[img=([0-9]{1,3})x([0-9]{1,3})\](\r\n?|\n?)(https?://([^<>\"']+?))\[/img\]#is", array($this, 'mycode_parse_img_callback2'), $message);
$message = preg_replace_callback("#\[img align=([a-z]+)\](\r\n?|\n?)(https?://([^<>\"']+?))\[/img\]#is", array($this, 'mycode_parse_img_callback3'), $message);
$message = preg_replace_callback("#\[img=([0-9]{1,3})x([0-9]{1,3}) align=([a-z]+)\](\r\n?|\n?)(https?://([^<>\"']+?))\[/img\]#is", array($this, 'mycode_parse_img_callback4'), $message);
}
// Convert videos when allow.
if($options['allow_videocode'] != 0)
{
$message = preg_replace_callback("#\[video=(.*?)\](.*?)\[/video\]#i", array($this, 'mycode_parse_video_callback'), $message);
}
return $message;
}
/**
* Generates a cache of smilies
*
* @access private
*/
private function cache_smilies()
{
global $cache, $mybb;
$this->smilies_cache = array();
$smilies = $cache->read("smilies");
if(is_array($smilies))
{
foreach($smilies as $sid => $smilie)
{
if(defined("IN_ARCHIVE") && substr($smilie['image'], 0, 4) != "http")
{
// We're in the archive and not using an outside image, add in our address
$smilie['image'] = $mybb->settings['bburl']."/".$smilie['image'];
}
$this->smilies_cache[$smilie['find']] = "<img src=\"{$smilie['image']}\" style=\"vertical-align: middle;\" border=\"0\" alt=\"{$smilie['name']}\" title=\"{$smilie['name']}\" />";
}
}
}
/**
* Parses smilie code in the specified message.
*
* @param string The message being parsed.
* @param string Base URL for the image tags created by smilies.
* @param string Yes/No if HTML is allowed in the post
* @return string The parsed message.
*/
function parse_smilies($message, $allow_html=0)
{
if($this->smilies_cache == 0)
{
$this->cache_smilies();
}
$message = ' ' . $message . ' ';
// First we take out any of the tags we don't want parsed between (url= etc)
preg_match_all("#\[(url(=[^\]]*)?\]|quote=([^\]]*)?\])#i", $message, $bad_matches, PREG_PATTERN_ORDER);
$message = preg_replace("#\[(url(=[^\]]*)?\]|quote=([^\]]*)?\])#si", "<mybb-bad-sm>", $message);
// Impose a hard limit of 500 smilies per message as to not overload the parser
$remaining = 500;
if(is_array($this->smilies_cache))
{
foreach($this->smilies_cache as $find => $replace)
{
$orig_message = $message;
$find = $this->parse_html($find);
$find = preg_quote($find, "#");
$replace = strip_tags($replace, "<img>");
// Fix issues for smileys starting with a ";"
$orig_find = $find;
if(substr($find, 0, 1) == ";")
{
$find = "(?<!>|<|&)".$find;
}
$message = @preg_replace("#(?<=[^\"])".$find."(?=.\W|\"|\W.|\W$)#si", $replace, $message, $remaining, $replacements);
if($message == null)
{
$message = preg_replace("#(?<=[^&;\"])".$orig_find."(?=.\W|\"|\W.|\W$)#si", $replace, $orig_message, $remaining);
}
$remaining -= $replacements;
if($remaining <= 0)
{
break; // Reached the limit
}
}
unset($orig_message, $orig_find);
}
// If we matched any tags previously, swap them back in
if(count($bad_matches[0]) > 0)
{
foreach($bad_matches[0] as $match)
{
$match = str_replace('$', '\$', $match);
$message = preg_replace("#<mybb-bad-sm>#", $match, $message, 1);
}
}
return trim($message);
}
/**
* Generates a cache of badwords filters.
*
* @access private
*/
private function cache_badwords()
{
global $cache;
$this->badwords_cache = array();
$this->badwords_cache = $cache->read("badwords");
}
/**
* Parses a list of filtered/badwords in the specified message.
*
* @param string The message to be parsed.
* @param array Array of parser options in yes/no format.
* @return string The parsed message.
*/
function parse_badwords($message, $options=array())
{
if($this->badwords_cache == 0)
{
$this->cache_badwords();
}
if(is_array($this->badwords_cache))
{
reset($this->badwords_cache);
foreach($this->badwords_cache as $bid => $badword)
{
if(!$badword['replacement'])
{
$badword['replacement'] = "*****";
}
// Take into account the position offset for our last replacement.
$index = substr_count($badword['badword'], '*')+2;
$badword['badword'] = str_replace('\*', '([a-zA-Z0-9_]{1})', preg_quote($badword['badword'], "#"));
// Ensure we run the replacement enough times but not recursively (i.e. not while(preg_match..))
$count = preg_match_all("#(^|\W)".$badword['badword']."(\W|$)#i", $message, $matches);
for($i=0; $i < $count; ++$i)
{
$message = preg_replace("#(^|\W)".$badword['badword']."(\W|$)#i", "\\1".$badword['replacement'].'\\'.$index, $message);
}
}
}
if(isset($options['strip_tags']) && $options['strip_tags'] == 1)
{
$message = strip_tags($message);
}
return $message;
}
/**
* Attempts to move any javascript references in the specified message.
*
* @param string The message to be parsed.
* @return string The parsed message.
*/
function fix_javascript($message)
{
$js_array = array(
"#(&\#(0*)106;?|&\#(0*)74;?|&\#x(0*)4a;?|&\#x(0*)6a;?|j)((&\#(0*)97;?|&\#(0*)65;?|a)(&\#(0*)118;?|&\#(0*)86;?|v)(&\#(0*)97;?|&\#(0*)65;?|a)(\s)?(&\#(0*)115;?|&\#(0*)83;?|s)(&\#(0*)99;?|&\#(0*)67;?|c)(&\#(0*)114;?|&\#(0*)82;?|r)(&\#(0*)105;?|&\#(0*)73;?|i)(&\#112;?|&\#(0*)80;?|p)(&\#(0*)116;?|&\#(0*)84;?|t)(&\#(0*)58;?|\:))#i",
"#(o)(nmouseover\s?=)#i",
"#(o)(nmouseout\s?=)#i",
"#(o)(nmousedown\s?=)#i",
"#(o)(nmousemove\s?=)#i",
"#(o)(nmouseup\s?=)#i",
"#(o)(nclick\s?=)#i",
"#(o)(ndblclick\s?=)#i",
"#(o)(nload\s?=)#i",
"#(o)(nsubmit\s?=)#i",
"#(o)(nblur\s?=)#i",
"#(o)(nchange\s?=)#i",
"#(o)(nfocus\s?=)#i",
"#(o)(nselect\s?=)#i",
"#(o)(nunload\s?=)#i",
"#(o)(nkeypress\s?=)#i",
"#(o)(nerror\s?=)#i",
"#(o)(nreset\s?=)#i",
"#(o)(nabort\s?=)#i"
);
$message = preg_replace($js_array, "$1<strong></strong>$2$4", $message);
return $message;
}
/**
* Handles fontsize.
*
* @param string The original size.
* @param string The text within a size tag.
* @return string The parsed text.
*/
function mycode_handle_size($size, $text)
{
$size = intval($size)+10;
if($size > 50)
{
$size = 50;
}
$text = "<span style=\"font-size: {$size}pt;\">".str_replace("\'", "'", $text)."</span>";
return $text;
}
/**
* Handles fontsize.
*
* @param array Matches.
* @return string The parsed text.
*/
function mycode_handle_size_callback($matches)
{
return $this->mycode_handle_size($matches[1], $matches[2]);
}
/**
* Parses quote MyCode.
*
* @param string The message to be parsed
* @param boolean Are we formatting as text?
* @return string The parsed message.
*/
function mycode_parse_quotes($message, $text_only=false)
{
global $lang, $templates, $theme, $mybb;
// Assign pattern and replace values.
$pattern = "#\[quote\](.*?)\[\/quote\](\r\n?|\n?)#si";
$pattern_callback = "#\[quote=([\"']|"|)(.*?)(?:\\1)(.*?)(?:[\"']|")?\](.*?)\[/quote\](\r\n?|\n?)#si";
if($text_only == false)
{
$replace = "<blockquote><cite>$lang->quote</cite>$1</blockquote>\n";
$replace_callback = array($this, 'mycode_parse_post_quotes_callback1');
}
else
{
$replace = "\n{$lang->quote}\n--\n$1\n--\n";
$replace_callback = array($this, 'mycode_parse_post_quotes_callback2');
}
do
{
// preg_replace has erased the message? Restore it...
$previous_message = $message;
$message = preg_replace($pattern, $replace, $message, -1, $count);
$message = preg_replace_callback($pattern_callback, $replace_callback, $message, -1, $count_callback);
if(!$message)
{
$message = $previous_message;
break;
}
} while($count || $count_callback);
if($text_only == false)
{
$find = array(
"#(\r\n*|\n*)<\/cite>(\r\n*|\n*)#",
"#(\r\n*|\n*)<\/blockquote>#"
);
$replace = array(
"</cite><br />",
"</blockquote>"
);
$message = preg_replace($find, $replace, $message);
}
return $message;
}
/**
* Parses quotes with post id and/or dateline.
*
* @param string The message to be parsed
* @param string The username to be parsed
* @param boolean Are we formatting as text?
* @return string The parsed message.
*/
function mycode_parse_post_quotes($message, $username, $text_only=false)
{
global $lang, $templates, $theme, $mybb;
$linkback = $date = "";
$message = trim($message);
$message = preg_replace("#(^<br(\s?)(\/?)>|<br(\s?)(\/?)>$)#i", "", $message);
if(!$message) return '';
$message = str_replace('\"', '"', $message);
$username = str_replace('\"', '"', $username)."'";
$delete_quote = true;
preg_match("#pid=(?:"|\"|')?([0-9]+)[\"']?(?:"|\"|')?#i", $username, $match);
if(intval($match[1]))
{
$pid = intval($match[1]);
$url = $mybb->settings['bburl']."/".get_post_link($pid)."#pid$pid";
if(defined("IN_ARCHIVE"))
{
$linkback = " <a href=\"{$url}\">[ -> ]</a>";
}
else
{
eval("\$linkback = \" ".$templates->get("postbit_gotopost", 1, 0)."\";");
}
$username = preg_replace("#(?:"|\"|')? pid=(?:"|\"|')?[0-9]+[\"']?(?:"|\"|')?#i", '', $username);
$delete_quote = false;
}
unset($match);
preg_match("#dateline=(?:"|\"|')?([0-9]+)(?:"|\"|')?#i", $username, $match);
if(intval($match[1]))
{
if($match[1] < TIME_NOW)
{
$postdate = my_date($mybb->settings['dateformat'], intval($match[1]));
$posttime = my_date($mybb->settings['timeformat'], intval($match[1]));
$date = " ({$postdate} {$posttime})";
}
$username = preg_replace("#(?:"|\"|')? dateline=(?:"|\"|')?[0-9]+(?:"|\"|')?#i", '', $username);
$delete_quote = false;
}
if($delete_quote)
{
$username = my_substr($username, 0, my_strlen($username)-1);
}
if($text_only)
{
return "\n".htmlspecialchars_uni($username)." $lang->wrote{$date}\n--\n{$message}\n--\n";
}
else
{
$span = "";
if(!$delete_quote)
{
$span = "<span>{$date}</span>";
}
return "<blockquote><cite>{$span}".htmlspecialchars_uni($username)." $lang->wrote{$linkback}</cite>{$message}</blockquote>\n";
}
}
/**
* Parses quotes with post id and/or dateline.
*
* @param array Matches.
* @return string The parsed message.
*/
function mycode_parse_post_quotes_callback1($matches)
{
return $this->mycode_parse_post_quotes($matches[4],$matches[2].$matches[3]);
}
/**
* Parses quotes with post id and/or dateline.
*
* @param array Matches.
* @return string The parsed message.
*/
function mycode_parse_post_quotes_callback2($matches)
{
return $this->mycode_parse_post_quotes($matches[4],$matches[2].$matches[3], true);
}
/**
* Parses code MyCode.
*
* @param string The message to be parsed
* @param boolean Are we formatting as text?
* @return string The parsed message.
*/
function mycode_parse_code($code, $text_only=false)
{
global $lang;
if($text_only == true)
{
return "\n{$lang->code}\n--\n{$code}\n--\n";
}
// Clean the string before parsing.
$code = preg_replace('#^(\t*)(\n|\r|\0|\x0B| )*#', '\\1', $code);
$code = rtrim($code);
$original = preg_replace('#^\t*#', '', $code);
if(empty($original))
{
return;
}
$code = str_replace('$', '$', $code);
$code = preg_replace('#\$([0-9])#', '\\\$\\1', $code);
$code = str_replace('\\', '\', $code);
$code = str_replace("\t", ' ', $code);
$code = str_replace(" ", ' ', $code);
return "<div class=\"codeblock\">\n<div class=\"title\">".$lang->code."\n</div><div class=\"body\" dir=\"ltr\"><code>".$code."</code></div></div>\n";
}
/**
* Parses code MyCode.
*
* @param array Matches.
* @return string The parsed message.
*/
function mycode_parse_code_callback($matches)
{
return $this->mycode_parse_code($matches[1], true);
}
/**
* Parses PHP code MyCode.
*
* @param string The message to be parsed
* @param boolean Whether or not it should return it as pre-wrapped in a div or not.
* @param boolean Are we formatting as text?
* @return string The parsed message.
*/
function mycode_parse_php($str, $bare_return = false, $text_only = false)
{
global $lang;
if($text_only == true)
{
return "\n{$lang->php_code}\n--\n$str\n--\n";
}
// Clean the string before parsing except tab spaces.
$str = preg_replace('#^(\t*)(\n|\r|\0|\x0B| )*#', '\\1', $str);
$str = rtrim($str);
$original = preg_replace('#^\t*#', '', $str);
if(empty($original))
{
return;
}
$str = str_replace('&', '&', $str);
$str = str_replace('<', '<', $str);
$str = str_replace('>', '>', $str);
// See if open and close tags are provided.
$added_open_tag = false;
if(!preg_match("#^\s*<\?#si", $str))
{
$added_open_tag = true;
$str = "<?php \n".$str;
}
$added_end_tag = false;
if(!preg_match("#\?>\s*$#si", $str))
{
$added_end_tag = true;
$str = $str." \n?>";
}
$code = @highlight_string($str, true);
// Do the actual replacing.
$code = preg_replace('#<code>\s*<span style="color: \#000000">\s*#i', "<code>", $code);
$code = preg_replace("#</span>\s*</code>#", "</code>", $code);
$code = preg_replace("#</span>(\r\n?|\n?)</code>#", "</span></code>", $code);
$code = str_replace("\\", '\', $code);
$code = str_replace('$', '$', $code);
$code = preg_replace("#&\#([0-9]+);#si", "&#$1;", $code);
if($added_open_tag)
{
$code = preg_replace("#<code><span style=\"color: \#([A-Z0-9]{6})\"><\?php( | )(<br />?)#", "<code><span style=\"color: #$1\">", $code);
}
if($added_end_tag)
{
$code = str_replace("?></span></code>", "</span></code>", $code);
// Wait a minute. It fails highlighting? Stupid highlighter.
$code = str_replace("?></code>", "</code>", $code);
}
$code = preg_replace("#<span style=\"color: \#([A-Z0-9]{6})\"></span>#", "", $code);
$code = str_replace("<code>", "<div dir=\"ltr\"><code>", $code);
$code = str_replace("</code>", "</code></div>", $code);
$code = preg_replace("# *$#", "", $code);
if($bare_return)
{
return $code;
}
// Send back the code all nice and pretty
return "<div class=\"codeblock phpcodeblock\"><div class=\"title\">$lang->php_code\n</div><div class=\"body\">".$code."</div></div>\n";
}
/**
* Parses PHP code MyCode.
*
* @param array Matches.
* @return string The parsed message.
*/
function mycode_parse_php_callback($matches)
{
return $this->mycode_parse_php($matches[1], false, true);
}
/**
* Parses URL MyCode.
*
* @param string The URL to link to.
* @param string The name of the link.
* @return string The built-up link.
*/
function mycode_parse_url($url, $name="")
{
if(!preg_match("#^[a-z0-9]+://#i", $url))
{
$url = "http://".$url;
}
$fullurl = $url;
$url = str_replace('&', '&', $url);
$name = str_replace('&', '&', $name);
if(!$name)
{
$name = $url;
}
$name = str_replace("\'", "'", $name);
$url = str_replace("\'", "'", $url);
$fullurl = str_replace("\'", "'", $fullurl);
if($name == $url && (!isset($this->options['shorten_urls']) || $this->options['shorten_urls'] != 0))
{
if(my_strlen($url) > 55)
{
$name = my_substr($url, 0, 40)."...".my_substr($url, -10);
}
}
$nofollow = '';
if(isset($this->options['nofollow_on']))
{
$nofollow = " rel=\"nofollow\"";
}
// Fix some entities in URLs
$entities = array('$' => '%24', '$' => '%24', '^' => '%5E', '`' => '%60', '[' => '%5B', ']' => '%5D', '{' => '%7B', '}' => '%7D', '"' => '%22', '<' => '%3C', '>' => '%3E', ' ' => '%20');
$fullurl = str_replace(array_keys($entities), array_values($entities), $fullurl);
$name = preg_replace("#&\#([0-9]+);#si", "&#$1;", $name); // Fix & but allow unicode
$link = "<a href=\"$fullurl\" target=\"_blank\"{$nofollow}>$name</a>";
return $link;
}
/**
* Parses URL MyCode.
*
* @param array Matches.
* @return string The built-up link.
*/
function mycode_parse_url_callback1($matches)
{
if(!isset($matches[3]))
{
$matches[3] = '';
}
return $this->mycode_parse_url($matches[1].$matches[2], $matches[3]);
}
/**
* Parses URL MyCode.
*
* @param array Matches.
* @return string The built-up link.
*/
function mycode_parse_url_callback2($matches)
{
if(!isset($matches[2]))
{
$matches[2] = '';
}
return $this->mycode_parse_url($matches[1], $matches[2]);
}
/**
* Parses IMG MyCode.
*
* @param string The URL to the image
* @param array Optional array of dimensions
*/
function mycode_parse_img($url, $dimensions=array(), $align='')
{
global $lang;
$url = trim($url);
$url = str_replace("\n", "", $url);
$url = str_replace("\r", "", $url);
if($align == "right")
{
$css_align = " style=\"float: right;\"";
}
else if($align == "left")
{
$css_align = " style=\"float: left;\"";
}
$alt = htmlspecialchars_uni(basename($url));
if(my_strlen($alt) > 55)
{
$alt = my_substr($alt, 0, 40)."...".my_substr($alt, -10);
}
$alt = $lang->sprintf($lang->posted_image, $alt);
if($dimensions[0] > 0 && $dimensions[1] > 0)
{
return "<img src=\"{$url}\" width=\"{$dimensions[0]}\" height=\"{$dimensions[1]}\" border=\"0\" alt=\"{$alt}\"{$css_align} />";
}
else
{
return "<img src=\"{$url}\" border=\"0\" alt=\"{$alt}\"{$css_align} />";
}
}
/**
* Parses IMG MyCode.
*
* @param array Matches.
* @return string Image code.
*/
function mycode_parse_img_callback1($matches)
{
return $this->mycode_parse_img($matches[2]);
}
/**
* Parses IMG MyCode.
*
* @param array Matches.
* @return string Image code.
*/
function mycode_parse_img_callback2($matches)
{
return $this->mycode_parse_img($matches[4], array($matches[1], $matches[2]));
}
/**
* Parses IMG MyCode.
*
* @param array Matches.
* @return string Image code.
*/
function mycode_parse_img_callback3($matches)
{
return $this->mycode_parse_img($matches[3], array(), $matches[1]);
}
/**
* Parses IMG MyCode.
*
* @param array Matches.
* @return string Image code.
*/
function mycode_parse_img_callback4($matches)
{
return $this->mycode_parse_img($matches[5], array($matches[1], $matches[2]), $matches[3]);
}
/**
* Parses email MyCode.
*
* @param string The email address to link to.
* @param string The name for the link.
* @return string The built-up email link.
*/
function mycode_parse_email($email, $name="")
{
$name = str_replace("\\'", "'", $name);
$email = str_replace("\\'", "'", $email);
if(!$name)
{
$name = $email;
}
if(preg_match("/^([a-zA-Z0-9-_\+\.]+?)@[a-zA-Z0-9-]+\.[a-zA-Z0-9\.-]+$/si", $email))
{
return "<a href=\"mailto:$email\">".$name."</a>";
}
else
{
return $email;
}
}
/**
* Parses email MyCode.
*
* @param array Matches
* @return string The built-up email link.
*/
function mycode_parse_email_callback($matches)
{
if(!isset($matches[2]))
{
$matches[2] = '';
}
return $this->mycode_parse_email($matches[1], $matches[2]);
}
/**
* Parses video MyCode.
*
* @param string The video provider.
* @param string The video to link to.
* @return string The built-up video code.
*/
function mycode_parse_video($video, $url)
{
global $templates;
if(empty($video) || empty($url))
{
return "[video={$video}]{$url}[/video]";
}
$parsed_url = @parse_url(urldecode($url));
if($parsed_url == false)
{
return "[video={$video}]{$url}[/video]";
}
$fragments = array();
if($parsed_url['fragment'])
{
$fragments = explode("&", $parsed_url['fragment']);
}
$queries = explode("&", $parsed_url['query']);
$input = array();
foreach($queries as $query)
{
list($key, $value) = explode("=", $query);
$key = str_replace("amp;", "", $key);
$input[$key] = $value;
}
$path = explode('/', $parsed_url['path']);
switch($video)
{
case "dailymotion":
list($id, ) = split("_", $path[2], 1); // http://www.dailymotion.com/video/fds123_title-goes-here
break;
case "metacafe":
$id = $path[2]; // http://www.metacafe.com/watch/fds123/title_goes_here/
$title = htmlspecialchars_uni($path[3]);
break;
case "myspacetv":
$id = $path[4]; // http://www.myspace.com/video/fds/fds/123
break;
case "yahoo":
$id = $path[1]; // http://xy.screen.yahoo.com/fds-123.html
// Support for localized portals
$domain = explode('.', $parsed_url['host']);
if($domain[0] != 'screen')
{
$local = htmlspecialchars_uni($domain[0]).'.';
}
else
{
$local = '';
}
break;
case "vimeo":
$id = $path[1]; // http://vimeo.com/fds123
break;
case "youtube":
if($fragments[0])
{
$id = str_replace('!v=', '', $fragments[0]); // http://www.youtube.com/watch#!v=fds123
}
elseif($input['v'])
{
$id = $input['v']; // http://www.youtube.com/watch?v=fds123
}
else
{
$id = $path[1]; // http://www.youtu.be/fds123
}
break;
default:
return "[video={$video}]{$url}[/video]";
}
if(empty($id))
{
return "[video={$video}]{$url}[/video]";
}
$id = htmlspecialchars_uni($id);
eval("\$video_code = \"".$templates->get("video_{$video}_embed")."\";");
return $video_code;
}
/**
* Parses video MyCode.
*
* @param array Matches.
* @return string The built-up video code.
*/
function mycode_parse_video_callback($matches)
{
return $this->mycode_parse_video($matches[1], $matches[2]);
}
/**
* Parses URLs automatically.
*
* @param string The message to be parsed
* @return string The parsed message.
*/
function mycode_auto_url($message)
{
$message = " ".$message;
$message = preg_replace("#([\>\s\(\)])(http|https|ftp|news){1}://([^\/\"\s\<\[\.]+\.([^\/\"\s\<\[\.]+\.)*[\w]+(:[0-9]+)?(/[^\"\s<\[]*)?)#i", "$1[url]$2://$3[/url]", $message);
$message = preg_replace("#([\>\s\(\)])(www|ftp)\.(([^\/\"\s\<\[\.]+\.)*[\w]+(:[0-9]+)?(/[^\"\s<\[]*)?)#i", "$1[url]$2.$3[/url]", $message);
$message = my_substr($message, 1);
return $message;
}
/**
* Parses list MyCode.
*
* @param string The message to be parsed
* @param string The list type
* @return string The parsed message.
*/
function mycode_parse_list($message, $type="")
{
$message = str_replace('\"', '"', $message);
$message = preg_replace("#\s*\[\*\]\s*#", "</li>\n<li>", $message);
$message .= "</li>";
if($type)
{
$list = "\n<ol type=\"$type\">$message</ol>\n";
}
else
{
$list = "<ul>$message</ul>\n";
}
$list = preg_replace("#<(ol type=\"$type\"|ul)>\s*</li>#", "<$1>", $list);
return $list;
}
/**
* Parses list MyCode.
*
* @param array Matches
* @return string The parsed message.
*/
function mycode_parse_list_callback($matches)
{
return $this->mycode_parse_list($matches[1]);
}
/**
* Parses list MyCode.
*
* @param array Matches
* @return string The parsed message.
*/
function mycode_parse_list_callback_type($matches)
{
return $this->mycode_parse_list($matches[2], $matches[1]);
}
/**
* Strips smilies from a string
*
* @param string The message for smilies to be stripped from
* @return string The message with smilies stripped
*/
function strip_smilies($message)
{
if($this->smilies_cache == 0)
{
$this->cache_smilies();
}
if(is_array($this->smilies_cache))
{
$message = str_replace($this->smilies_cache, array_keys($this->smilies_cache), $message);
}
return $message;
}
/**
* Highlights a string
*
* @param string The message to be highligted
* @param string The highlight keywords
* @return string The message with highlight bbcodes
*/
function highlight_message($message, $highlight)
{
if(empty($this->highlight_cache))
{
$this->highlight_cache = build_highlight_array($highlight);
}
if(is_array($this->highlight_cache) && !empty($this->highlight_cache))
{
$message = preg_replace(array_keys($this->highlight_cache), $this->highlight_cache, $message);
}
return $message;
}
/**
* Parses message to plain text equivalents of MyCode.
*
* @param string The message to be parsed
* @return string The parsed message.
*/
function text_parse_message($message, $options=array())
{
global $plugins;
// Filter bad words if requested.
if($options['filter_badwords'] != 0)
{
$message = $this->parse_badwords($message);
}
// Parse quotes first
$message = $this->mycode_parse_quotes($message, true);
$message = preg_replace_callback("#\[php\](.*?)\[/php\](\r\n?|\n?)#is", array($this, 'mycode_parse_php_callback'), $message);
$message = preg_replace_callback("#\[code\](.*?)\[/code\](\r\n?|\n?)#is", array($this, 'mycode_parse_code_callback'), $message);
$find = array(
"#\[(b|u|i|s|url|email|color|img)\](.*?)\[/\\1\]#is",
"#\[img=([0-9]{1,3})x([0-9]{1,3})\](\r\n?|\n?)(https?://([^<>\"']+?))\[/img\]#is",
"#\[url=([a-z]+?://)([^\r\n\"<]+?)\](.+?)\[/url\]#si",
"#\[url=([^\r\n\"<&\(\)]+?)\](.+?)\[/url\]#si",
);
$replace = array(
"$2",
"$4",
"$3 ($1$2)",
"$2 ($1)",
);
$message = preg_replace($find, $replace, $message);
// Replace "me" code and slaps if we have a username
if($options['me_username'])
{
global $lang;
$message = preg_replace('#(>|^|\r|\n)/me ([^\r\n<]*)#i', "\\1* {$options['me_username']} \\2", $message);
$message = preg_replace('#(>|^|\r|\n)/slap ([^\r\n<]*)#i', "\\1* {$options['me_username']} {$lang->slaps} \\2 {$lang->with_trout}", $message);
}
// Special code requiring special attention
while(preg_match("#\[list\](.*?)\[/list\]#si", $message))
{
$message = preg_replace_callback("#\s?\[list\](.*?)\[/list\](\r\n?|\n?)#si", array($this, 'mycode_parse_list_callback'), $message);
}
// Replace lists.
while(preg_match("#\[list=(a|A|i|I|1)\](.*?)\[/list\](\r\n?|\n?)#si", $message))
{
$message = preg_replace_callback("#\s?\[list=(a|A|i|I|1)\](.*?)\[/list\]#si", array($this, 'mycode_parse_list_callback_type'), $message);
}
// Run plugin hooks
$message = $plugins->run_hooks("text_parse_message", $message);
return $message;
}
}
?>
|
238696e37d6a22b89e6bba11e4de3e6620cb5547
|
https://github.com/mybb/mybb
|
bug_change_status_page.php
|
php
|
<?php
# MantisBT - A PHP based bugtracking system
# MantisBT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# MantisBT 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 MantisBT. If not, see <http://www.gnu.org/licenses/>.
/**
* Handling of Bug Status change
* @package MantisBT
* @copyright Copyright 2000 - 2002 Kenzaburo Ito - kenito@300baud.org
* @copyright Copyright 2002 MantisBT Team - mantisbt-dev@lists.sourceforge.net
* @link http://www.mantisbt.org
*
* @uses core.php
* @uses access_api.php
* @uses authentication_api.php
* @uses bug_api.php
* @uses config_api.php
* @uses constant_inc.php
* @uses custom_field_api.php
* @uses date_api.php
* @uses event_api.php
* @uses form_api.php
* @uses gpc_api.php
* @uses helper_api.php
* @uses html_api.php
* @uses lang_api.php
* @uses print_api.php
* @uses relationship_api.php
* @uses sponsorship_api.php
* @uses version_api.php
*/
$g_allow_browser_cache = 1;
require_once( 'core.php' );
require_api( 'access_api.php' );
require_api( 'authentication_api.php' );
require_api( 'bug_api.php' );
require_api( 'config_api.php' );
require_api( 'constant_inc.php' );
require_api( 'custom_field_api.php' );
require_api( 'date_api.php' );
require_api( 'event_api.php' );
require_api( 'form_api.php' );
require_api( 'gpc_api.php' );
require_api( 'helper_api.php' );
require_api( 'html_api.php' );
require_api( 'lang_api.php' );
require_api( 'print_api.php' );
require_api( 'relationship_api.php' );
require_api( 'sponsorship_api.php' );
require_api( 'version_api.php' );
$f_bug_id = gpc_get_int( 'id' );
$t_bug = bug_get( $f_bug_id );
$t_file = __FILE__;
$t_mantis_dir = dirname( __FILE__ ) . DIRECTORY_SEPARATOR;
$t_show_page_header = false;
$t_force_readonly = true;
$t_fields_config_option = 'bug_change_status_page_fields';
if( $t_bug->project_id != helper_get_current_project() ) {
# in case the current project is not the same project of the bug we are viewing...
# ... override the current project. This to avoid problems with categories and handlers lists etc.
$g_project_override = $t_bug->project_id;
}
$f_new_status = gpc_get_int( 'new_status' );
$f_change_type = gpc_get_string( 'change_type', BUG_UPDATE_TYPE_CHANGE_STATUS );
$t_reopen = config_get( 'bug_reopen_status', null, null, $t_bug->project_id );
$t_resolved = config_get( 'bug_resolved_status_threshold', null, null, $t_bug->project_id );
$t_closed = config_get( 'bug_closed_status_threshold', null, null, $t_bug->project_id );
$t_current_user_id = auth_get_current_user_id();
# Ensure user has proper access level before proceeding
if( $f_new_status == $t_reopen && $f_change_type == BUG_UPDATE_TYPE_REOPEN ) {
access_ensure_can_reopen_bug( $t_bug, $t_current_user_id );
} else if( $f_new_status == $t_closed ) {
access_ensure_can_close_bug( $t_bug, $t_current_user_id );
} else if( bug_is_readonly( $f_bug_id )
|| !access_has_bug_level( access_get_status_threshold( $f_new_status, $t_bug->project_id ), $f_bug_id, $t_current_user_id ) ) {
access_denied();
}
$t_can_update_due_date = access_has_bug_level( config_get( 'due_date_update_threshold' ), $f_bug_id );
# get new issue handler if set, otherwise default to original handler
$f_handler_id = gpc_get_int( 'handler_id', $t_bug->handler_id );
if( config_get( 'bug_assigned_status' ) == $f_new_status ) {
$t_bug_sponsored = config_get( 'enable_sponsorship' )
&& sponsorship_get_amount( sponsorship_get_all_ids( $f_bug_id ) ) > 0;
if( $t_bug_sponsored && !access_has_bug_level( config_get( 'assign_sponsored_bugs_threshold' ), $f_bug_id ) ) {
trigger_error( ERROR_SPONSORSHIP_ASSIGNER_ACCESS_LEVEL_TOO_LOW, ERROR );
}
if( $f_handler_id != NO_USER ) {
if( !access_has_bug_level( config_get( 'handle_bug_threshold' ), $f_bug_id, $f_handler_id ) ) {
trigger_error( ERROR_HANDLER_ACCESS_TOO_LOW, ERROR );
}
if( $t_bug_sponsored && !access_has_bug_level( config_get( 'handle_sponsored_bugs_threshold' ), $f_bug_id, $f_handler_id ) ) {
trigger_error( ERROR_SPONSORSHIP_HANDLER_ACCESS_LEVEL_TOO_LOW, ERROR );
}
}
}
$t_status_label = str_replace( ' ', '_', MantisEnum::getLabel( config_get( 'status_enum_string' ), $f_new_status ) );
layout_page_header( bug_format_summary( $f_bug_id, SUMMARY_CAPTION ) );
layout_page_begin();
?>
<div class="col-md-12 col-xs-12">
<div id="bug-change-status-div" class="form-container">
<form id="bug-change-status-form" name="bug_change_status_form" method="post" action="bug_update.php">
<fieldset>
<?php echo form_security_field( 'bug_update' ) ?>
<div class="widget-box widget-color-blue2">
<div class="widget-header widget-header-small">
<h4 class="widget-title lighter">
<?php echo lang_get( $t_status_label . '_bug_title' ) ?>
</h4>
</div>
<div class="widget-body">
<div class="widget-main no-padding">
<div class="table-responsive">
<table class="table table-bordered table-condensed table-striped">
<thead>
<input type="hidden" name="bug_id" value="<?php echo $f_bug_id ?>" />
<input type="hidden" name="status" value="<?php echo $f_new_status ?>" />
<input type="hidden" name="last_updated" value="<?php echo $t_bug->last_updated ?>" />
<?php
if( $f_new_status >= $t_resolved ) {
if( relationship_can_resolve_bug( $f_bug_id ) == false ) {
echo '<tr><td colspan="2">' . lang_get( 'relationship_warning_blocking_bugs_not_resolved_2' ) . '</td></tr>';
}
}
?>
</thead>
<tbody>
<?php
$t_current_resolution = $t_bug->resolution;
$t_bug_is_open = $t_current_resolution < $t_resolved;
if( $f_new_status >= $t_resolved && ( $f_new_status < $t_closed || $t_bug_is_open ) ) {
?>
<!-- Resolution -->
<tr>
<th class="category">
<?php echo lang_get( 'resolution' ) ?>
</th>
<td>
<select name="resolution" class="input-sm">
<?php
$t_resolution = $t_bug_is_open ? config_get( 'bug_resolution_fixed_threshold' ) : $t_current_resolution;
$t_relationships = relationship_get_all_src( $f_bug_id );
foreach( $t_relationships as $t_relationship ) {
if( $t_relationship->type == BUG_DUPLICATE ) {
$t_resolution = config_get( 'bug_duplicate_resolution' );
break;
}
}
print_enum_string_option_list( 'resolution', $t_resolution );
?>
</select>
</td>
</tr>
<?php
if( $t_resolution != config_get( 'bug_duplicate_resolution' ) ) {
?>
<!-- Duplicate ID -->
<tr>
<th class="category">
<?php echo lang_get( 'duplicate_id' ) ?>
</th>
<td>
<input type="text" class="input-sm" name="duplicate_id" maxlength="10" />
</td>
</tr>
<?php
}
}
if( access_has_bug_level( config_get( 'update_bug_assign_threshold', config_get( 'update_bug_threshold' ) ), $f_bug_id ) ) {
$t_suggested_handler_id = $t_bug->handler_id;
if( $t_suggested_handler_id == NO_USER && access_has_bug_level( config_get( 'handle_bug_threshold' ), $f_bug_id ) ) {
$t_suggested_handler_id = $t_current_user_id;
}
?>
<!-- Assigned To -->
<tr>
<th class="category">
<?php echo lang_get( 'assigned_to' ) ?>
</th>
<td>
<select name="handler_id" class="input-sm">
<option value="0"></option>
<?php print_assign_to_option_list( $t_suggested_handler_id, $t_bug->project_id ) ?>
</select>
</td>
</tr>
<?php } ?>
<?php
if( $t_can_update_due_date ) {
$t_date_to_display = '';
if( !date_is_null( $t_bug->due_date ) ) {
$t_date_to_display = date( config_get( 'normal_date_format' ), $t_bug->due_date );
}
?>
<!-- Due date -->
<tr>
<th class="category">
<?php echo lang_get( 'due_date' ) ?>
</th>
<td>
<input type="text" id="due_date" name="due_date" class="datetimepicker input-sm" size="16" maxlength="16"
data-picker-locale="<?php lang_get_current_datetime_locale() ?>"
data-picker-format="<?php echo config_get( 'datetime_picker_format' ) ?>"
<?php helper_get_tab_index() ?> value="<?php echo $t_date_to_display ?>" />
<i class="fa fa-calendar fa-xlg datetimepicker"></i>
</td>
</tr>
<?php
}
?>
<!-- Custom Fields -->
<?php
/**
* @todo thraxisp - I undid part of the change for #5068 for #5527
* We really need to say what fields are shown in which statusses. For now,
* this page will show required custom fields in update mode, or
* display or required fields on resolve or close
*/
$t_custom_status_label = 'update'; # Don't show custom fields by default
if( ( $f_new_status >= $t_resolved ) && ( $f_new_status < $t_closed ) ) {
$t_custom_status_label = 'resolved';
}
if( $t_closed == $f_new_status ) {
$t_custom_status_label = 'closed';
}
$t_related_custom_field_ids = custom_field_get_linked_ids( $t_bug->project_id );
foreach( $t_related_custom_field_ids as $t_id ) {
$t_def = custom_field_get_definition( $t_id );
$t_display = $t_def['display_' . $t_custom_status_label];
$t_require = $t_def['require_' . $t_custom_status_label];
if( ( 'update' == $t_custom_status_label ) && ( !$t_require ) ) {
continue;
}
if( in_array( $t_custom_status_label, array( 'resolved', 'closed' ) ) && !( $t_display || $t_require ) ) {
continue;
}
$t_has_write_access = custom_field_has_write_access( $t_id, $f_bug_id );
$t_class_required = $t_require && $t_has_write_access ? 'class="required"' : '';
?>
<tr>
<th class="category">
<?php echo lang_get_defaulted( $t_def['name'] ) ?>
</th>
<td>
<?php
if( $t_has_write_access ) {
print_custom_field_input( $t_def, $f_bug_id );
} elseif( custom_field_has_read_access( $t_id, $f_bug_id ) ) {
print_custom_field_value( $t_def, $t_id, $f_bug_id );
}
?>
</td>
</tr>
<?php
} # foreach( $t_related_custom_field_ids as $t_id )
if( ( $f_new_status >= $t_resolved ) ) {
if( version_should_show_product_version( $t_bug->project_id )
&& !bug_is_readonly( $f_bug_id )
&& access_has_bug_level( config_get( 'update_bug_threshold' ), $f_bug_id )
) {
?>
<!-- Fixed in Version -->
<tr>
<th class="category">
<?php echo lang_get( 'fixed_in_version' ) ?>
</th>
<td>
<select name="fixed_in_version" class="input-sm">
<?php print_version_option_list( $t_bug->fixed_in_version, $t_bug->project_id, VERSION_ALL ) ?>
</select>
</td>
</tr>
<?php
}
}
event_signal( 'EVENT_UPDATE_BUG_STATUS_FORM', array( $f_bug_id, $f_new_status ) );
if( $f_change_type == BUG_UPDATE_TYPE_REOPEN ) {
?>
<!-- Bug was re-opened -->
<?php
printf( ' <input type="hidden" name="resolution" value="%s" />' . "\n", config_get( 'bug_reopen_resolution' ) );
}
?>
<?php if( access_has_bug_level( config_get( 'private_bugnote_threshold' ), $f_bug_id ) ) { ?>
<tr>
<th class="category">
<?php echo lang_get( 'view_status' ) ?>
</th>
<td>
<?php
$t_default_bugnote_view_status = config_get( 'default_bugnote_view_status' );
if( access_has_bug_level( config_get( 'set_view_status_threshold' ), $f_bug_id ) ) {
?>
<input type="checkbox" id="bugnote_add_view_status" class="ace" name="private"
<?php check_checked( $t_default_bugnote_view_status, VS_PRIVATE ); ?> />
<label class="lbl" for="bugnote_add_view_status"> <?php echo lang_get( 'private' ) ?> </label>
<?php
} else {
echo get_enum_element( 'project_view_state', $t_default_bugnote_view_status );
}
?>
</td>
</tr>
<?php } ?>
<!-- Bugnote -->
<tr id="bug-change-status-note">
<th class="category">
<?php echo lang_get( 'add_bugnote_title' ) ?>
</th>
<td>
<textarea class="form-control" name="bugnote_text" cols="80" rows="10"></textarea>
</td>
</tr>
<?php
if( config_get( 'time_tracking_enabled' )
&& access_has_bug_level( config_get( 'private_bugnote_threshold' ), $f_bug_id )
&& access_has_bug_level( config_get( 'time_tracking_edit_threshold' ), $f_bug_id )
) {
?>
<tr>
<th class="category">
<?php echo lang_get( 'time_tracking' ) ?>
</th>
<td>
<input type="text" name="time_tracking" class="input-sm" size="5" placeholder="hh:mm" />
</td>
</tr>
<?php
}
event_signal( 'EVENT_BUGNOTE_ADD_FORM', array( $f_bug_id ) );
?>
</tbody>
</table>
<input type="hidden" name="action_type" value="<?php echo $f_change_type; ?>" />
</div>
</div>
<div class="widget-toolbox padding-8 clearfix">
<input type="submit" class="btn btn-primary btn-white btn-round" value="<?php echo lang_get( $t_status_label . '_bug_button' ) ?>" />
</div>
</div>
</div>
</div>
</form>
<div class="space-10"></div>
</div>
<?php
define( 'BUG_VIEW_INC_ALLOW', true );
include( dirname( __FILE__ ) . '/bug_view_inc.php' );
|
<?php
# MantisBT - A PHP based bugtracking system
# MantisBT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# MantisBT 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 MantisBT. If not, see <http://www.gnu.org/licenses/>.
/**
* Handling of Bug Status change
* @package MantisBT
* @copyright Copyright 2000 - 2002 Kenzaburo Ito - kenito@300baud.org
* @copyright Copyright 2002 MantisBT Team - mantisbt-dev@lists.sourceforge.net
* @link http://www.mantisbt.org
*
* @uses core.php
* @uses access_api.php
* @uses authentication_api.php
* @uses bug_api.php
* @uses config_api.php
* @uses constant_inc.php
* @uses custom_field_api.php
* @uses date_api.php
* @uses event_api.php
* @uses form_api.php
* @uses gpc_api.php
* @uses helper_api.php
* @uses html_api.php
* @uses lang_api.php
* @uses print_api.php
* @uses relationship_api.php
* @uses sponsorship_api.php
* @uses version_api.php
*/
$g_allow_browser_cache = 1;
require_once( 'core.php' );
require_api( 'access_api.php' );
require_api( 'authentication_api.php' );
require_api( 'bug_api.php' );
require_api( 'config_api.php' );
require_api( 'constant_inc.php' );
require_api( 'custom_field_api.php' );
require_api( 'date_api.php' );
require_api( 'event_api.php' );
require_api( 'form_api.php' );
require_api( 'gpc_api.php' );
require_api( 'helper_api.php' );
require_api( 'html_api.php' );
require_api( 'lang_api.php' );
require_api( 'print_api.php' );
require_api( 'relationship_api.php' );
require_api( 'sponsorship_api.php' );
require_api( 'version_api.php' );
$f_bug_id = gpc_get_int( 'id' );
$t_bug = bug_get( $f_bug_id );
$t_file = __FILE__;
$t_mantis_dir = dirname( __FILE__ ) . DIRECTORY_SEPARATOR;
$t_show_page_header = false;
$t_force_readonly = true;
$t_fields_config_option = 'bug_change_status_page_fields';
if( $t_bug->project_id != helper_get_current_project() ) {
# in case the current project is not the same project of the bug we are viewing...
# ... override the current project. This to avoid problems with categories and handlers lists etc.
$g_project_override = $t_bug->project_id;
}
$f_new_status = gpc_get_int( 'new_status' );
$f_change_type = gpc_get_string( 'change_type', BUG_UPDATE_TYPE_CHANGE_STATUS );
$t_reopen = config_get( 'bug_reopen_status', null, null, $t_bug->project_id );
$t_resolved = config_get( 'bug_resolved_status_threshold', null, null, $t_bug->project_id );
$t_closed = config_get( 'bug_closed_status_threshold', null, null, $t_bug->project_id );
$t_current_user_id = auth_get_current_user_id();
# Ensure user has proper access level before proceeding
if( $f_new_status == $t_reopen && $f_change_type == BUG_UPDATE_TYPE_REOPEN ) {
access_ensure_can_reopen_bug( $t_bug, $t_current_user_id );
} else if( $f_new_status == $t_closed ) {
access_ensure_can_close_bug( $t_bug, $t_current_user_id );
} else if( bug_is_readonly( $f_bug_id )
|| !access_has_bug_level( access_get_status_threshold( $f_new_status, $t_bug->project_id ), $f_bug_id, $t_current_user_id ) ) {
access_denied();
}
$t_can_update_due_date = access_has_bug_level( config_get( 'due_date_update_threshold' ), $f_bug_id );
# get new issue handler if set, otherwise default to original handler
$f_handler_id = gpc_get_int( 'handler_id', $t_bug->handler_id );
if( config_get( 'bug_assigned_status' ) == $f_new_status ) {
$t_bug_sponsored = config_get( 'enable_sponsorship' )
&& sponsorship_get_amount( sponsorship_get_all_ids( $f_bug_id ) ) > 0;
if( $t_bug_sponsored && !access_has_bug_level( config_get( 'assign_sponsored_bugs_threshold' ), $f_bug_id ) ) {
trigger_error( ERROR_SPONSORSHIP_ASSIGNER_ACCESS_LEVEL_TOO_LOW, ERROR );
}
if( $f_handler_id != NO_USER ) {
if( !access_has_bug_level( config_get( 'handle_bug_threshold' ), $f_bug_id, $f_handler_id ) ) {
trigger_error( ERROR_HANDLER_ACCESS_TOO_LOW, ERROR );
}
if( $t_bug_sponsored && !access_has_bug_level( config_get( 'handle_sponsored_bugs_threshold' ), $f_bug_id, $f_handler_id ) ) {
trigger_error( ERROR_SPONSORSHIP_HANDLER_ACCESS_LEVEL_TOO_LOW, ERROR );
}
}
}
$t_status_label = str_replace( ' ', '_', MantisEnum::getLabel( config_get( 'status_enum_string' ), $f_new_status ) );
layout_page_header( bug_format_summary( $f_bug_id, SUMMARY_CAPTION ) );
layout_page_begin();
?>
<div class="col-md-12 col-xs-12">
<div id="bug-change-status-div" class="form-container">
<form id="bug-change-status-form" name="bug_change_status_form" method="post" action="bug_update.php">
<fieldset>
<?php echo form_security_field( 'bug_update' ) ?>
<div class="widget-box widget-color-blue2">
<div class="widget-header widget-header-small">
<h4 class="widget-title lighter">
<?php echo lang_get( $t_status_label . '_bug_title' ) ?>
</h4>
</div>
<div class="widget-body">
<div class="widget-main no-padding">
<div class="table-responsive">
<table class="table table-bordered table-condensed table-striped">
<thead>
<input type="hidden" name="bug_id" value="<?php echo $f_bug_id ?>" />
<input type="hidden" name="status" value="<?php echo $f_new_status ?>" />
<input type="hidden" name="last_updated" value="<?php echo $t_bug->last_updated ?>" />
<?php
if( $f_new_status >= $t_resolved ) {
if( relationship_can_resolve_bug( $f_bug_id ) == false ) {
echo '<tr><td colspan="2">' . lang_get( 'relationship_warning_blocking_bugs_not_resolved_2' ) . '</td></tr>';
}
}
?>
</thead>
<tbody>
<?php
$t_current_resolution = $t_bug->resolution;
$t_bug_is_open = $t_current_resolution < $t_resolved;
if( $f_new_status >= $t_resolved && ( $f_new_status < $t_closed || $t_bug_is_open ) ) {
?>
<!-- Resolution -->
<tr>
<th class="category">
<?php echo lang_get( 'resolution' ) ?>
</th>
<td>
<select name="resolution" class="input-sm">
<?php
$t_resolution = $t_bug_is_open ? config_get( 'bug_resolution_fixed_threshold' ) : $t_current_resolution;
$t_relationships = relationship_get_all_src( $f_bug_id );
foreach( $t_relationships as $t_relationship ) {
if( $t_relationship->type == BUG_DUPLICATE ) {
$t_resolution = config_get( 'bug_duplicate_resolution' );
break;
}
}
print_enum_string_option_list( 'resolution', $t_resolution );
?>
</select>
</td>
</tr>
<?php
if( $t_resolution != config_get( 'bug_duplicate_resolution' ) ) {
?>
<!-- Duplicate ID -->
<tr>
<th class="category">
<?php echo lang_get( 'duplicate_id' ) ?>
</th>
<td>
<input type="text" class="input-sm" name="duplicate_id" maxlength="10" />
</td>
</tr>
<?php
}
}
if( access_has_bug_level( config_get( 'update_bug_assign_threshold', config_get( 'update_bug_threshold' ) ), $f_bug_id ) ) {
$t_suggested_handler_id = $t_bug->handler_id;
if( $t_suggested_handler_id == NO_USER && access_has_bug_level( config_get( 'handle_bug_threshold' ), $f_bug_id ) ) {
$t_suggested_handler_id = $t_current_user_id;
}
?>
<!-- Assigned To -->
<tr>
<th class="category">
<?php echo lang_get( 'assigned_to' ) ?>
</th>
<td>
<select name="handler_id" class="input-sm">
<option value="0"></option>
<?php print_assign_to_option_list( $t_suggested_handler_id, $t_bug->project_id ) ?>
</select>
</td>
</tr>
<?php } ?>
<?php
if( $t_can_update_due_date ) {
$t_date_to_display = '';
if( !date_is_null( $t_bug->due_date ) ) {
$t_date_to_display = date( config_get( 'normal_date_format' ), $t_bug->due_date );
}
?>
<!-- Due date -->
<tr>
<th class="category">
<?php echo lang_get( 'due_date' ) ?>
</th>
<td>
<input type="text" id="due_date" name="due_date" class="datetimepicker input-sm" size="16" maxlength="16"
data-picker-locale="<?php lang_get_current_datetime_locale() ?>"
data-picker-format="<?php echo config_get( 'datetime_picker_format' ) ?>"
<?php helper_get_tab_index() ?> value="<?php echo $t_date_to_display ?>" />
<i class="fa fa-calendar fa-xlg datetimepicker"></i>
</td>
</tr>
<?php
}
?>
<!-- Custom Fields -->
<?php
/**
* @todo thraxisp - I undid part of the change for #5068 for #5527
* We really need to say what fields are shown in which statusses. For now,
* this page will show required custom fields in update mode, or
* display or required fields on resolve or close
*/
$t_custom_status_label = 'update'; # Don't show custom fields by default
if( ( $f_new_status >= $t_resolved ) && ( $f_new_status < $t_closed ) ) {
$t_custom_status_label = 'resolved';
}
if( $t_closed == $f_new_status ) {
$t_custom_status_label = 'closed';
}
$t_related_custom_field_ids = custom_field_get_linked_ids( $t_bug->project_id );
foreach( $t_related_custom_field_ids as $t_id ) {
$t_def = custom_field_get_definition( $t_id );
$t_display = $t_def['display_' . $t_custom_status_label];
$t_require = $t_def['require_' . $t_custom_status_label];
if( ( 'update' == $t_custom_status_label ) && ( !$t_require ) ) {
continue;
}
if( in_array( $t_custom_status_label, array( 'resolved', 'closed' ) ) && !( $t_display || $t_require ) ) {
continue;
}
$t_has_write_access = custom_field_has_write_access( $t_id, $f_bug_id );
$t_class_required = $t_require && $t_has_write_access ? 'class="required"' : '';
?>
<tr>
<th class="category">
<?php echo lang_get_defaulted( $t_def['name'] ) ?>
</th>
<td>
<?php
if( $t_has_write_access ) {
print_custom_field_input( $t_def, $f_bug_id );
} elseif( custom_field_has_read_access( $t_id, $f_bug_id ) ) {
print_custom_field_value( $t_def, $t_id, $f_bug_id );
}
?>
</td>
</tr>
<?php
} # foreach( $t_related_custom_field_ids as $t_id )
if( ( $f_new_status >= $t_resolved ) ) {
if( version_should_show_product_version( $t_bug->project_id )
&& !bug_is_readonly( $f_bug_id )
&& access_has_bug_level( config_get( 'update_bug_threshold' ), $f_bug_id )
) {
?>
<!-- Fixed in Version -->
<tr>
<th class="category">
<?php echo lang_get( 'fixed_in_version' ) ?>
</th>
<td>
<select name="fixed_in_version" class="input-sm">
<?php print_version_option_list( $t_bug->fixed_in_version, $t_bug->project_id, VERSION_ALL ) ?>
</select>
</td>
</tr>
<?php
}
}
event_signal( 'EVENT_UPDATE_BUG_STATUS_FORM', array( $f_bug_id, $f_new_status ) );
if( $f_change_type == BUG_UPDATE_TYPE_REOPEN ) {
?>
<!-- Bug was re-opened -->
<?php
printf( ' <input type="hidden" name="resolution" value="%s" />' . "\n", config_get( 'bug_reopen_resolution' ) );
}
?>
<?php if( access_has_bug_level( config_get( 'private_bugnote_threshold' ), $f_bug_id ) ) { ?>
<tr>
<th class="category">
<?php echo lang_get( 'view_status' ) ?>
</th>
<td>
<?php
$t_default_bugnote_view_status = config_get( 'default_bugnote_view_status' );
if( access_has_bug_level( config_get( 'set_view_status_threshold' ), $f_bug_id ) ) {
?>
<input type="checkbox" id="bugnote_add_view_status" class="ace" name="private"
<?php check_checked( $t_default_bugnote_view_status, VS_PRIVATE ); ?> />
<label class="lbl" for="bugnote_add_view_status"> <?php echo lang_get( 'private' ) ?> </label>
<?php
} else {
echo get_enum_element( 'project_view_state', $t_default_bugnote_view_status );
}
?>
</td>
</tr>
<?php } ?>
<!-- Bugnote -->
<tr id="bug-change-status-note">
<th class="category">
<?php echo lang_get( 'add_bugnote_title' ) ?>
</th>
<td>
<textarea class="form-control" name="bugnote_text" cols="80" rows="10"></textarea>
</td>
</tr>
<?php
if( config_get( 'time_tracking_enabled' )
&& access_has_bug_level( config_get( 'private_bugnote_threshold' ), $f_bug_id )
&& access_has_bug_level( config_get( 'time_tracking_edit_threshold' ), $f_bug_id )
) {
?>
<tr>
<th class="category">
<?php echo lang_get( 'time_tracking' ) ?>
</th>
<td>
<input type="text" name="time_tracking" class="input-sm" size="5" placeholder="hh:mm" />
</td>
</tr>
<?php
}
event_signal( 'EVENT_BUGNOTE_ADD_FORM', array( $f_bug_id ) );
?>
</tbody>
</table>
<input type="hidden" name="action_type" value="<?php echo string_attribute( $f_change_type ); ?>" />
</div>
</div>
<div class="widget-toolbox padding-8 clearfix">
<input type="submit" class="btn btn-primary btn-white btn-round" value="<?php echo lang_get( $t_status_label . '_bug_button' ) ?>" />
</div>
</div>
</div>
</div>
</form>
<div class="space-10"></div>
</div>
<?php
define( 'BUG_VIEW_INC_ALLOW', true );
include( dirname( __FILE__ ) . '/bug_view_inc.php' );
|
c272c3f65da9677e505ff692b1f1e476b3afa56e
|
https://github.com/mantisbt/mantisbt
|
timeline_inc.php
|
php
|
<?php
# MantisBT - a php based bugtracking system
# MantisBT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# MantisBT 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 MantisBT. If not, see <http://www.gnu.org/licenses/>.
require_once( 'core.php' );
require_api( 'timeline_api.php' );
define( 'MAX_EVENTS', 50 );
# Variables that are defined in parent script:
#
# $g_timeline_filter Filter array to be used to get timeline event
# If undefined, it's initialized as null.
# $g_timeline_user User id to limit timeline scope.
# If undefined, it's initialized as null.
#
if( !isset( $g_timeline_filter ) ) {
$g_timeline_filter = null;
}
if( !isset( $g_timeline_user ) ) {
$g_timeline_user = null;
}
$f_days = gpc_get_int( 'days', 0 );
$f_all = gpc_get_int( 'all', 0 );
$t_max_events = $f_all ? 0 : MAX_EVENTS + 1;
$t_end_time = time() - ( $f_days * SECONDS_PER_DAY );
$t_start_time = $t_end_time - ( 7 * SECONDS_PER_DAY );
$t_events = timeline_events( $t_start_time, $t_end_time, $t_max_events, $g_timeline_filter, $g_timeline_user );
$t_collapse_block = is_collapsed( 'timeline' );
$t_block_css = $t_collapse_block ? 'collapsed' : '';
$t_block_icon = $t_collapse_block ? 'fa-chevron-down' : 'fa-chevron-up';
$t_url_page = $_SERVER["PHP_SELF"];
$t_url_params = $_GET;
if( isset( $t_url_params['all'] ) ) {
unset( $t_url_params['all'] );
}
?>
<div id="timeline" class="widget-box widget-color-blue2 <?php echo $t_block_css ?>">
<div class="widget-header widget-header-small">
<h4 class="widget-title lighter">
<i class="ace-icon fa fa-clock-o"></i>
<?php echo lang_get( 'timeline_title' ) ?>
</h4>
<div class="widget-toolbar">
<a data-action="collapse" href="#">
<i class="1 ace-icon fa <?php echo $t_block_icon ?> bigger-125"></i>
</a>
</div>
</div>
<div class="widget-body">
<div class="widget-toolbox">
<div class="btn-toolbar">
<?php
$t_short_date_format = config_get( 'short_date_format' );
echo '  ';
echo '<span class="label label-grey"> ' . date( $t_short_date_format, $t_start_time ) . ' </span>';
echo ' .. ';
echo '<span class="label label-grey"> ' . date( $t_short_date_format, $t_end_time ) . ' </span>';
echo '  ';
echo '<div class="btn-group">';
$t_url_params['days'] = $f_days + 7;
$t_href = $t_url_page . '?' . http_build_query( $t_url_params );
echo ' <a class="btn btn-primary btn-xs btn-white btn-round" href="' . $t_href . '">' . lang_get( 'prev' ) . '</a>';
$t_next_days = ( $f_days - 7 ) > 0 ? $f_days - 7 : 0;
if( $t_next_days != $f_days ) {
$t_url_params['days'] = $t_next_days;
$t_href = $t_url_page . '?' . http_build_query( $t_url_params );
echo ' <a class="btn btn-primary btn-xs btn-white btn-round" href="' . $t_href . '">' . lang_get( 'next' ) . '</a>';
}
echo '</div>';
?>
</div>
</div>
<div class="widget-main no-padding">
<div class="profile-feed">
</div>
</div>
<?php
if( !$f_all && count( $t_events ) > MAX_EVENTS ) {
$t_events = array_slice( $t_events, 0, MAX_EVENTS );
timeline_print_events( $t_events );
echo '<div class="widget-toolbox">';
echo '<div class="btn-toolbar">';
$t_url_params['all'] = 1;
$t_href = $t_url_page . '?' . http_build_query( $t_url_params );
echo '<a class="btn btn-primary btn-sm btn-white btn-round" href="' . $t_href . '">' . lang_get( 'timeline_more' ) . '</a>';
echo '</div>';
echo '</div>';
} else {
timeline_print_events( $t_events );
}
?>
</div>
</div>
|
<?php
# MantisBT - a php based bugtracking system
# MantisBT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# MantisBT 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 MantisBT. If not, see <http://www.gnu.org/licenses/>.
require_once( 'core.php' );
require_api( 'timeline_api.php' );
define( 'MAX_EVENTS', 50 );
# Variables that are defined in parent script:
#
# $g_timeline_filter Filter array to be used to get timeline event
# If undefined, it's initialized as null.
# $g_timeline_user User id to limit timeline scope.
# If undefined, it's initialized as null.
#
if( !isset( $g_timeline_filter ) ) {
$g_timeline_filter = null;
}
if( !isset( $g_timeline_user ) ) {
$g_timeline_user = null;
}
$f_days = gpc_get_int( 'days', 0 );
$f_all = gpc_get_int( 'all', 0 );
$t_max_events = $f_all ? 0 : MAX_EVENTS + 1;
$t_end_time = time() - ( $f_days * SECONDS_PER_DAY );
$t_start_time = $t_end_time - ( 7 * SECONDS_PER_DAY );
$t_events = timeline_events( $t_start_time, $t_end_time, $t_max_events, $g_timeline_filter, $g_timeline_user );
$t_collapse_block = is_collapsed( 'timeline' );
$t_block_css = $t_collapse_block ? 'collapsed' : '';
$t_block_icon = $t_collapse_block ? 'fa-chevron-down' : 'fa-chevron-up';
$t_url_page = string_sanitize_url( basename( $_SERVER['SCRIPT_NAME'] ) );
$t_url_params = $_GET;
if( isset( $t_url_params['all'] ) ) {
unset( $t_url_params['all'] );
}
?>
<div id="timeline" class="widget-box widget-color-blue2 <?php echo $t_block_css ?>">
<div class="widget-header widget-header-small">
<h4 class="widget-title lighter">
<i class="ace-icon fa fa-clock-o"></i>
<?php echo lang_get( 'timeline_title' ) ?>
</h4>
<div class="widget-toolbar">
<a data-action="collapse" href="#">
<i class="1 ace-icon fa <?php echo $t_block_icon ?> bigger-125"></i>
</a>
</div>
</div>
<div class="widget-body">
<div class="widget-toolbox">
<div class="btn-toolbar">
<?php
$t_short_date_format = config_get( 'short_date_format' );
echo '  ';
echo '<span class="label label-grey"> ' . date( $t_short_date_format, $t_start_time ) . ' </span>';
echo ' .. ';
echo '<span class="label label-grey"> ' . date( $t_short_date_format, $t_end_time ) . ' </span>';
echo '  ';
echo '<div class="btn-group">';
$t_url_params['days'] = $f_days + 7;
$t_href = $t_url_page . '?' . http_build_query( $t_url_params );
echo ' <a class="btn btn-primary btn-xs btn-white btn-round" href="' . $t_href . '">' . lang_get( 'prev' ) . '</a>';
$t_next_days = ( $f_days - 7 ) > 0 ? $f_days - 7 : 0;
if( $t_next_days != $f_days ) {
$t_url_params['days'] = $t_next_days;
$t_href = $t_url_page . '?' . http_build_query( $t_url_params );
echo ' <a class="btn btn-primary btn-xs btn-white btn-round" href="' . $t_href . '">' . lang_get( 'next' ) . '</a>';
}
echo '</div>';
?>
</div>
</div>
<div class="widget-main no-padding">
<div class="profile-feed">
</div>
</div>
<?php
if( !$f_all && count( $t_events ) > MAX_EVENTS ) {
$t_events = array_slice( $t_events, 0, MAX_EVENTS );
timeline_print_events( $t_events );
echo '<div class="widget-toolbox">';
echo '<div class="btn-toolbar">';
$t_url_params['all'] = 1;
$t_href = $t_url_page . '?' . http_build_query( $t_url_params );
echo '<a class="btn btn-primary btn-sm btn-white btn-round" href="' . $t_href . '">' . lang_get( 'timeline_more' ) . '</a>';
echo '</div>';
echo '</div>';
} else {
timeline_print_events( $t_events );
}
?>
</div>
</div>
|
a1c719313d61b07bbe8700005807b8195fdc32f1
|
https://github.com/mantisbt/mantisbt
|
template.php
|
php
|
<?php must_have_access(); ?>
<script type="text/javascript">
mw.require('options.js');
mw.require('forms.js');
</script>
<script type="text/javascript">
$(document).ready(function () {
mw.options.form('.<?php print $config['module_class'] ?>', function () {
mw.notification.success("<?php _ejs("All changes are saved"); ?>.");
});
});
</script>
<div class="<?php print $config['module_class'] ?>">
<?php $data = get_option('current_template', 'template', 1); ?>
<?php
if (!isset($data['id'])) {
$data['id'] = 0;
}
if (!isset($data['option_value'])) {
$data['option_value'] = 'default';
}
if (!isset($data['option_key'])) {
$data['option_key'] = 'current_template';
}
?>
<script type="text/javascript">
function mw_set_default_template() {
changeTemplateDialog = mw.dialog({
content: '<div id="mw_admin_change_template_modal_content"></div>',
title: 'Change Template',
width: 700,
id: 'mw_admin_change_template_modal'
});
var params = {};
mw.load_module('settings/group/template_install_modal', '#mw_admin_change_template_modal_content', function() {
changeTemplateDialog.center();
}, params);
}
$(document).ready(function () {
$(window).on('templateSelected', function () {
$(".mw-site-theme-selector").find("[name='active_site_template'] option:selected").each(function (index) {
$("#mw_curr_theme_val").val($(this).val());
});
});
});
</script>
<?php
$selected_template = $data['option_value'];
$change_template = false;
if(isset($_GET['template'])){
$change_template = true;
$selected_template = $_GET['template'];
}
$selected_template = xss_clean($selected_template);
?>
<?php if($change_template){ ?>
<div class="alert alert-dismissible alert-primary">
<?php _e("You must click the apply template button to change your template"); ?>
</div>
<?php } ?>
<div class="mw-site-theme-selector">
<input id="mw_curr_theme_val" name="current_template" class="mw_option_field mw-ui-field" type="hidden" option-group="template" value="<?php print $selected_template; ?>" data-id="<?php print $data['id']; ?>"/>
<module type="content/views/layout_selector" show_allow_multiple_template="true" show_save_changes_buttons="true" show_full="true" data-active-site-template="<?php print $selected_template ?>" autoload="1" xxlive_edit_styles_check="1" no-default-name="true"/>
</div>
</div>
|
<?php must_have_access(); ?>
<script type="text/javascript">
mw.require('options.js');
mw.require('forms.js');
</script>
<script type="text/javascript">
$(document).ready(function () {
mw.options.form('.<?php print $config['module_class'] ?>', function () {
mw.notification.success("<?php _ejs("All changes are saved"); ?>.");
});
});
</script>
<div class="<?php print $config['module_class'] ?>">
<?php $data = get_option('current_template', 'template', 1); ?>
<?php
if (!isset($data['id'])) {
$data['id'] = 0;
}
if (!isset($data['option_value'])) {
$data['option_value'] = 'default';
}
if (!isset($data['option_key'])) {
$data['option_key'] = 'current_template';
}
?>
<script type="text/javascript">
function mw_set_default_template() {
changeTemplateDialog = mw.dialog({
content: '<div id="mw_admin_change_template_modal_content"></div>',
title: 'Change Template',
width: 700,
id: 'mw_admin_change_template_modal'
});
var params = {};
mw.load_module('settings/group/template_install_modal', '#mw_admin_change_template_modal_content', function() {
changeTemplateDialog.center();
}, params);
}
$(document).ready(function () {
$(window).on('templateSelected', function () {
$(".mw-site-theme-selector").find("[name='active_site_template'] option:selected").each(function (index) {
$("#mw_curr_theme_val").val($(this).val());
});
});
});
</script>
<?php
$selected_template = $data['option_value'];
$change_template = false;
if(isset($_GET['template'])){
$change_template = true;
$selected_template = e($_GET['template']);
}
$selected_template = xss_clean($selected_template);
?>
<?php if($change_template){ ?>
<div class="alert alert-dismissible alert-primary">
<?php _e("You must click the apply template button to change your template"); ?>
</div>
<?php } ?>
<div class="mw-site-theme-selector">
<input id="mw_curr_theme_val" name="current_template" class="mw_option_field mw-ui-field" type="hidden" option-group="template" value="<?php print $selected_template; ?>" data-id="<?php print $data['id']; ?>"/>
<module type="content/views/layout_selector" show_allow_multiple_template="true" show_save_changes_buttons="true" show_full="true" data-active-site-template="<?php print $selected_template ?>" autoload="1" xxlive_edit_styles_check="1" no-default-name="true"/>
</div>
</div>
|
1a9b904722b35b00653c6ae72dca2969149159b3
|
https://github.com/microweber/microweber
|
manage_filter_edit_page.php
|
php
|
<?php
# MantisBT - A PHP based bugtracking system
# MantisBT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# MantisBT 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 MantisBT. If not, see <http://www.gnu.org/licenses/>.
/**
* Manage filter edit page
*
* @package MantisBT
* @copyright Copyright 2016 MantisBT Team - mantisbt-dev@lists.sourceforge.net
* @link http://www.mantisbt.org
*
* @uses core.php
* @uses access_api.php
* @uses authentication_api.php
* @uses compress_api.php
* @uses config_api.php
* @uses constant_inc.php
* @uses current_user_api.php
* @uses custom_field_api.php
* @uses filter_api.php
* @uses filter_constants_inc.php
* @uses gpc_api.php
* @uses helper_api.php
* @uses html_api.php
* @uses lang_api.php
* @uses print_api.php
* @uses string_api.php
* @uses version_api.php
*/
require_once( 'core.php' );
require_api( 'access_api.php' );
require_api( 'authentication_api.php' );
require_api( 'compress_api.php' );
require_api( 'config_api.php' );
require_api( 'constant_inc.php' );
require_api( 'current_user_api.php' );
require_api( 'custom_field_api.php' );
require_api( 'filter_api.php' );
require_api( 'filter_constants_inc.php' );
require_api( 'gpc_api.php' );
require_api( 'helper_api.php' );
require_api( 'html_api.php' );
require_api( 'lang_api.php' );
require_api( 'print_api.php' );
require_api( 'string_api.php' );
require_api( 'version_api.php' );
auth_ensure_user_authenticated();
layout_page_header( lang_get('manage_filter_edit_page_title' ) );
layout_page_begin( 'manage_filter_edit_page.php' );
$f_filter_id = gpc_get_int( 'filter_id', null );
if( null === $f_filter_id ) {
error_parameters( 'FILTER_ID' );
trigger_error( ERROR_EMPTY_FIELD, ERROR );
}
$t_filter = filter_get( $f_filter_id, null );
if( null === $t_filter ) {
access_denied();
}
$f_view_type = gpc_get_string( 'view_type', $t_filter['_view_type'] );
$t_filter['_view_type'] = $f_view_type;
$t_filter = filter_ensure_valid_filter( $t_filter );
$t_action = 'manage_filter_edit_update.php';
$t_current_project_id = helper_get_current_project();
$t_filter_project_id = filter_get_field( $f_filter_id, 'project_id' );
?>
<div class="col-md-12 col-xs-12">
<div class="space-10"></div>
<form method="post" name="filters" id="filters_form_open" action="<?php echo $t_action; ?>">
<input type="hidden" name="filter_id" value="<?php echo $f_filter_id ?>" >
<input type="hidden" name="view_type" value="<?php echo $t_filter['_view_type'] ?>" >
<?php echo form_security_field( 'manage_filter_edit_update' ) ?>
<div class="widget-box widget-color-blue2">
<div class="widget-header widget-header-small">
<h4 class="widget-title lighter">
<i class="ace-icon fa fa-filter"></i>
<?php echo lang_get('edit_filter') ?>
</h4>
<div class="widget-toolbar">
<div class="widget-menu">
<a href="#" data-action="settings" data-toggle="dropdown">
<i class="ace-icon fa fa-bars bigger-125"></i>
</a>
<ul class="dropdown-menu dropdown-menu-right dropdown-yellow dropdown-caret dropdown-closer">
<?php
$t_url = 'manage_filter_edit_page.php?filter_id=' . $f_filter_id . '&view_type=';
filter_print_view_type_toggle( $t_url, $t_filter['_view_type'] );
?>
</ul>
</div>
</div>
</div>
<div class="widget-body">
<div class="widget-main no-padding">
<div class="widget-toolbox padding-8 clearfix">
<div class="btn-toolbar pull-left">
<div class="form-inline">
<label>
<?php echo lang_get( 'query_name' ) ?>
<input type="text" size="25" name="filter_name" maxlength="64" value="<?php echo filter_get_field( $f_filter_id, 'name' ) ?>">
</label>
</div>
</div>
</div>
<div class="table-responsive">
<?php
$t_for_screen = true;
$t_static = gpc_get_bool( 'static', false );
filter_form_draw_inputs( $t_filter, $t_for_screen, $t_static );
?>
</div>
<div class="widget-toolbox padding-8 clearfix">
<div class="btn-toolbar pull-left">
<div class="form-inline">
<label><?php echo lang_get( 'search' ) ?>
<input type="text" id="filter-search-txt" class="input-sm" size="16"
name="<?php echo FILTER_PROPERTY_SEARCH ?>"
value="<?php echo string_attribute( $t_filter[FILTER_PROPERTY_SEARCH] ) ?>">
</label>
</div>
</div>
</div>
<div class="table-responsive">
<table class="table table-bordered table-condensed table-striped">
<?php
if( access_has_project_level( config_get( 'stored_query_create_shared_threshold' ) ) ) {
?>
<tr>
<td class="category">
<?php echo lang_get( 'view_status' ) ?>
</td>
<td>
<label>
<input type="radio" class="ace" name="is_public" value="1" <?php check_checked( (bool)filter_get_field( $f_filter_id, 'is_public' ), true ) ?> />
<span class="lbl padding-6"><?php echo lang_get( 'public' ) ?></span>
</label>
    
<label>
<input type="radio" class="ace" name="is_public" value="0" <?php check_checked( (bool)filter_get_field( $f_filter_id, 'is_public' ), false ) ?> />
<span class="lbl padding-6"><?php echo lang_get( 'private' ) ?></span>
</label>
</td>
</tr>
<?php } ?>
<tr>
<td class="category">
<?php echo lang_get( 'email_project' ) ?>
</td>
<td>
<label class="inline">
<input type="radio" class="ace input-sm" name="filter_project_id" value="<?php echo ALL_PROJECTS ?>" <?php check_checked( ALL_PROJECTS == $t_filter_project_id ) ?>>
<span class="lbl padding-6"><?php echo lang_get( 'all_projects' ) ?></span>
</label>
<br>
<?php if( ALL_PROJECTS != $t_filter_project_id ) { ?>
<label>
<input type="radio" class="ace input-sm" name="filter_project_id" value="<?php echo $t_filter_project_id ?>" <?php check_checked( ALL_PROJECTS != $t_filter_project_id ) ?>>
<span class="lbl padding-6"><?php echo lang_get( 'stored_project' ) . ' (' . project_get_name( $t_filter_project_id ) . ')' ?></span>
</label>
<br>
<?php } ?>
<?php if( $t_filter_project_id != $t_current_project_id ) { ?>
<label>
<input type="radio" class="ace input-sm" name="filter_project_id" value="<?php echo $t_current_project_id ?>">
<span class="lbl padding-6"><?php echo lang_get( 'current_project' ) . ' (' . project_get_name( $t_current_project_id ) . ')' ?></span>
</label>
<?php } ?>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="widget-toolbox padding-8 clearfix">
<input type="submit" class="btn btn-primary btn-white btn-round" value="<?php echo lang_get( 'update_filter' ) ?>" />
</div>
</div>
</form>
</div>
<?php
layout_page_end();
|
<?php
# MantisBT - A PHP based bugtracking system
# MantisBT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# MantisBT 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 MantisBT. If not, see <http://www.gnu.org/licenses/>.
/**
* Manage filter edit page
*
* @package MantisBT
* @copyright Copyright 2016 MantisBT Team - mantisbt-dev@lists.sourceforge.net
* @link http://www.mantisbt.org
*
* @uses core.php
* @uses access_api.php
* @uses authentication_api.php
* @uses compress_api.php
* @uses config_api.php
* @uses constant_inc.php
* @uses current_user_api.php
* @uses custom_field_api.php
* @uses filter_api.php
* @uses filter_constants_inc.php
* @uses gpc_api.php
* @uses helper_api.php
* @uses html_api.php
* @uses lang_api.php
* @uses print_api.php
* @uses string_api.php
* @uses version_api.php
*/
require_once( 'core.php' );
require_api( 'access_api.php' );
require_api( 'authentication_api.php' );
require_api( 'compress_api.php' );
require_api( 'config_api.php' );
require_api( 'constant_inc.php' );
require_api( 'current_user_api.php' );
require_api( 'custom_field_api.php' );
require_api( 'filter_api.php' );
require_api( 'filter_constants_inc.php' );
require_api( 'gpc_api.php' );
require_api( 'helper_api.php' );
require_api( 'html_api.php' );
require_api( 'lang_api.php' );
require_api( 'print_api.php' );
require_api( 'string_api.php' );
require_api( 'version_api.php' );
auth_ensure_user_authenticated();
layout_page_header( lang_get('manage_filter_edit_page_title' ) );
layout_page_begin( 'manage_filter_edit_page.php' );
$f_filter_id = gpc_get_int( 'filter_id', null );
if( null === $f_filter_id ) {
error_parameters( 'FILTER_ID' );
trigger_error( ERROR_EMPTY_FIELD, ERROR );
}
$t_filter = filter_get( $f_filter_id, null );
if( null === $t_filter ) {
access_denied();
}
$f_view_type = gpc_get_string( 'view_type', $t_filter['_view_type'] );
$t_filter['_view_type'] = $f_view_type;
$t_filter = filter_ensure_valid_filter( $t_filter );
$t_action = 'manage_filter_edit_update.php';
$t_current_project_id = helper_get_current_project();
$t_filter_project_id = filter_get_field( $f_filter_id, 'project_id' );
?>
<div class="col-md-12 col-xs-12">
<div class="space-10"></div>
<form method="post" name="filters" id="filters_form_open" action="<?php echo $t_action; ?>">
<input type="hidden" name="filter_id" value="<?php echo $f_filter_id ?>" >
<input type="hidden" name="view_type" value="<?php echo $t_filter['_view_type'] ?>" >
<?php echo form_security_field( 'manage_filter_edit_update' ) ?>
<div class="widget-box widget-color-blue2">
<div class="widget-header widget-header-small">
<h4 class="widget-title lighter">
<i class="ace-icon fa fa-filter"></i>
<?php echo lang_get('edit_filter') ?>
</h4>
<div class="widget-toolbar">
<div class="widget-menu">
<a href="#" data-action="settings" data-toggle="dropdown">
<i class="ace-icon fa fa-bars bigger-125"></i>
</a>
<ul class="dropdown-menu dropdown-menu-right dropdown-yellow dropdown-caret dropdown-closer">
<?php
$t_url = 'manage_filter_edit_page.php?filter_id=' . $f_filter_id . '&view_type=';
filter_print_view_type_toggle( $t_url, $t_filter['_view_type'] );
?>
</ul>
</div>
</div>
</div>
<div class="widget-body">
<div class="widget-main no-padding">
<div class="widget-toolbox padding-8 clearfix">
<div class="btn-toolbar pull-left">
<div class="form-inline">
<label>
<?php echo lang_get( 'query_name' ) ?>
<input type="text" size="25" name="filter_name" maxlength="64" value="<?php echo string_display_line( filter_get_field( $f_filter_id, 'name' ) ) ?>">
</label>
</div>
</div>
</div>
<div class="table-responsive">
<?php
$t_for_screen = true;
$t_static = gpc_get_bool( 'static', false );
filter_form_draw_inputs( $t_filter, $t_for_screen, $t_static );
?>
</div>
<div class="widget-toolbox padding-8 clearfix">
<div class="btn-toolbar pull-left">
<div class="form-inline">
<label><?php echo lang_get( 'search' ) ?>
<input type="text" id="filter-search-txt" class="input-sm" size="16"
name="<?php echo FILTER_PROPERTY_SEARCH ?>"
value="<?php echo string_attribute( $t_filter[FILTER_PROPERTY_SEARCH] ) ?>">
</label>
</div>
</div>
</div>
<div class="table-responsive">
<table class="table table-bordered table-condensed table-striped">
<?php
if( access_has_project_level( config_get( 'stored_query_create_shared_threshold' ) ) ) {
?>
<tr>
<td class="category">
<?php echo lang_get( 'view_status' ) ?>
</td>
<td>
<label>
<input type="radio" class="ace" name="is_public" value="1" <?php check_checked( (bool)filter_get_field( $f_filter_id, 'is_public' ), true ) ?> />
<span class="lbl padding-6"><?php echo lang_get( 'public' ) ?></span>
</label>
    
<label>
<input type="radio" class="ace" name="is_public" value="0" <?php check_checked( (bool)filter_get_field( $f_filter_id, 'is_public' ), false ) ?> />
<span class="lbl padding-6"><?php echo lang_get( 'private' ) ?></span>
</label>
</td>
</tr>
<?php } ?>
<tr>
<td class="category">
<?php echo lang_get( 'email_project' ) ?>
</td>
<td>
<label class="inline">
<input type="radio" class="ace input-sm" name="filter_project_id" value="<?php echo ALL_PROJECTS ?>" <?php check_checked( ALL_PROJECTS == $t_filter_project_id ) ?>>
<span class="lbl padding-6"><?php echo lang_get( 'all_projects' ) ?></span>
</label>
<br>
<?php if( ALL_PROJECTS != $t_filter_project_id ) { ?>
<label>
<input type="radio" class="ace input-sm" name="filter_project_id" value="<?php echo $t_filter_project_id ?>" <?php check_checked( ALL_PROJECTS != $t_filter_project_id ) ?>>
<span class="lbl padding-6"><?php echo lang_get( 'stored_project' ) . ' (' . project_get_name( $t_filter_project_id ) . ')' ?></span>
</label>
<br>
<?php } ?>
<?php if( $t_filter_project_id != $t_current_project_id ) { ?>
<label>
<input type="radio" class="ace input-sm" name="filter_project_id" value="<?php echo $t_current_project_id ?>">
<span class="lbl padding-6"><?php echo lang_get( 'current_project' ) . ' (' . project_get_name( $t_current_project_id ) . ')' ?></span>
</label>
<?php } ?>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="widget-toolbox padding-8 clearfix">
<input type="submit" class="btn btn-primary btn-white btn-round" value="<?php echo lang_get( 'update_filter' ) ?>" />
</div>
</div>
</form>
</div>
<?php
layout_page_end();
|
8b5fa243dbf04344a55fe880135ec149fc1f439f
|
https://github.com/mantisbt/mantisbt
|
backend_header.php
|
php
|
<?php
/**
* Local variables.
*
* @var string $active_menu
* @var string $company_logo
*/
?>
<nav id="header" class="navbar navbar-expand-md navbar-dark">
<div id="header-logo" class="navbar-brand">
<img src="<?= base_url('assets/img/logo.png') ?>" alt="logo">
<h6>EASY!APPOINTMENTS</h6>
<small>Online Appointment Scheduler</small>
</div>
<button type="button" class="navbar-toggler" data-bs-toggle="collapse" data-bs-target="#header-menu">
<span class="sr-only">Toggle navigation</span>
<span class="navbar-toggler-icon"></span>
</button>
<div id="header-menu" class="collapse navbar-collapse flex-row-reverse px-2">
<ul class="navbar-nav">
<?php $hidden = can('view', PRIV_APPOINTMENTS) ? '' : 'd-none' ?>
<?php $active = $active_menu == PRIV_APPOINTMENTS ? 'active' : '' ?>
<li class="nav-item <?= $active . $hidden ?>">
<a href="<?= site_url('calendar' . (vars('calendar_view') === CALENDAR_VIEW_TABLE ? '?view=table' : '')) ?>" class="nav-link"
data-tippy-content="<?= lang('manage_appointment_record_hint') ?>">
<i class="fas fa-calendar-alt me-2"></i>
<?= lang('calendar') ?>
</a>
</li>
<?php $hidden = can('view', PRIV_CUSTOMERS) ? '' : 'd-none' ?>
<?php $active = $active_menu == PRIV_CUSTOMERS ? 'active' : '' ?>
<li class="nav-item <?= $active . $hidden ?>">
<a href="<?= site_url('customers') ?>" class="nav-link"
data-tippy-content="<?= lang('manage_customers_hint') ?>">
<i class="fas fa-user-friends me-2"></i>
<?= lang('customers') ?>
</a>
</li>
<?php $hidden = can('view', PRIV_SERVICES) ? '' : 'd-none' ?>
<?php $active = $active_menu == PRIV_SERVICES ? 'active' : '' ?>
<li class="nav-item dropdown <?= $active . $hidden ?>">
<a class="nav-link dropdown-toggle" href="#" data-bs-toggle="dropdown"
data-tippy-content="<?= lang('manage_services_hint') ?>">
<i class="fas fa-business-time me-2"></i>
<?= lang('services') ?>
</a>
<div class="dropdown-menu dropdown-menu-end">
<a class="dropdown-item" href="<?= site_url('services') ?>">
<?= lang('services') ?>
</a>
<a class="dropdown-item" href="<?= site_url('categories') ?>">
<?= lang('categories') ?>
</a>
</div>
</li>
<?php $hidden = can('view', PRIV_USERS) ? '' : 'd-none' ?>
<?php $active = $active_menu == PRIV_USERS ? 'active' : '' ?>
<li class="nav-item dropdown <?= $active . $hidden ?>">
<a class="nav-link dropdown-toggle" href="#" data-bs-toggle="dropdown"
data-tippy-content="<?= lang('manage_users_hint') ?>">
<i class="fas fa-users me-2"></i>
<?= lang('users') ?>
</a>
<div class="dropdown-menu dropdown-menu-end">
<a class="dropdown-item" href="<?= site_url('providers') ?>">
<?= lang('providers') ?>
</a>
<a class="dropdown-item" href="<?= site_url('secretaries') ?>">
<?= lang('secretaries') ?>
</a>
<a class="dropdown-item" href="<?= site_url('admins') ?>">
<?= lang('admins') ?>
</a>
</div>
</li>
<?php $hidden = can('view', PRIV_SYSTEM_SETTINGS) || can('view', PRIV_USER_SETTINGS) ? '' : 'd-none' ?>
<?php $active = $active_menu == PRIV_SYSTEM_SETTINGS ? 'active' : '' ?>
<li class="nav-item dropdown <?= $active . $hidden ?>">
<a class="nav-link dropdown-toggle" href="#" data-bs-toggle="dropdown"
data-tippy-content="<?= lang('settings_hint') ?>">
<i class="fas fa-user me-2"></i>
<?= vars('user_display_name') ?>
</a>
<div class="dropdown-menu dropdown-menu-end">
<?php if (can('view', PRIV_SYSTEM_SETTINGS)): ?>
<a class="dropdown-item" href="<?= site_url('general_settings') ?>">
<?= lang('settings') ?>
</a>
<?php endif ?>
<a class="dropdown-item" href="<?= site_url('account') ?>">
<?= lang('account') ?>
</a>
<a class="dropdown-item" href="<?= site_url('about') ?>">
<?= lang('about') ?>
</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="<?= site_url('logout') ?>">
<?= lang('log_out') ?>
</a>
</div>
</li>
</ul>
</div>
</nav>
<div id="notification" style="display: none;"></div>
<div id="loading" style="display: none;">
<div class="any-element animation is-loading">
</div>
</div>
|
<?php
/**
* Local variables.
*
* @var string $active_menu
* @var string $company_logo
*/
?>
<nav id="header" class="navbar navbar-expand-md navbar-dark">
<div id="header-logo" class="navbar-brand">
<img src="<?= base_url('assets/img/logo.png') ?>" alt="logo">
<h6>EASY!APPOINTMENTS</h6>
<small>Online Appointment Scheduler</small>
</div>
<button type="button" class="navbar-toggler" data-bs-toggle="collapse" data-bs-target="#header-menu">
<span class="sr-only">Toggle navigation</span>
<span class="navbar-toggler-icon"></span>
</button>
<div id="header-menu" class="collapse navbar-collapse flex-row-reverse px-2">
<ul class="navbar-nav">
<?php $hidden = can('view', PRIV_APPOINTMENTS) ? '' : 'd-none' ?>
<?php $active = $active_menu == PRIV_APPOINTMENTS ? 'active' : '' ?>
<li class="nav-item <?= $active . $hidden ?>">
<a href="<?= site_url('calendar' . (vars('calendar_view') === CALENDAR_VIEW_TABLE ? '?view=table' : '')) ?>" class="nav-link"
data-tippy-content="<?= lang('manage_appointment_record_hint') ?>">
<i class="fas fa-calendar-alt me-2"></i>
<?= lang('calendar') ?>
</a>
</li>
<?php $hidden = can('view', PRIV_CUSTOMERS) ? '' : 'd-none' ?>
<?php $active = $active_menu == PRIV_CUSTOMERS ? 'active' : '' ?>
<li class="nav-item <?= $active . $hidden ?>">
<a href="<?= site_url('customers') ?>" class="nav-link"
data-tippy-content="<?= lang('manage_customers_hint') ?>">
<i class="fas fa-user-friends me-2"></i>
<?= lang('customers') ?>
</a>
</li>
<?php $hidden = can('view', PRIV_SERVICES) ? '' : 'd-none' ?>
<?php $active = $active_menu == PRIV_SERVICES ? 'active' : '' ?>
<li class="nav-item dropdown <?= $active . $hidden ?>">
<a class="nav-link dropdown-toggle" href="#" data-bs-toggle="dropdown"
data-tippy-content="<?= lang('manage_services_hint') ?>">
<i class="fas fa-business-time me-2"></i>
<?= lang('services') ?>
</a>
<div class="dropdown-menu dropdown-menu-end">
<a class="dropdown-item" href="<?= site_url('services') ?>">
<?= lang('services') ?>
</a>
<a class="dropdown-item" href="<?= site_url('categories') ?>">
<?= lang('categories') ?>
</a>
</div>
</li>
<?php $hidden = can('view', PRIV_USERS) ? '' : 'd-none' ?>
<?php $active = $active_menu == PRIV_USERS ? 'active' : '' ?>
<li class="nav-item dropdown <?= $active . $hidden ?>">
<a class="nav-link dropdown-toggle" href="#" data-bs-toggle="dropdown"
data-tippy-content="<?= lang('manage_users_hint') ?>">
<i class="fas fa-users me-2"></i>
<?= lang('users') ?>
</a>
<div class="dropdown-menu dropdown-menu-end">
<a class="dropdown-item" href="<?= site_url('providers') ?>">
<?= lang('providers') ?>
</a>
<a class="dropdown-item" href="<?= site_url('secretaries') ?>">
<?= lang('secretaries') ?>
</a>
<a class="dropdown-item" href="<?= site_url('admins') ?>">
<?= lang('admins') ?>
</a>
</div>
</li>
<?php $hidden = can('view', PRIV_SYSTEM_SETTINGS) || can('view', PRIV_USER_SETTINGS) ? '' : 'd-none' ?>
<?php $active = $active_menu == PRIV_SYSTEM_SETTINGS ? 'active' : '' ?>
<li class="nav-item dropdown <?= $active . $hidden ?>">
<a class="nav-link dropdown-toggle" href="#" data-bs-toggle="dropdown"
data-tippy-content="<?= lang('settings_hint') ?>">
<i class="fas fa-user me-2"></i>
<?= e(vars('user_display_name')) ?>
</a>
<div class="dropdown-menu dropdown-menu-end">
<?php if (can('view', PRIV_SYSTEM_SETTINGS)): ?>
<a class="dropdown-item" href="<?= site_url('general_settings') ?>">
<?= lang('settings') ?>
</a>
<?php endif ?>
<a class="dropdown-item" href="<?= site_url('account') ?>">
<?= lang('account') ?>
</a>
<a class="dropdown-item" href="<?= site_url('about') ?>">
<?= lang('about') ?>
</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="<?= site_url('logout') ?>">
<?= lang('log_out') ?>
</a>
</div>
</li>
</ul>
</div>
</nav>
<div id="notification" style="display: none;"></div>
<div id="loading" style="display: none;">
<div class="any-element animation is-loading">
</div>
</div>
|
bddc5cbeb7ff237a72943b304dcb01c653781767
|
https://github.com/alextselegidis/easyappointments
|
db_central_columns.php
|
php
|
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Central Columns view/edit
*
* @package PhpMyAdmin
*/
/**
* Gets some core libraries
*/
require_once 'libraries/common.inc.php';
require_once 'libraries/central_columns.lib.php';
if (isset($_POST['edit_save']) || isset($_POST['add_new_column'])) {
$col_name = $_POST['col_name'];
if (isset($_POST['edit_save'])) {
$orig_col_name = $_POST['orig_col_name'];
}
$col_default = $_POST['col_default'];
if ($col_default == 'NONE' && $_POST['col_default_sel'] != 'USER_DEFINED') {
$col_default = "";
}
$col_extra = isset($_POST['col_extra']) ? $_POST['col_extra'] : '';
$col_isNull = isset($_POST['col_isNull'])?1:0;
$col_length = $_POST['col_length'];
$col_attribute = $_POST['col_attribute'];
$col_type = $_POST['col_type'];
$collation = $_POST['collation'];
if (isset($orig_col_name) && $orig_col_name) {
echo PMA_updateOneColumn(
$db, $orig_col_name, $col_name, $col_type, $col_attribute,
$col_length, $col_isNull, $collation, $col_extra, $col_default
);
exit;
} else {
$tmp_msg = PMA_updateOneColumn(
$db, "", $col_name, $col_type, $col_attribute,
$col_length, $col_isNull, $collation, $col_extra, $col_default
);
}
}
if (isset($_POST['populateColumns'])) {
$selected_tbl = $_POST['selectedTable'];
echo PMA_getHTMLforColumnDropdown($db, $selected_tbl);
exit;
}
if (isset($_POST['getColumnList'])) {
echo PMA_getCentralColumnsListRaw($db, $_POST['cur_table']);
exit;
}
if (isset($_POST['add_column'])) {
$selected_col = array();
$selected_tbl = $_POST['table-select'];
$selected_col[] = $_POST['column-select'];
$tmp_msg = PMA_syncUniqueColumns($selected_col, false, $selected_tbl);
}
$response = PMA_Response::getInstance();
$header = $response->getHeader();
$scripts = $header->getScripts();
$scripts->addFile('jquery/jquery.uitablefilter.js');
$scripts->addFile('jquery/jquery.tablesorter.js');
$scripts->addFile('db_central_columns.js');
$cfgCentralColumns = PMA_centralColumnsGetParams();
$pmadb = $cfgCentralColumns['db'];
$pmatable = $cfgCentralColumns['table'];
$max_rows = $GLOBALS['cfg']['MaxRows'];
if (isset($_REQUEST['edit_central_columns_page'])) {
$selected_fld = $_REQUEST['selected_fld'];
$selected_db = $_REQUEST['db'];
$edit_central_column_page = PMA_getHTMLforEditingPage(
$selected_fld, $selected_db
);
$response->addHTML($edit_central_column_page);
exit;
}
if (isset($_POST['multi_edit_central_column_save'])) {
$message = PMA_updateMultipleColumn();
if (!is_bool($message)) {
$response->isSuccess(false);
$response->addJSON('message', $message);
}
}
if (isset($_POST['delete_save'])) {
$col_name = array();
parse_str($_POST['col_name'], $col_name);
$tmp_msg = PMA_deleteColumnsFromList($col_name['selected_fld'], false);
}
if (isset($_REQUEST['total_rows']) && $_REQUEST['total_rows']) {
$total_rows = $_REQUEST['total_rows'];
} else {
$total_rows = PMA_getCentralColumnsCount($db);
}
if (isset($_REQUEST['pos'])) {
$pos = $_REQUEST['pos'];
} else {
$pos = 0;
}
$addNewColumn = PMA_getHTMLforAddNewColumn($db);
$response->addHTML($addNewColumn);
if ($total_rows <= 0) {
$response->addHTML(
'<fieldset>' . __(
'The central list of columns for the current database is empty.'
) . '</fieldset>'
);
$columnAdd = PMA_getHTMLforAddCentralColumn($total_rows, $pos, $db);
$response->addHTML($columnAdd);
exit;
}
$table_navigation_html = PMA_getHTMLforTableNavigation($total_rows, $pos, $db);
$response->addHTML($table_navigation_html);
$columnAdd = PMA_getHTMLforAddCentralColumn($total_rows, $pos, $db);
$response->addHTML($columnAdd);
$deleteRowForm = '<form method="post" id="del_form" action="db_central_columns.php">'
. PMA_URL_getHiddenInputs(
$db
)
. '<input id="del_col_name" type="hidden" name="col_name" value="">'
. '<input type="hidden" name="pos" value="' . $pos . '">'
. '<input type="hidden" name="delete_save" value="delete"></form>';
$response->addHTML($deleteRowForm);
$table_struct = '<div id="tableslistcontainer">'
. '<form name="tableslistcontainer">'
. '<table id="table_columns" class="tablesorter" '
. 'style="min-width:100%" class="data">';
$response->addHTML($table_struct);
$tableheader = PMA_getCentralColumnsTableHeader(
'column_heading', __('Click to sort.'), 2
);
$response->addHTML($tableheader);
$result = PMA_getColumnsList($db, $pos, $max_rows);
$odd_row = true;
$row_num = 0;
foreach ($result as $row) {
$tableHtmlRow = PMA_getHTMLforCentralColumnsTableRow(
$row, $odd_row, $row_num, $db
);
$response->addHTML($tableHtmlRow);
$odd_row = !$odd_row;
$row_num++;
}
$response->addHTML('</table>');
$tablefooter = PMA_getCentralColumnsTableFooter($pmaThemeImage, $text_dir);
$response->addHTML($tablefooter);
$response->addHTML('</form></div>');
$message = PMA_Message::success(
sprintf(__('Showing rows %1$s - %2$s.'), ($pos + 1), ($pos + count($result)))
);
if (isset($tmp_msg) && $tmp_msg !== true) {
$message = $tmp_msg;
}
|
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Central Columns view/edit
*
* @package PhpMyAdmin
*/
/**
* Gets some core libraries
*/
require_once 'libraries/common.inc.php';
require_once 'libraries/central_columns.lib.php';
if (isset($_POST['edit_save']) || isset($_POST['add_new_column'])) {
$col_name = $_POST['col_name'];
if (isset($_POST['edit_save'])) {
$orig_col_name = $_POST['orig_col_name'];
}
$col_default = $_POST['col_default'];
if ($col_default == 'NONE' && $_POST['col_default_sel'] != 'USER_DEFINED') {
$col_default = "";
}
$col_extra = isset($_POST['col_extra']) ? $_POST['col_extra'] : '';
$col_isNull = isset($_POST['col_isNull'])?1:0;
$col_length = $_POST['col_length'];
$col_attribute = $_POST['col_attribute'];
$col_type = $_POST['col_type'];
$collation = $_POST['collation'];
if (isset($orig_col_name) && $orig_col_name) {
echo PMA_updateOneColumn(
$db, $orig_col_name, $col_name, $col_type, $col_attribute,
$col_length, $col_isNull, $collation, $col_extra, $col_default
);
exit;
} else {
$tmp_msg = PMA_updateOneColumn(
$db, "", $col_name, $col_type, $col_attribute,
$col_length, $col_isNull, $collation, $col_extra, $col_default
);
}
}
if (isset($_POST['populateColumns'])) {
$selected_tbl = $_POST['selectedTable'];
echo PMA_getHTMLforColumnDropdown($db, $selected_tbl);
exit;
}
if (isset($_POST['getColumnList'])) {
echo PMA_getCentralColumnsListRaw($db, $_POST['cur_table']);
exit;
}
if (isset($_POST['add_column'])) {
$selected_col = array();
$selected_tbl = $_POST['table-select'];
$selected_col[] = $_POST['column-select'];
$tmp_msg = PMA_syncUniqueColumns($selected_col, false, $selected_tbl);
}
$response = PMA_Response::getInstance();
$header = $response->getHeader();
$scripts = $header->getScripts();
$scripts->addFile('jquery/jquery.uitablefilter.js');
$scripts->addFile('jquery/jquery.tablesorter.js');
$scripts->addFile('db_central_columns.js');
$cfgCentralColumns = PMA_centralColumnsGetParams();
$pmadb = $cfgCentralColumns['db'];
$pmatable = $cfgCentralColumns['table'];
$max_rows = $GLOBALS['cfg']['MaxRows'];
if (isset($_REQUEST['edit_central_columns_page'])) {
$selected_fld = $_REQUEST['selected_fld'];
$selected_db = $_REQUEST['db'];
$edit_central_column_page = PMA_getHTMLforEditingPage(
$selected_fld, $selected_db
);
$response->addHTML($edit_central_column_page);
exit;
}
if (isset($_POST['multi_edit_central_column_save'])) {
$message = PMA_updateMultipleColumn();
if (!is_bool($message)) {
$response->isSuccess(false);
$response->addJSON('message', $message);
}
}
if (isset($_POST['delete_save'])) {
$col_name = array();
parse_str($_POST['col_name'], $col_name);
$tmp_msg = PMA_deleteColumnsFromList($col_name['selected_fld'], false);
}
if (isset($_REQUEST['total_rows']) && $_REQUEST['total_rows']) {
$total_rows = $_REQUEST['total_rows'];
} else {
$total_rows = PMA_getCentralColumnsCount($db);
}
if (PMA_isValid($_REQUEST['pos'], 'integer')) {
$pos = $_REQUEST['pos'];
} else {
$pos = 0;
}
$addNewColumn = PMA_getHTMLforAddNewColumn($db);
$response->addHTML($addNewColumn);
if ($total_rows <= 0) {
$response->addHTML(
'<fieldset>' . __(
'The central list of columns for the current database is empty.'
) . '</fieldset>'
);
$columnAdd = PMA_getHTMLforAddCentralColumn($total_rows, $pos, $db);
$response->addHTML($columnAdd);
exit;
}
$table_navigation_html = PMA_getHTMLforTableNavigation($total_rows, $pos, $db);
$response->addHTML($table_navigation_html);
$columnAdd = PMA_getHTMLforAddCentralColumn($total_rows, $pos, $db);
$response->addHTML($columnAdd);
$deleteRowForm = '<form method="post" id="del_form" action="db_central_columns.php">'
. PMA_URL_getHiddenInputs(
$db
)
. '<input id="del_col_name" type="hidden" name="col_name" value="">'
. '<input type="hidden" name="pos" value="' . $pos . '">'
. '<input type="hidden" name="delete_save" value="delete"></form>';
$response->addHTML($deleteRowForm);
$table_struct = '<div id="tableslistcontainer">'
. '<form name="tableslistcontainer">'
. '<table id="table_columns" class="tablesorter" '
. 'style="min-width:100%" class="data">';
$response->addHTML($table_struct);
$tableheader = PMA_getCentralColumnsTableHeader(
'column_heading', __('Click to sort.'), 2
);
$response->addHTML($tableheader);
$result = PMA_getColumnsList($db, $pos, $max_rows);
$odd_row = true;
$row_num = 0;
foreach ($result as $row) {
$tableHtmlRow = PMA_getHTMLforCentralColumnsTableRow(
$row, $odd_row, $row_num, $db
);
$response->addHTML($tableHtmlRow);
$odd_row = !$odd_row;
$row_num++;
}
$response->addHTML('</table>');
$tablefooter = PMA_getCentralColumnsTableFooter($pmaThemeImage, $text_dir);
$response->addHTML($tablefooter);
$response->addHTML('</form></div>');
$message = PMA_Message::success(
sprintf(__('Showing rows %1$s - %2$s.'), ($pos + 1), ($pos + count($result)))
);
if (isset($tmp_msg) && $tmp_msg !== true) {
$message = $tmp_msg;
}
|
cc55f44a4a90147a007dee1aefa1cb529e23798b
|
https://github.com/phpmyadmin/phpmyadmin
|
common.inc.php
|
php
|
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Loads libraries/common.inc.php and preforms some additional actions
*
* @package PhpMyAdmin-Setup
*/
/**
* Do not include full common.
* @ignore
*/
define('PMA_MINIMUM_COMMON', true);
define('PMA_SETUP', true);
chdir('..');
if (!file_exists('./libraries/common.inc.php')) {
PMA_fatalError('Bad invocation!');
}
require_once './libraries/common.inc.php';
require_once './libraries/Util.class.php';
require_once './libraries/config/config_functions.lib.php';
require_once './libraries/config/messages.inc.php';
require_once './libraries/config/ConfigFile.class.php';
require_once './libraries/url_generating.lib.php';
require_once './libraries/user_preferences.lib.php';
// use default error handler
restore_error_handler();
// Save current language in a cookie, required since we use PMA_MINIMUM_COMMON
$GLOBALS['PMA_Config']->setCookie('pma_lang', $GLOBALS['lang']);
$GLOBALS['ConfigFile'] = new ConfigFile();
$GLOBALS['ConfigFile']->setPersistKeys(
array(
'DefaultLang',
'ServerDefault',
'UploadDir',
'SaveDir',
'Servers/1/verbose',
'Servers/1/host',
'Servers/1/port',
'Servers/1/socket',
'Servers/1/connect_type',
'Servers/1/auth_type',
'Servers/1/user',
'Servers/1/password'
)
);
// allows for redirection even after sending some data
ob_start();
|
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Loads libraries/common.inc.php and preforms some additional actions
*
* @package PhpMyAdmin-Setup
*/
/**
* Do not include full common.
* @ignore
*/
define('PMA_MINIMUM_COMMON', true);
define('PMA_SETUP', true);
chdir('..');
if (!file_exists('./libraries/common.inc.php')) {
die('Bad invocation!');
}
require_once './libraries/common.inc.php';
require_once './libraries/Util.class.php';
require_once './libraries/config/config_functions.lib.php';
require_once './libraries/config/messages.inc.php';
require_once './libraries/config/ConfigFile.class.php';
require_once './libraries/url_generating.lib.php';
require_once './libraries/user_preferences.lib.php';
// use default error handler
restore_error_handler();
// Save current language in a cookie, required since we use PMA_MINIMUM_COMMON
$GLOBALS['PMA_Config']->setCookie('pma_lang', $GLOBALS['lang']);
$GLOBALS['ConfigFile'] = new ConfigFile();
$GLOBALS['ConfigFile']->setPersistKeys(
array(
'DefaultLang',
'ServerDefault',
'UploadDir',
'SaveDir',
'Servers/1/verbose',
'Servers/1/host',
'Servers/1/port',
'Servers/1/socket',
'Servers/1/connect_type',
'Servers/1/auth_type',
'Servers/1/user',
'Servers/1/password'
)
);
// allows for redirection even after sending some data
ob_start();
|
447c88f4884fe30a25d38c331c31d820a19f8c93
|
https://github.com/phpmyadmin/phpmyadmin
|
proj_doc_edit_page.php
|
php
|
<?php
# MantisBT - A PHP based bugtracking system
# MantisBT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# MantisBT 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 MantisBT. If not, see <http://www.gnu.org/licenses/>.
/**
* Edit Project Documentation
*
* @package MantisBT
* @copyright Copyright 2000 - 2002 Kenzaburo Ito - kenito@300baud.org
* @copyright Copyright 2002 MantisBT Team - mantisbt-dev@lists.sourceforge.net
* @link http://www.mantisbt.org
*
* @uses core.php
* @uses access_api.php
* @uses config_api.php
* @uses database_api.php
* @uses file_api.php
* @uses form_api.php
* @uses gpc_api.php
* @uses html_api.php
* @uses lang_api.php
* @uses print_api.php
* @uses string_api.php
* @uses utility_api.php
*/
require_once( 'core.php' );
require_api( 'access_api.php' );
require_api( 'config_api.php' );
require_api( 'database_api.php' );
require_api( 'file_api.php' );
require_api( 'form_api.php' );
require_api( 'gpc_api.php' );
require_api( 'html_api.php' );
require_api( 'lang_api.php' );
require_api( 'print_api.php' );
require_api( 'string_api.php' );
require_api( 'utility_api.php' );
# Check if project documentation feature is enabled.
if( OFF == config_get( 'enable_project_documentation' ) ||
!file_is_uploading_enabled() ||
!file_allow_project_upload() ) {
access_denied();
}
$t_file_id = gpc_get_int( 'file_id' );
$t_project_id = file_get_field( $t_file_id, 'project_id', 'project' );
access_ensure_project_level( config_get( 'upload_project_file_threshold' ), $t_project_id );
$t_query = 'SELECT * FROM {project_file} WHERE id=' . db_param();
$t_result = db_query( $t_query, array( $t_file_id ) );
$t_row = db_fetch_array( $t_result );
extract( $t_row, EXTR_PREFIX_ALL, 'v' );
$v_title = string_attribute( $v_title );
$v_description = string_textarea( $v_description );
$t_max_file_size = file_get_max_file_size();
layout_page_header();
layout_page_begin( 'proj_doc_page.php' );
print_doc_menu();
?>
<div class="col-md-12 col-xs-12">
<div class="space-10"></div>
<div class="form-container">
<form method="post" enctype="multipart/form-data" action="proj_doc_update.php">
<?php echo form_security_field( 'proj_doc_update' ) ?>
<input type="hidden" name="file_id" value="<?php echo $t_file_id ?>"/>
<div class="widget-box widget-color-blue2">
<div class="widget-header widget-header-small">
<h4 class="widget-title lighter">
<i class="ace-icon fa fa-edit"></i>
<?php echo lang_get('upload_file_title') ?>
</h4>
</div>
<div class="widget-body">
<div class="widget-main no-padding">
<div class="table-responsive">
<table class="table table-bordered table-condensed table-striped">
<tr>
<th class="category" width="20%">
<span class="required">*</span> <?php echo lang_get( 'title' ) ?>
</th>
<td width="80%">
<input type="text" name="title" class="input-sm" size="70" maxlength="250" value="<?php echo $v_title ?>" required />
</td>
</tr>
<tr>
<th class="category">
<?php echo lang_get( 'description' ) ?>
</th>
<td>
<textarea class="form-control" name="description" cols="60" rows="7"><?php echo $v_description ?></textarea>
</td>
</tr>
<tr>
<th class="category">
<?php echo lang_get( 'filename' ) ?>
</th>
<td>
<?php
$t_href = '<a href="file_download.php?file_id='.$v_id.'&type=doc">';
echo $t_href;
print_file_icon( $v_filename );
echo '</a> ' . $t_href . file_get_display_name( $v_filename ) . '</a>';
?>
</td>
</tr>
<tr>
<td class="category">
<?php echo lang_get( 'select_file' ); ?>
<br />
<?php print_max_filesize( $t_max_file_size ); ?>
</td>
<td>
<input type="hidden" name="max_file_size" value="<?php echo $t_max_file_size ?>" />
<input name="file" type="file" size="70" />
</td>
<tr>
</table>
</div>
</div>
<div class="widget-toolbox padding-8 clearfix">
<span class="required pull-right"> * <?php echo lang_get('required') ?></span>
<input type="submit" class="btn btn-primary btn-white btn-round"
value="<?php echo lang_get('file_update_button') ?>"/>
</div>
</div>
</div>
</form>
</div>
<div class="space-10"></div>
<form method="post" action="proj_doc_delete.php">
<?php echo form_security_field( 'proj_doc_delete' ) ?>
<input type="hidden" name="file_id" value="<?php echo $t_file_id ?>" />
<input type="hidden" name="title" value="<?php echo $v_title ?>" />
<input type="submit" class="btn btn-sm btn-primary btn-white btn-round" value="<?php echo lang_get( 'file_delete_button' ) ?>" />
</form>
</div>
<?php
layout_page_end();
|
<?php
# MantisBT - A PHP based bugtracking system
# MantisBT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# MantisBT 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 MantisBT. If not, see <http://www.gnu.org/licenses/>.
/**
* Edit Project Documentation
*
* @package MantisBT
* @copyright Copyright 2000 - 2002 Kenzaburo Ito - kenito@300baud.org
* @copyright Copyright 2002 MantisBT Team - mantisbt-dev@lists.sourceforge.net
* @link http://www.mantisbt.org
*
* @uses core.php
* @uses access_api.php
* @uses config_api.php
* @uses database_api.php
* @uses file_api.php
* @uses form_api.php
* @uses gpc_api.php
* @uses html_api.php
* @uses lang_api.php
* @uses print_api.php
* @uses string_api.php
* @uses utility_api.php
*/
require_once( 'core.php' );
require_api( 'access_api.php' );
require_api( 'config_api.php' );
require_api( 'database_api.php' );
require_api( 'file_api.php' );
require_api( 'form_api.php' );
require_api( 'gpc_api.php' );
require_api( 'html_api.php' );
require_api( 'lang_api.php' );
require_api( 'print_api.php' );
require_api( 'string_api.php' );
require_api( 'utility_api.php' );
# Check if project documentation feature is enabled.
if( OFF == config_get( 'enable_project_documentation' ) ||
!file_is_uploading_enabled() ||
!file_allow_project_upload() ) {
access_denied();
}
$t_file_id = gpc_get_int( 'file_id' );
$t_project_id = file_get_field( $t_file_id, 'project_id', 'project' );
access_ensure_project_level( config_get( 'upload_project_file_threshold' ), $t_project_id );
$t_query = 'SELECT * FROM {project_file} WHERE id=' . db_param();
$t_result = db_query( $t_query, array( $t_file_id ) );
$t_row = db_fetch_array( $t_result );
extract( $t_row, EXTR_PREFIX_ALL, 'v' );
$v_title = string_attribute( $v_title );
$v_description = string_textarea( $v_description );
$t_max_file_size = file_get_max_file_size();
layout_page_header();
layout_page_begin( 'proj_doc_page.php' );
print_doc_menu();
?>
<div class="col-md-12 col-xs-12">
<div class="space-10"></div>
<div class="form-container">
<form method="post" enctype="multipart/form-data" action="proj_doc_update.php">
<?php echo form_security_field( 'proj_doc_update' ) ?>
<input type="hidden" name="file_id" value="<?php echo $t_file_id ?>"/>
<div class="widget-box widget-color-blue2">
<div class="widget-header widget-header-small">
<h4 class="widget-title lighter">
<i class="ace-icon fa fa-edit"></i>
<?php echo lang_get('upload_file_title') ?>
</h4>
</div>
<div class="widget-body">
<div class="widget-main no-padding">
<div class="table-responsive">
<table class="table table-bordered table-condensed table-striped">
<tr>
<th class="category" width="20%">
<span class="required">*</span> <?php echo lang_get( 'title' ) ?>
</th>
<td width="80%">
<input type="text" name="title" class="input-sm" size="70" maxlength="250" value="<?php echo $v_title ?>" required />
</td>
</tr>
<tr>
<th class="category">
<?php echo lang_get( 'description' ) ?>
</th>
<td>
<textarea class="form-control" name="description" cols="60" rows="7"><?php echo $v_description ?></textarea>
</td>
</tr>
<tr>
<th class="category">
<?php echo lang_get( 'filename' ) ?>
</th>
<td>
<?php
$t_href = '<a href="file_download.php?file_id='.$v_id.'&type=doc">';
echo $t_href;
print_file_icon( $v_filename );
echo '</a> ' . $t_href . string_html_specialchars( file_get_display_name( $v_filename ) ) . '</a>';
?>
</td>
</tr>
<tr>
<td class="category">
<?php echo lang_get( 'select_file' ); ?>
<br />
<?php print_max_filesize( $t_max_file_size ); ?>
</td>
<td>
<input type="hidden" name="max_file_size" value="<?php echo $t_max_file_size ?>" />
<input name="file" type="file" size="70" />
</td>
<tr>
</table>
</div>
</div>
<div class="widget-toolbox padding-8 clearfix">
<span class="required pull-right"> * <?php echo lang_get('required') ?></span>
<input type="submit" class="btn btn-primary btn-white btn-round"
value="<?php echo lang_get('file_update_button') ?>"/>
</div>
</div>
</div>
</form>
</div>
<div class="space-10"></div>
<form method="post" action="proj_doc_delete.php">
<?php echo form_security_field( 'proj_doc_delete' ) ?>
<input type="hidden" name="file_id" value="<?php echo $t_file_id ?>" />
<input type="hidden" name="title" value="<?php echo $v_title ?>" />
<input type="submit" class="btn btn-sm btn-primary btn-white btn-round" value="<?php echo lang_get( 'file_delete_button' ) ?>" />
</form>
</div>
<?php
layout_page_end();
|
bd094dede74ff6e313e286e949e2387233a96eea
|
https://github.com/mantisbt/mantisbt
|
index.php
|
php
|
<?php
$DEFAULT_REDIRECT = "https://someothersite.org";
$mysqli = new mysqli("127.0.0.1", "db_username", "db_password", "db_name");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if (isset($_SERVER["QUERY_STRING"]) && ($_SERVER["QUERY_STRING"] != '')) {
$query = sprintf("SELECT id, redirect_to FROM short_links WHERE short_link = '%s'
ORDER BY id DESC LIMIT 1", $mysqli->real_escape_string($_SERVER["QUERY_STRING"]));
$result = $mysqli->query($query);
$fail = 0;
if (!$result) {
// query failed
error_log("Sent an error 404 having executed query $query and got an error of " . $mysqli->error());
$fail = 1;
}
if ($result->num_rows < 1) {
// short link not found in db
error_log("Sent an error 404 having executed query $query and got no rows back");
$fail = 1;
}
$link = $result->fetch_array(MYSQLI_ASSOC);
$query = "UPDATE short_links SET count = count + 1, last_request = NOW() WHERE id = " . $link["id"];
$result = $mysqli->query($query);
if (!$result) {
// query failed updating db (this really shouldn't occur ever
error_log("Sent an error 404 having executed query $query and got an error of " . $mysqli->error());
$fail = 1;
}
if ($fail == 1) {
header("HTTP/1.0 404 Not Found");
print "<html><body><p>The requested short link was not found.</p></body></html>";
} else {
header("HTTP/1.1 301 Moved Permanently");
header("Location: " . $link["redirect_to"]);
}
} else {
// redirect to some default site
// I don't have a home page, but here you could just output some HTML
header("HTTP/1.1 301 Moved Permanently");
header("Location: " . $DEFAULT_REDIRECT);
}
?>
|
<?php
$DEFAULT_REDIRECT = "https://someothersite.org";
$mysqli = new mysqli("127.0.0.1", "db_username", "db_password", "db_name");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if (isset($_SERVER["QUERY_STRING"]) && ($_SERVER["QUERY_STRING"] != '')) {
$query = sprintf("SELECT id, redirect_to FROM short_links WHERE short_link = '%s'
ORDER BY id DESC LIMIT 1", $mysqli->real_escape_string($_SERVER["QUERY_STRING"]));
$result = $mysqli->query($query);
$fail = 0;
if (!$result) {
// query failed
error_log("Sent an error 404 having executed query $query and got an error of " . $mysqli->error());
$fail = 1;
}
if ($result->num_rows < 1) {
// short link not found in db
error_log("Sent an error 404 having executed query $query and got no rows back");
$fail = 1;
}
$link = $result->fetch_array(MYSQLI_ASSOC);
$query = sprintf("UPDATE short_links SET count = count + 1, last_request = NOW() WHERE id = ''%s''", $link["id"]);
$result = $mysqli->query($query);
if (!$result) {
// query failed updating db (this really shouldn't occur ever
error_log("Sent an error 404 having executed query $query and got an error of " . $mysqli->error());
$fail = 1;
}
if ($fail == 1) {
header("HTTP/1.0 404 Not Found");
print "<html><body><p>The requested short link was not found.</p></body></html>";
} else {
header("HTTP/1.1 301 Moved Permanently");
header("Location: " . $link["redirect_to"]);
}
} else {
// redirect to some default site
// I don't have a home page, but here you could just output some HTML
header("HTTP/1.1 301 Moved Permanently");
header("Location: " . $DEFAULT_REDIRECT);
}
?>
|
b26ac6480761635ed94ccb0222ba6b732de6e53f
|
https://github.com/mikebharris/simple_php_link_shortener
|
edit_feed.php
|
php
|
<?php
/************************************************************************/
/* ATutor */
/************************************************************************/
/* Copyright (c) 2002-2010 */
/* Inclusive Design Institute */
/* http://atutor.ca */
/* */
/* This program is free software. You can redistribute it and/or */
/* modify it under the terms of the GNU General Public License */
/* as published by the Free Software Foundation. */
/************************************************************************/
// $Id$
define('AT_INCLUDE_PATH', '../../../include/');
require(AT_INCLUDE_PATH . 'vitals.inc.php');
admin_authenticate(AT_ADMIN_PRIV_RSS);
$feed_id = intval($_GET['fid']);
$title_file = AT_CONTENT_DIR.'feeds/'.$feed_id.'_rss_title.cache';
if (isset($_GET['submit'])) {
$missing_fields = array();
//check both fields are not empty
if (trim($_REQUEST['title']) == '') {
$missing_fields[] = _AT('title');
}
if (trim($_REQUEST['url']) == '') {
$missing_fields[] = _AT('url');
}
if ($missing_fields) {
$missing_fields = implode(', ', $missing_fields);
$msg->addError(array('EMPTY_FIELDS', $missing_fields));
}
if (!$msg->containsErrors()) {
$_GET['url'] = $addslashes($_GET['url']);
$sql = "REPLACE INTO %sfeeds VALUES(%d, '%s')";
$result = queryDB($sql, array(TABLE_PREFIX, $feed_id, $_GET['url']));
//update language
if ($f = @fopen($title_file, 'w')) {
fwrite($f, $_GET['title'], strlen($_GET['title']));
fclose($f);
}
//delete old cache file
@unlink(AT_CONTENT_DIR.'/feeds/'.$feed_id.'_rss.cache');
$msg->addFeedback('ACTION_COMPLETED_SUCCESSFULLY');
header('Location: index.php');
exit;
}
} else if (isset($_GET['cancel'])) {
$msg->addFeedback('CANCELLED');
header("Location:index.php");
exit;
}
if ($feed_id != '') {
$sql = "SELECT * FROM %sfeeds WHERE feed_id=%d";
$row = queryDB($sql, array(TABLE_PREFIX, $feed_id), TRUE);
if (file_exists($title_file)) {
$_GET['title'] = file_get_contents($title_file);
}
$_GET['url'] = $row['url'];
}
$onload = 'document.form.title.focus();';
require (AT_INCLUDE_PATH.'header.inc.php');
$savant->assign('feed_id', $feed_id);
$savant->display('admin/system_preferences/edit_feed.tmpl.php');
require (AT_INCLUDE_PATH.'footer.inc.php'); ?>
|
<?php
/************************************************************************/
/* ATutor */
/************************************************************************/
/* Copyright (c) 2002-2010 */
/* Inclusive Design Institute */
/* http://atutor.ca */
/* */
/* This program is free software. You can redistribute it and/or */
/* modify it under the terms of the GNU General Public License */
/* as published by the Free Software Foundation. */
/************************************************************************/
// $Id$
define('AT_INCLUDE_PATH', '../../../include/');
require(AT_INCLUDE_PATH . 'vitals.inc.php');
admin_authenticate(AT_ADMIN_PRIV_RSS);
$feed_id = intval($_GET['fid']);
$title_file = AT_CONTENT_DIR.'feeds/'.$feed_id.'_rss_title.cache';
if (isset($_GET['submit'])) {
$missing_fields = array();
//check both fields are not empty
if (trim($_REQUEST['title']) == '') {
$missing_fields[] = _AT('title');
}
if (trim($_REQUEST['url']) == '') {
$missing_fields[] = _AT('url');
}
if ($missing_fields) {
$missing_fields = implode(', ', $missing_fields);
$msg->addError(array('EMPTY_FIELDS', $missing_fields));
}
if (!$msg->containsErrors()) {
$_GET['url'] = htmlspecialchars(strip_tags($_GET['url']), ENT_QUOTES);
$sql = "REPLACE INTO %sfeeds VALUES(%d, '%s')";
$result = queryDB($sql, array(TABLE_PREFIX, $feed_id, $_GET['url']));
//update language
if ($f = @fopen($title_file, 'w')) {
fwrite($f, $_GET['title'], strlen($_GET['title']));
fclose($f);
}
//delete old cache file
@unlink(AT_CONTENT_DIR.'/feeds/'.$feed_id.'_rss.cache');
$msg->addFeedback('ACTION_COMPLETED_SUCCESSFULLY');
header('Location: index.php');
exit;
}
} else if (isset($_GET['cancel'])) {
$msg->addFeedback('CANCELLED');
header("Location:index.php");
exit;
}
if ($feed_id != '') {
$sql = "SELECT * FROM %sfeeds WHERE feed_id=%d";
$row = queryDB($sql, array(TABLE_PREFIX, $feed_id), TRUE);
if (file_exists($title_file)) {
$_GET['title'] = file_get_contents($title_file);
}
$_GET['url'] = $row['url'];
}
$onload = 'document.form.title.focus();';
require (AT_INCLUDE_PATH.'header.inc.php');
$savant->assign('feed_id', $feed_id);
$savant->display('admin/system_preferences/edit_feed.tmpl.php');
require (AT_INCLUDE_PATH.'footer.inc.php'); ?>
|
9292360c8b3898d0990983269f110cef21729090
|
https://github.com/atutor/atutor
|
login.php
|
php
|
<?php
define('LOGIN_PAGE', true);
require_once 'includes/common.inc.php';
$page['css'][] = 'login';
require 'includes/header.inc.php';
// Layout borrowed from http://getbootstrap.com/examples/signin/
?>
<h1 class="logo">phpRedisAdmin</h1>
<form class="form-signin" method="post" action="login.php">
<h2 class="form-signin-heading">Please log in</h2>
<?php if (isset($_POST['username']) || isset($_POST['password'])): ?>
<div class="invalid-credentials">
<h3>Invalid username/password</h3>
<p>Please try again.</p>
</div>
<?php endif; ?>
<label for="inputUser" class="sr-only">Username</label>
<input type="text" name="username" id="inputUser" class="form-control"
placeholder="Username"
value="<?= isset($_POST['username']) ? $_POST['username'] : '' ?>"
required <?= isset($_POST['username']) ? '' : 'autofocus' ?>>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" name="password" id="inputPassword" class="form-control"
placeholder="Password"
required <?= isset($_POST['username']) ? 'autofocus' : '' ?>>
<button class="btn btn-lg btn-primary btn-block" type="submit">Log in</button>
</form>
<?php
require 'includes/footer.inc.php';
?>
|
<?php
define('LOGIN_PAGE', true);
require_once 'includes/common.inc.php';
$page['css'][] = 'login';
require 'includes/header.inc.php';
// Layout borrowed from http://getbootstrap.com/examples/signin/
?>
<h1 class="logo">phpRedisAdmin</h1>
<form class="form-signin" method="post" action="login.php">
<h2 class="form-signin-heading">Please log in</h2>
<?php if (isset($_POST['username']) || isset($_POST['password'])): ?>
<div class="invalid-credentials">
<h3>Invalid username/password</h3>
<p>Please try again.</p>
</div>
<?php endif; ?>
<label for="inputUser" class="sr-only">Username</label>
<input type="text" name="username" id="inputUser" class="form-control"
placeholder="Username"
value="<?= isset($_POST['username']) ? htmlentities($_POST['username'], defined('ENT_SUBSTITUTE') ? (ENT_QUOTES | ENT_SUBSTITUTE) : ENT_QUOTES, 'utf-8') : '' ?>"
required <?= isset($_POST['username']) ? '' : 'autofocus' ?>>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" name="password" id="inputPassword" class="form-control"
placeholder="Password"
required <?= isset($_POST['username']) ? 'autofocus' : '' ?>>
<button class="btn btn-lg btn-primary btn-block" type="submit">Log in</button>
</form>
<?php
require 'includes/footer.inc.php';
?>
|
eddaa674536d2e76e6d0b4efeb00604e992eab8f
|
https://github.com/erikdubbelboer/phpredisadmin
|
cloneClient.json.php
|
php
|
<?php
$time_start = microtime(true);
$config = '../../videos/configuration.php';
session_write_close();
if (!file_exists($config)) {
[$scriptPath] = get_included_files();
$path = pathinfo($scriptPath);
$config = $path['dirname'] . "/" . $config;
}
header('Content-Type: application/json');
require_once $config;
set_time_limit(0);
require_once $global['systemRootPath'] . 'objects/plugin.php';
require_once $global['systemRootPath'] . 'plugin/CloneSite/CloneSite.php';
require_once $global['systemRootPath'] . 'plugin/CloneSite/CloneLog.php';
require_once $global['systemRootPath'] . 'plugin/CloneSite/functions.php';
$totalSteps = 7;
$total2 = $total = 0;
$resp = new stdClass();
$resp->error = true;
$resp->msg = "";
$log = new CloneLog();
$log->add("Clone: Clone Start");
$objClone = AVideoPlugin::getObjectDataIfEnabled("CloneSite");
if (empty($objClone)) {
$resp->msg = "Your Clone Site Plugin is not enabled";
$log->add("Clone: {$resp->msg}");
die(json_encode($resp));
}
if (empty($objClone->cloneSiteURL)) {
$resp->msg = "Your Clone Site URL is empty, please click on the Edit parameters buttons and place an AVideo URL";
_error_log("{$resp->msg} (" . json_encode($objClone) . ")");
$log->add("Clone: {$resp->msg}");
die(json_encode($resp));
}
$objClone->cloneSiteURL = rtrim($objClone->cloneSiteURL, "/") . '/';
$objCloneOriginal = $objClone;
$argv[1] = preg_replace("/[^A-Za-z0-9 ]/", '', @$argv[1]);
if (empty($objClone) || empty($argv[1]) || $objClone->myKey !== $argv[1]) {
if (!User::isAdmin()) {
$resp->msg = "You can't do this";
$log->add("Clone: {$resp->msg}");
echo "$objClone->myKey !== $argv[1]";
die(json_encode($resp));
}
}
$videosSite = "{$objClone->cloneSiteURL}videos/";
$videosDir = Video::getStoragePath() . "";
$clonesDir = "{$videosDir}cache/clones/";
$photosDir = "{$videosDir}userPhoto/";
$photosSite = "{$videosSite}userPhoto/";
if (!file_exists($clonesDir)) {
mkdir($clonesDir, 0777, true);
file_put_contents($clonesDir . "index.html", '');
}
if (!file_exists($photosDir)) {
mkdir($photosDir, 0777, true);
}
$url = $objClone->cloneSiteURL . "plugin/CloneSite/cloneServer.json.php?url=" . urlencode($global['webSiteRootURL']) . "&key={$objClone->myKey}&useRsync=" . intval($objClone->useRsync);
// check if it respond
$log->add("Clone (1 of {$totalSteps}): Asking the Server the database and the files");
$content = url_get_contents($url, "", 3600, true);
_error_log("Clone: url_get_contents($url) respond: ($content)");
//var_dump($url, $content);exit;
$json = _json_decode($content);
if (empty($json)) {
$resp->msg = "Clone Server Unknow ERROR";
$log->add("Clone: Server Unknow ERROR");
die(json_encode($resp));
}
if (!empty($json->error)) {
$resp->msg = "Clone Server message: {$json->msg}";
$log->add("Clone: {$resp->msg}");
die(json_encode($resp));
}
$log->add("Clone: Good start! the server has answered");
$json->sqlFile = escapeshellarg(preg_replace('/[^a-z0-9_.-]/i', '', $json->sqlFile));
$json->videoFiles = escapeshellarg(preg_replace('/[^a-z0-9_.-]/i', '', $json->videoFiles));
$json->photoFiles = escapeshellarg(preg_replace('/[^a-z0-9_.-]/i', '', $json->photoFiles));
// get dump file
$cmd = "wget -O {$clonesDir}{$json->sqlFile} {$objClone->cloneSiteURL}videos/cache/clones/{$json->sqlFile}";
$log->add("Clone (2 of {$totalSteps}): Geting MySQL Dump file");
exec($cmd . " 2>&1", $output, $return_val);
if ($return_val !== 0) {
$log->add("Clone Error: " . print_r($output, true));
}
$log->add("Clone: Nice! we got the MySQL Dump file");
// remove the first warning line
$file = "{$clonesDir}{$json->sqlFile}";
$contents = file($file, FILE_IGNORE_NEW_LINES);
$first_line = array_shift($contents);
file_put_contents($file, implode("\r\n", $contents));
$log->add("Clone (3 of {$totalSteps}): Overwriting our database with the server database");
// restore dump
$cmd = "mysql -u {$mysqlUser} -p{$mysqlPass} --host {$mysqlHost} {$mysqlDatabase} < {$clonesDir}{$json->sqlFile}";
exec($cmd . " 2>&1", $output, $return_val);
if ($return_val !== 0) {
$log->add("Clone Error try again: " . end($output));
$cmd2 = "sed -i 's/COLLATE=utf8mb4_0900_ai_ci/ /g' {$clonesDir}{$json->sqlFile} ";
$log->add("Clone try again this command: {$cmd2}");
exec($cmd2 . " 2>&1", $output2, $return_val2);
if ($return_val2 !== 0) {
$log->add("Clone Error: " . print_r($output2, true));
}
$cmd2 = "sed -i 's/COLLATE utf8mb4_0900_ai_ci/ /g' {$clonesDir}{$json->sqlFile} ";
$log->add("and also this command: {$cmd2}");
exec($cmd2 . " 2>&1", $output2, $return_val2);
if ($return_val2 !== 0) {
$log->add("Clone Error: " . end($output2));
}
exec($cmd . " 2>&1", $output, $return_val);
if ($return_val !== 0) {
$log->add("Clone Error: " . end($output));
}
}
$log->add("Clone: Great! we overwrite it with success.");
if (empty($objClone->useRsync)) {
$videoFiles = getCloneFilesInfo($videosDir);
$newVideoFiles = detectNewFiles($json->videoFiles, $videoFiles);
$photoFiles = getCloneFilesInfo($photosDir, "userPhoto/");
$newPhotoFiles = detectNewFiles($json->photoFiles, $photoFiles);
$total = count($newVideoFiles);
$count = 0;
if (!empty($total)) {
$log->add("Clone (4 of {$totalSteps}): Now we will copy {$total} new video files, usually this takes a while.");
// copy videos
foreach ($newVideoFiles as $value) {
$query = parse_url($value->url, PHP_URL_QUERY);
if ($query) {
$value->url .= '&ignoreXsendfilePreVideoPlay=1';
} else {
$value->url .= '?ignoreXsendfilePreVideoPlay=1';
}
$count++;
$log->add("Clone: Copying Videos {$count} of {$total} {$value->url}");
file_put_contents("{$videosDir}{$value->filename}", fopen("$value->url", 'r'));
}
$log->add("Clone: Copying video files done.");
} else {
$log->add("Clone (4 of {$totalSteps}): There is no new video file to copy.");
}
$total2 = count($newPhotoFiles);
$count2 = 0;
if (!empty($total2)) {
$log->add("Clone (5 of {$totalSteps}): Now we will copy {$total2} new user photo files.");
// copy Photos
foreach ($newPhotoFiles as $value) {
$count2++;
$log->add("Clone: Copying Photos {$count2} of {$total2} {$value->url}");
file_put_contents("{$photosDir}{$value->filename}", fopen("$value->url", 'r'));
}
$log->add("Clone: Copying user photo files done.");
} else {
$log->add("Clone (5 of {$totalSteps}): There is no new user photo file to copy.");
}
} else {
// decrypt the password now
$objClone = Plugin::decryptIfNeed($objClone);
$port = intval($objClone->cloneSiteSSHPort);
if (empty($port)) {
$port = 22;
}
$rsync = "sshpass -p '{password}' rsync -av -e 'ssh -p {$port} -o StrictHostKeyChecking=no' --exclude '*.php' --exclude 'cache' --exclude '*.sql' --exclude '*.log' {$objClone->cloneSiteSSHUser}@{$objClone->cloneSiteSSHIP}:{$json->videosDir} " . Video::getStoragePath() . " --log-file='{$log->file}' ";
$cmd = str_replace("{password}", $objClone->cloneSiteSSHPassword->value, $rsync);
$log->add("Clone (4 of {$totalSteps}): execute rsync ({$rsync})");
exec($cmd . " 2>&1", $output, $return_val);
if ($return_val !== 0) {
//$log->add("Clone Error: " . print_r($output, true));
}
$log->add("Clone (5 of {$totalSteps}): rsync finished");
}
// notify to delete dump
$url = $url . "&deleteDump={$json->sqlFile}";
// check if it respond
$log->add("Clone (6 of {$totalSteps}): Notify Server to Delete Dump");
$content2 = url_get_contents($url);
//var_dump($url, $content);exit;
$json2 = _json_decode($content);
if (!empty($json2->error)) {
$log->add("Clone: Dump NOT deleted");
} else {
$log->add("Clone: Dump DELETED");
}
$log->add("Clone (7 of {$totalSteps}): Resotre the Clone Configuration");
// restore clone plugin configuration
$plugin = new CloneSite();
$p = new Plugin(0);
$p->loadFromUUID($plugin->getUUID());
$p->setObject_data(addcslashes(json_encode($objCloneOriginal), '\\'));
$p->setStatus('active');
$p->save();
echo json_encode($json);
$log->add("Clone: Complete, Database, {$total} Videos and {$total2} Photos");
$cmd = "chmod -R 777 {$videosDir}";
exec($cmd);
$time_end = microtime(true);
//dividing with 60 will give the execution time in minutes otherwise seconds
$execution_time = ($time_end - $time_start);
$timeStr = "Seconds";
if ($execution_time > 60) {
$execution_time = $execution_time / 60;
$timeStr = "Minutes";
}
//execution time of the script
$log->add('Total Execution Time: ' . $execution_time . ' ' . $timeStr);
|
<?php
$time_start = microtime(true);
$config = '../../videos/configuration.php';
session_write_close();
if (!file_exists($config)) {
[$scriptPath] = get_included_files();
$path = pathinfo($scriptPath);
$config = $path['dirname'] . "/" . $config;
}
header('Content-Type: application/json');
require_once $config;
set_time_limit(0);
require_once $global['systemRootPath'] . 'objects/plugin.php';
require_once $global['systemRootPath'] . 'plugin/CloneSite/CloneSite.php';
require_once $global['systemRootPath'] . 'plugin/CloneSite/CloneLog.php';
require_once $global['systemRootPath'] . 'plugin/CloneSite/functions.php';
$totalSteps = 7;
$total2 = $total = 0;
$resp = new stdClass();
$resp->error = true;
$resp->msg = "";
$log = new CloneLog();
$log->add("Clone: Clone Start");
$objClone = AVideoPlugin::getObjectDataIfEnabled("CloneSite");
if (empty($objClone)) {
$resp->msg = "Your Clone Site Plugin is not enabled";
$log->add("Clone: {$resp->msg}");
die(json_encode($resp));
}
if (empty($objClone->cloneSiteURL)) {
$resp->msg = "Your Clone Site URL is empty, please click on the Edit parameters buttons and place an AVideo URL";
_error_log("{$resp->msg} (" . json_encode($objClone) . ")");
$log->add("Clone: {$resp->msg}");
die(json_encode($resp));
}
$objClone->cloneSiteURL = rtrim($objClone->cloneSiteURL, "/") . '/';
$objCloneOriginal = $objClone;
$argv[1] = preg_replace("/[^A-Za-z0-9 ]/", '', @$argv[1]);
if (empty($objClone) || empty($argv[1]) || $objClone->myKey !== $argv[1]) {
if (!User::isAdmin()) {
$resp->msg = "You can't do this";
$log->add("Clone: {$resp->msg}");
echo "$objClone->myKey !== $argv[1]";
die(json_encode($resp));
}
}
$videosSite = "{$objClone->cloneSiteURL}videos/";
$videosDir = Video::getStoragePath() . "";
$clonesDir = "{$videosDir}cache/clones/";
$photosDir = "{$videosDir}userPhoto/";
$photosSite = "{$videosSite}userPhoto/";
if (!file_exists($clonesDir)) {
mkdir($clonesDir, 0777, true);
file_put_contents($clonesDir . "index.html", '');
}
if (!file_exists($photosDir)) {
mkdir($photosDir, 0777, true);
}
$url = $objClone->cloneSiteURL . "plugin/CloneSite/cloneServer.json.php?url=" . urlencode($global['webSiteRootURL']) . "&key={$objClone->myKey}&useRsync=" . intval($objClone->useRsync);
// check if it respond
$log->add("Clone (1 of {$totalSteps}): Asking the Server the database and the files");
$content = url_get_contents($url, "", 3600, true);
_error_log("Clone: url_get_contents($url) respond: ($content)");
//var_dump($url, $content);exit;
$json = _json_decode($content);
if (empty($json)) {
$resp->msg = "Clone Server Unknow ERROR";
$log->add("Clone: Server Unknow ERROR");
die(json_encode($resp));
}
if (!empty($json->error)) {
$resp->msg = "Clone Server message: {$json->msg}";
$log->add("Clone: {$resp->msg}");
die(json_encode($resp));
}
$log->add("Clone: Good start! the server has answered");
$json->sqlFile = escapeshellarg(preg_replace('/[^a-z0-9_.-]/i', '', $json->sqlFile));
$json->videoFiles = escapeshellarg(preg_replace('/[^a-z0-9_.-]/i', '', $json->videoFiles));
$json->photoFiles = escapeshellarg(preg_replace('/[^a-z0-9_.-]/i', '', $json->photoFiles));
$objClone->cloneSiteURL = escapeshellarg($objClone->cloneSiteURL);
// get dump file
$cmd = "wget -O {$clonesDir}{$json->sqlFile} {$objClone->cloneSiteURL}videos/cache/clones/{$json->sqlFile}";
$log->add("Clone (2 of {$totalSteps}): Geting MySQL Dump file");
exec($cmd . " 2>&1", $output, $return_val);
if ($return_val !== 0) {
$log->add("Clone Error: " . print_r($output, true));
}
$log->add("Clone: Nice! we got the MySQL Dump file");
// remove the first warning line
$file = "{$clonesDir}{$json->sqlFile}";
$contents = file($file, FILE_IGNORE_NEW_LINES);
$first_line = array_shift($contents);
file_put_contents($file, implode("\r\n", $contents));
$log->add("Clone (3 of {$totalSteps}): Overwriting our database with the server database");
// restore dump
$cmd = "mysql -u {$mysqlUser} -p{$mysqlPass} --host {$mysqlHost} {$mysqlDatabase} < {$clonesDir}{$json->sqlFile}";
exec($cmd . " 2>&1", $output, $return_val);
if ($return_val !== 0) {
$log->add("Clone Error try again: " . end($output));
$cmd2 = "sed -i 's/COLLATE=utf8mb4_0900_ai_ci/ /g' {$clonesDir}{$json->sqlFile} ";
$log->add("Clone try again this command: {$cmd2}");
exec($cmd2 . " 2>&1", $output2, $return_val2);
if ($return_val2 !== 0) {
$log->add("Clone Error: " . print_r($output2, true));
}
$cmd2 = "sed -i 's/COLLATE utf8mb4_0900_ai_ci/ /g' {$clonesDir}{$json->sqlFile} ";
$log->add("and also this command: {$cmd2}");
exec($cmd2 . " 2>&1", $output2, $return_val2);
if ($return_val2 !== 0) {
$log->add("Clone Error: " . end($output2));
}
exec($cmd . " 2>&1", $output, $return_val);
if ($return_val !== 0) {
$log->add("Clone Error: " . end($output));
}
}
$log->add("Clone: Great! we overwrite it with success.");
if (empty($objClone->useRsync)) {
$videoFiles = getCloneFilesInfo($videosDir);
$newVideoFiles = detectNewFiles($json->videoFiles, $videoFiles);
$photoFiles = getCloneFilesInfo($photosDir, "userPhoto/");
$newPhotoFiles = detectNewFiles($json->photoFiles, $photoFiles);
$total = count($newVideoFiles);
$count = 0;
if (!empty($total)) {
$log->add("Clone (4 of {$totalSteps}): Now we will copy {$total} new video files, usually this takes a while.");
// copy videos
foreach ($newVideoFiles as $value) {
$query = parse_url($value->url, PHP_URL_QUERY);
if ($query) {
$value->url .= '&ignoreXsendfilePreVideoPlay=1';
} else {
$value->url .= '?ignoreXsendfilePreVideoPlay=1';
}
$count++;
$log->add("Clone: Copying Videos {$count} of {$total} {$value->url}");
file_put_contents("{$videosDir}{$value->filename}", fopen("$value->url", 'r'));
}
$log->add("Clone: Copying video files done.");
} else {
$log->add("Clone (4 of {$totalSteps}): There is no new video file to copy.");
}
$total2 = count($newPhotoFiles);
$count2 = 0;
if (!empty($total2)) {
$log->add("Clone (5 of {$totalSteps}): Now we will copy {$total2} new user photo files.");
// copy Photos
foreach ($newPhotoFiles as $value) {
$count2++;
$log->add("Clone: Copying Photos {$count2} of {$total2} {$value->url}");
file_put_contents("{$photosDir}{$value->filename}", fopen("$value->url", 'r'));
}
$log->add("Clone: Copying user photo files done.");
} else {
$log->add("Clone (5 of {$totalSteps}): There is no new user photo file to copy.");
}
} else {
// decrypt the password now
$objClone = Plugin::decryptIfNeed($objClone);
$port = intval($objClone->cloneSiteSSHPort);
if (empty($port)) {
$port = 22;
}
$rsync = "sshpass -p '{password}' rsync -av -e 'ssh -p {$port} -o StrictHostKeyChecking=no' --exclude '*.php' --exclude 'cache' --exclude '*.sql' --exclude '*.log' {$objClone->cloneSiteSSHUser}@{$objClone->cloneSiteSSHIP}:{$json->videosDir} " . Video::getStoragePath() . " --log-file='{$log->file}' ";
$cmd = str_replace("{password}", $objClone->cloneSiteSSHPassword->value, $rsync);
$log->add("Clone (4 of {$totalSteps}): execute rsync ({$rsync})");
exec($cmd . " 2>&1", $output, $return_val);
if ($return_val !== 0) {
//$log->add("Clone Error: " . print_r($output, true));
}
$log->add("Clone (5 of {$totalSteps}): rsync finished");
}
// notify to delete dump
$url = $url . "&deleteDump={$json->sqlFile}";
// check if it respond
$log->add("Clone (6 of {$totalSteps}): Notify Server to Delete Dump");
$content2 = url_get_contents($url);
//var_dump($url, $content);exit;
$json2 = _json_decode($content);
if (!empty($json2->error)) {
$log->add("Clone: Dump NOT deleted");
} else {
$log->add("Clone: Dump DELETED");
}
$log->add("Clone (7 of {$totalSteps}): Resotre the Clone Configuration");
// restore clone plugin configuration
$plugin = new CloneSite();
$p = new Plugin(0);
$p->loadFromUUID($plugin->getUUID());
$p->setObject_data(addcslashes(json_encode($objCloneOriginal), '\\'));
$p->setStatus('active');
$p->save();
echo json_encode($json);
$log->add("Clone: Complete, Database, {$total} Videos and {$total2} Photos");
$cmd = "chmod -R 777 {$videosDir}";
exec($cmd);
$time_end = microtime(true);
//dividing with 60 will give the execution time in minutes otherwise seconds
$execution_time = ($time_end - $time_start);
$timeStr = "Seconds";
if ($execution_time > 60) {
$execution_time = $execution_time / 60;
$timeStr = "Minutes";
}
//execution time of the script
$log->add('Total Execution Time: ' . $execution_time . ' ' . $timeStr);
|
1df4af01f80d56ff2c4c43b89d0bac151e7fb6e3
|
https://github.com/wwbn/avideo
|
link_manager.php
|
php
|
<?php
if ($_SERVER["PHP_SELF"] == "/admin/index.php") {
include_once $_SERVER['DOCUMENT_ROOT'].'/config/language.php'; // Translation Code
if (!empty($_POST) && isset($_POST["dstrMgrSubmit"])):
//if (!empty($_POST)):
if (preg_match('/[^A-Z]/',$_POST["Link"])) { unset ($_POST["Link"]);}
if ($_POST["Link"] == "LINK") {
if (preg_match('/[^A-Za-z0-9 ]/',$_POST["RefName"])) { unset ($_POST["RefName"]);}
if (preg_match('/[^A-Z]/',$_POST["Letter"])) { unset ($_POST["Letter"]);}
if (preg_match('/[^A-Z0-9 ]/',$_POST["Module"])) { unset ($_POST["Module"]);}
}
if (empty($_POST["RefName"]) || empty($_POST["Letter"]) || empty($_POST["Module"])) { echo "Somthing wrong with your input, try again";}
else {
if (strlen($_POST["RefName"]) != 7) {
$targetRef = str_pad($_POST["RefName"], 7, " ");
} else {
$targetRef = $_POST["RefName"];
}
$targetRef = $targetRef.$_POST["Letter"];
$targetRef = strtoupper($targetRef);
$module = $_POST["Module"];
if (strlen($module) != 8) { //Fix the length of the module information
$moduleFixedCs = strlen($module) - 1; //Length of the string, -1
$moduleFixedBand = substr($module, -1); //Single Band Letter in the 8th position
$moduleFixedCallPad = str_pad(substr($module, 0, $moduleFixedCs), 7); //Pad the callsign area to 7 chars
$module = $moduleFixedCallPad.$moduleFixedBand; //Re add the band information
};
$unlinkCommand = "sudo remotecontrold \"".$module."\" unlink";
$linkCommand = "sudo remotecontrold \"".$module."\" link never \"".$targetRef."\"";
if ($module != $targetRef && $_POST["Link"] == "LINK") { // Sanity check that we are not connecting to ourself
echo "<b>D-Star Link Manager</b>\n";
echo "<table>\n<tr><th>Command Output</th></tr>\n<tr><td>";
echo exec($linkCommand);
echo "</td></tr>\n</table>\n";
}
if ($module == $targetRef && $_POST["Link"] == "LINK") { // Sanity Check Failed
echo "<b>D-Star Link Manager</b>\n";
echo "<table>\n<tr><th>Command Output</th></tr>\n<tr><td>";
echo "Cannot link to myself - Aborting link request!";
echo "</td></tr>\n</table>\n";
}
if ($_POST["Link"] == "UNLINK") { // Allow Unlink no matter what
echo "<b>D-Star Link Manager</b>\n";
echo "<table>\n<tr><th>Command Output</th></tr>\n<tr><td>";
echo exec($unlinkCommand);
echo "</td></tr>\n</table>\n";
}
}
unset($_POST);
echo '<script type="text/javascript">setTimeout(function() { window.location=window.location;},2000);</script>';
else: ?>
<b><?php echo $lang['d-star_link_manager'];?></b>
<form action="//<?php echo htmlentities($_SERVER['HTTP_HOST']).htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<table>
<tr>
<th width="150"><a class="tooltip" href="#">Radio Module<span><b>Radio Module</b></span></a></th>
<th width="180"><a class="tooltip" href="#">Reflector<span><b>Reflector</b></span></a></th>
<th width="150"><a class="tooltip" href="#">Link / Un-Link<span><b>Link / Un-Link</b></span></a></th>
<th><a class="tooltip" href="#">Action<span><b>Action</b></span></a></th>
</tr>
<tr>
<td>
<select name="Module">
<?php
$ci = 0;
for($i = 1;$i < 5; $i++){
$param="repeaterBand" . $i;
if((isset($configs[$param])) && strlen($configs[$param]) == 1) {
$ci++;
if($ci > 1) { $ci = 0; }
$module = $configs[$param];
$rcall = sprintf("%-7.7s%-1.1s",$MYCALL,$module);
$param="repeaterCall" . $i;
if(isset($configs[$param])) { $rptrcall=sprintf("%-7.7s%-1.1s",$configs[$param],$module); } else { $rptrcall = $rcall;}
print "<option>$rptrcall</option>\n";
}
} ?>
</select>
</td>
<td>
<select name="RefName"
onchange="if (this.options[this.selectedIndex].value == 'customOption') {
toggleField(this,this.nextSibling);
this.selectedIndex='0';
} ">
<?php
$dcsFile = fopen("/usr/local/etc/DCS_Hosts.txt", "r");
$dplusFile = fopen("/usr/local/etc/DPlus_Hosts.txt", "r");
$dextraFile = fopen("/usr/local/etc/DExtra_Hosts.txt", "r");
echo " <option value=\"".substr($configs['reflector1'], 0, 6)."\" selected=\"selected\">".substr($configs['reflector1'], 0, 6)."</option>\n";
echo " <option value=\"customOption\">Text Entry</option>\n";
while (!feof($dcsFile)) {
$dcsLine = fgets($dcsFile);
if (strpos($dcsLine, 'DCS') !== FALSE && strpos($dcsLine, '#') === FALSE) {
echo " <option value=\"".substr($dcsLine, 0, 6)."\">".substr($dcsLine, 0, 6)."</option>\n";
}
if (strpos($dcsLine, 'XLX') !== FALSE && strpos($dcsLine, '#') === FALSE) {
echo " <option value=\"".substr($dcsLine, 0, 6)."\">".substr($dcsLine, 0, 6)."</option>\n";
}
}
fclose($dcsFile);
while (!feof($dplusFile)) {
$dplusLine = fgets($dplusFile);
if (strpos($dplusLine, 'REF') !== FALSE && strpos($dplusLine, '#') === FALSE) {
echo " <option value=\"".substr($dplusLine, 0, 6)."\">".substr($dplusLine, 0, 6)."</option>\n";
}
if (strpos($dplusLine, 'XRF') !== FALSE && strpos($dplusLine, '#') === FALSE) {
echo " <option value=\"".substr($dplusLine, 0, 6)."\">".substr($dplusLine, 0, 6)."</option>\n";
}
}
fclose($dplusFile);
while (!feof($dextraFile)) {
$dextraLine = fgets($dextraFile);
if (strpos($dextraLine, 'XRF') !== FALSE && strpos($dextraLine, '#') === FALSE)
echo " <option value=\"".substr($dextraLine, 0, 6)."\">".substr($dextraLine, 0, 6)."</option>\n";
}
fclose($dextraFile);
?>
</select><input name="RefName" style="display:none;" disabled="disabled" type="text" size="7" maxlength="7"
onblur="if(this.value==''){toggleField(this,this.previousSibling);}" />
<select name="Letter">
<?php echo " <option value=\"".substr($configs['reflector1'], 7)."\" selected=\"selected\">".substr($configs['reflector1'], 7)."</option>\n"; ?>
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>E</option>
<option>F</option>
<option>G</option>
<option>H</option>
<option>I</option>
<option>J</option>
<option>K</option>
<option>L</option>
<option>M</option>
<option>N</option>
<option>O</option>
<option>P</option>
<option>Q</option>
<option>R</option>
<option>S</option>
<option>T</option>
<option>U</option>
<option>V</option>
<option>W</option>
<option>X</option>
<option>Y</option>
<option>Z</option>
</select>
</td>
<td>
<input type="radio" name="Link" value="LINK" checked="checked" />Link
<input type="radio" name="Link" value="UNLINK" />UnLink
</td>
<td>
<input type="submit" name="dstrMgrSubmit" value="Request Change" />
</td>
</tr>
</table>
</form>
<?php endif; ?>
<?php
exec ("pgrep pistar-keeper", $pids);
if (!empty($pids))
{
echo "<br />\n";
echo "<b>PiStar-Keeper Logbook</b><input type=button onClick=\"location.href='/admin/pistar-keeper-download.php'\" value=\"Download Logbook\">\n";
echo "<table>\n";
echo " <tr>\n";
echo " <th><a class=\"tooltip\" href=\"#\">PiStar-Keeper Log Entries (UTC)<span><b>PiStar-Keeper Log Entries (UTC)</b></span></th>\n";
echo " </tr>\n";
exec ("tail -n 5 /var/pistar-keeper/pistar-keeper.log", $lines);
$counter = 0;
foreach ($lines as $line) {
echo "<tr><td align=\"left\">".$lines[$counter]."</td></tr>\n";
$counter++;
}
echo "</table>\n";
}
}
?>
|
<?php
if ($_SERVER["PHP_SELF"] == "/admin/index.php") {
include_once $_SERVER['DOCUMENT_ROOT'].'/config/language.php'; // Translation Code
if (!empty($_POST) && isset($_POST["dstrMgrSubmit"])):
//if (!empty($_POST)):
if (preg_match('/[^A-Z]/',$_POST["Link"])) { unset ($_POST["Link"]);}
if ($_POST["Link"] == "LINK") {
if (preg_match('/[^A-Za-z0-9 ]/',$_POST["RefName"])) { unset ($_POST["RefName"]);}
if (preg_match('/[^A-Z]/',$_POST["Letter"])) { unset ($_POST["Letter"]);}
if (preg_match('/[^A-Z0-9 ]/',$_POST["Module"])) { unset ($_POST["Module"]);}
}
if (empty($_POST["RefName"]) || empty($_POST["Letter"]) || empty($_POST["Module"])) { echo "Somthing wrong with your input, try again";}
else {
if (strlen($_POST["RefName"]) != 7) {
$targetRef = str_pad($_POST["RefName"], 7, " ");
} else {
$targetRef = $_POST["RefName"];
}
$targetRef = $targetRef.$_POST["Letter"];
$targetRef = strtoupper($targetRef);
$module = substr($_POST["Module"], 0, 7);
$module = preg_replace("/[^a-zA-Z0-9]+/", "", $module);
if (strlen($module) != 8) { //Fix the length of the module information
$moduleFixedCs = strlen($module) - 1; //Length of the string, -1
$moduleFixedBand = substr($module, -1); //Single Band Letter in the 8th position
$moduleFixedCallPad = str_pad(substr($module, 0, $moduleFixedCs), 7); //Pad the callsign area to 7 chars
$module = $moduleFixedCallPad.$moduleFixedBand; //Re add the band information
};
$unlinkCommand = "sudo remotecontrold \"".$module."\" unlink";
$linkCommand = "sudo remotecontrold \"".$module."\" link never \"".$targetRef."\"";
if ($module != $targetRef && $_POST["Link"] == "LINK") { // Sanity check that we are not connecting to ourself
echo "<b>D-Star Link Manager</b>\n";
echo "<table>\n<tr><th>Command Output</th></tr>\n<tr><td>";
echo exec($linkCommand);
echo "</td></tr>\n</table>\n";
}
if ($module == $targetRef && $_POST["Link"] == "LINK") { // Sanity Check Failed
echo "<b>D-Star Link Manager</b>\n";
echo "<table>\n<tr><th>Command Output</th></tr>\n<tr><td>";
echo "Cannot link to myself - Aborting link request!";
echo "</td></tr>\n</table>\n";
}
if ($_POST["Link"] == "UNLINK") { // Allow Unlink no matter what
echo "<b>D-Star Link Manager</b>\n";
echo "<table>\n<tr><th>Command Output</th></tr>\n<tr><td>";
echo exec($unlinkCommand);
echo "</td></tr>\n</table>\n";
}
}
unset($_POST);
echo '<script type="text/javascript">setTimeout(function() { window.location=window.location;},2000);</script>';
else: ?>
<b><?php echo $lang['d-star_link_manager'];?></b>
<form action="//<?php echo htmlentities($_SERVER['HTTP_HOST']).htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<table>
<tr>
<th width="150"><a class="tooltip" href="#">Radio Module<span><b>Radio Module</b></span></a></th>
<th width="180"><a class="tooltip" href="#">Reflector<span><b>Reflector</b></span></a></th>
<th width="150"><a class="tooltip" href="#">Link / Un-Link<span><b>Link / Un-Link</b></span></a></th>
<th><a class="tooltip" href="#">Action<span><b>Action</b></span></a></th>
</tr>
<tr>
<td>
<select name="Module">
<?php
$ci = 0;
for($i = 1;$i < 5; $i++){
$param="repeaterBand" . $i;
if((isset($configs[$param])) && strlen($configs[$param]) == 1) {
$ci++;
if($ci > 1) { $ci = 0; }
$module = $configs[$param];
$rcall = sprintf("%-7.7s%-1.1s",$MYCALL,$module);
$param="repeaterCall" . $i;
if(isset($configs[$param])) { $rptrcall=sprintf("%-7.7s%-1.1s",$configs[$param],$module); } else { $rptrcall = $rcall;}
print "<option>$rptrcall</option>\n";
}
} ?>
</select>
</td>
<td>
<select name="RefName"
onchange="if (this.options[this.selectedIndex].value == 'customOption') {
toggleField(this,this.nextSibling);
this.selectedIndex='0';
} ">
<?php
$dcsFile = fopen("/usr/local/etc/DCS_Hosts.txt", "r");
$dplusFile = fopen("/usr/local/etc/DPlus_Hosts.txt", "r");
$dextraFile = fopen("/usr/local/etc/DExtra_Hosts.txt", "r");
echo " <option value=\"".substr($configs['reflector1'], 0, 6)."\" selected=\"selected\">".substr($configs['reflector1'], 0, 6)."</option>\n";
echo " <option value=\"customOption\">Text Entry</option>\n";
while (!feof($dcsFile)) {
$dcsLine = fgets($dcsFile);
if (strpos($dcsLine, 'DCS') !== FALSE && strpos($dcsLine, '#') === FALSE) {
echo " <option value=\"".substr($dcsLine, 0, 6)."\">".substr($dcsLine, 0, 6)."</option>\n";
}
if (strpos($dcsLine, 'XLX') !== FALSE && strpos($dcsLine, '#') === FALSE) {
echo " <option value=\"".substr($dcsLine, 0, 6)."\">".substr($dcsLine, 0, 6)."</option>\n";
}
}
fclose($dcsFile);
while (!feof($dplusFile)) {
$dplusLine = fgets($dplusFile);
if (strpos($dplusLine, 'REF') !== FALSE && strpos($dplusLine, '#') === FALSE) {
echo " <option value=\"".substr($dplusLine, 0, 6)."\">".substr($dplusLine, 0, 6)."</option>\n";
}
if (strpos($dplusLine, 'XRF') !== FALSE && strpos($dplusLine, '#') === FALSE) {
echo " <option value=\"".substr($dplusLine, 0, 6)."\">".substr($dplusLine, 0, 6)."</option>\n";
}
}
fclose($dplusFile);
while (!feof($dextraFile)) {
$dextraLine = fgets($dextraFile);
if (strpos($dextraLine, 'XRF') !== FALSE && strpos($dextraLine, '#') === FALSE)
echo " <option value=\"".substr($dextraLine, 0, 6)."\">".substr($dextraLine, 0, 6)."</option>\n";
}
fclose($dextraFile);
?>
</select><input name="RefName" style="display:none;" disabled="disabled" type="text" size="7" maxlength="7"
onblur="if(this.value==''){toggleField(this,this.previousSibling);}" />
<select name="Letter">
<?php echo " <option value=\"".substr($configs['reflector1'], 7)."\" selected=\"selected\">".substr($configs['reflector1'], 7)."</option>\n"; ?>
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>E</option>
<option>F</option>
<option>G</option>
<option>H</option>
<option>I</option>
<option>J</option>
<option>K</option>
<option>L</option>
<option>M</option>
<option>N</option>
<option>O</option>
<option>P</option>
<option>Q</option>
<option>R</option>
<option>S</option>
<option>T</option>
<option>U</option>
<option>V</option>
<option>W</option>
<option>X</option>
<option>Y</option>
<option>Z</option>
</select>
</td>
<td>
<input type="radio" name="Link" value="LINK" checked="checked" />Link
<input type="radio" name="Link" value="UNLINK" />UnLink
</td>
<td>
<input type="submit" name="dstrMgrSubmit" value="Request Change" />
</td>
</tr>
</table>
</form>
<?php endif; ?>
<?php
exec ("pgrep pistar-keeper", $pids);
if (!empty($pids))
{
echo "<br />\n";
echo "<b>PiStar-Keeper Logbook</b><input type=button onClick=\"location.href='/admin/pistar-keeper-download.php'\" value=\"Download Logbook\">\n";
echo "<table>\n";
echo " <tr>\n";
echo " <th><a class=\"tooltip\" href=\"#\">PiStar-Keeper Log Entries (UTC)<span><b>PiStar-Keeper Log Entries (UTC)</b></span></th>\n";
echo " </tr>\n";
exec ("tail -n 5 /var/pistar-keeper/pistar-keeper.log", $lines);
$counter = 0;
foreach ($lines as $line) {
echo "<tr><td align=\"left\">".$lines[$counter]."</td></tr>\n";
$counter++;
}
echo "</table>\n";
}
}
?>
|
1e46533f4051648bc40478d99201f19241bbaa41
|
https://github.com/andytaylortweet/pi-star_dv_dash
|
client.inc.php
|
php
|
<?php
/*********************************************************************
client.inc.php
File included on every client page
Peter Rotich <peter@osticket.com>
Copyright (c) 2006-2013 osTicket
http://www.osticket.com
Released under the GNU General Public License WITHOUT ANY WARRANTY.
See LICENSE.TXT for details.
vim: expandtab sw=4 ts=4 sts=4:
**********************************************************************/
if(!strcasecmp(basename($_SERVER['SCRIPT_NAME']),basename(__FILE__))) die('kwaheri rafiki!');
$thisdir=str_replace('\\', '/', dirname(__FILE__)).'/';
if(!file_exists($thisdir.'main.inc.php')) die('Fatal Error.');
require_once($thisdir.'main.inc.php');
if(!defined('INCLUDE_DIR')) die('Fatal error');
/*Some more include defines specific to client only */
define('CLIENTINC_DIR',INCLUDE_DIR.'client/');
define('OSTCLIENTINC',TRUE);
define('ASSETS_PATH',ROOT_PATH.'assets/default/');
//Check the status of the HelpDesk.
if (!in_array(strtolower(basename($_SERVER['SCRIPT_NAME'])), array('logo.php',))
&& !(is_object($ost) && $ost->isSystemOnline())) {
include(ROOT_DIR.'offline.php');
exit;
}
/* include what is needed on client stuff */
require_once(INCLUDE_DIR.'class.client.php');
require_once(INCLUDE_DIR.'class.ticket.php');
require_once(INCLUDE_DIR.'class.dept.php');
//clear some vars
$errors=array();
$msg='';
$nav=null;
//Make sure the user is valid..before doing anything else.
$thisclient = UserAuthenticationBackend::getUser();
if (isset($_GET['lang']) && $_GET['lang']) {
$_SESSION['client:lang'] = $_GET['lang'];
}
// Bootstrap gettext translations as early as possible, but after attempting
// to sign on the agent
TextDomain::configureForUser($thisclient);
//is the user logged in?
if($thisclient && $thisclient->getId() && $thisclient->isValid()){
$thisclient->refreshSession();
} else {
$thisclient = null;
}
/******* CSRF Protectin *************/
// Enforce CSRF protection for POSTS
if ($_POST && !$ost->checkCSRFToken()) {
Http::redirect('index.php');
//just incase redirect fails
die('Action denied (400)!');
}
//Add token to the header - used on ajax calls [DO NOT CHANGE THE NAME]
$ost->addExtraHeader('<meta name="csrf_token" content="'.$ost->getCSRFToken().'" />');
/* Client specific defaults */
define('PAGE_LIMIT', DEFAULT_PAGE_LIMIT);
$nav = new UserNav($thisclient, 'home');
$exempt = in_array(basename($_SERVER['SCRIPT_NAME']), array('logout.php', 'ajax.php', 'logs.php', 'upgrade.php'));
if (!$exempt && $thisclient && ($acct = $thisclient->getAccount())
&& $acct->isPasswdResetForced()) {
$warn = __('Password change required to continue');
require('profile.php'); //profile.php must request this file as require_once to avoid problems.
exit;
}
?>
|
<?php
/*********************************************************************
client.inc.php
File included on every client page
Peter Rotich <peter@osticket.com>
Copyright (c) 2006-2013 osTicket
http://www.osticket.com
Released under the GNU General Public License WITHOUT ANY WARRANTY.
See LICENSE.TXT for details.
vim: expandtab sw=4 ts=4 sts=4:
**********************************************************************/
if(!strcasecmp(basename($_SERVER['SCRIPT_NAME']),basename(__FILE__))) die('kwaheri rafiki!');
$thisdir=str_replace('\\', '/', dirname(__FILE__)).'/';
if(!file_exists($thisdir.'main.inc.php')) die('Fatal Error.');
require_once($thisdir.'main.inc.php');
if(!defined('INCLUDE_DIR')) die('Fatal error');
/*Some more include defines specific to client only */
define('CLIENTINC_DIR',INCLUDE_DIR.'client/');
define('OSTCLIENTINC',TRUE);
define('ASSETS_PATH',ROOT_PATH.'assets/default/');
//Check the status of the HelpDesk.
if (!in_array(strtolower(basename($_SERVER['SCRIPT_NAME'])), array('logo.php',))
&& !(is_object($ost) && $ost->isSystemOnline())) {
include(ROOT_DIR.'offline.php');
exit;
}
/* include what is needed on client stuff */
require_once(INCLUDE_DIR.'class.client.php');
require_once(INCLUDE_DIR.'class.ticket.php');
require_once(INCLUDE_DIR.'class.dept.php');
//clear some vars
$errors=array();
$msg='';
$nav=null;
//Make sure the user is valid..before doing anything else.
$thisclient = UserAuthenticationBackend::getUser();
if (isset($_GET['lang']) && $_GET['lang']) {
if (Internationalization::getLanguageInfo($_GET['lang']))
$_SESSION['client:lang'] = $_GET['lang'];
}
// Bootstrap gettext translations as early as possible, but after attempting
// to sign on the agent
TextDomain::configureForUser($thisclient);
//is the user logged in?
if($thisclient && $thisclient->getId() && $thisclient->isValid()){
$thisclient->refreshSession();
} else {
$thisclient = null;
}
/******* CSRF Protectin *************/
// Enforce CSRF protection for POSTS
if ($_POST && !$ost->checkCSRFToken()) {
Http::redirect('index.php');
//just incase redirect fails
die('Action denied (400)!');
}
//Add token to the header - used on ajax calls [DO NOT CHANGE THE NAME]
$ost->addExtraHeader('<meta name="csrf_token" content="'.$ost->getCSRFToken().'" />');
/* Client specific defaults */
define('PAGE_LIMIT', DEFAULT_PAGE_LIMIT);
$nav = new UserNav($thisclient, 'home');
$exempt = in_array(basename($_SERVER['SCRIPT_NAME']), array('logout.php', 'ajax.php', 'logs.php', 'upgrade.php'));
if (!$exempt && $thisclient && ($acct = $thisclient->getAccount())
&& $acct->isPasswdResetForced()) {
$warn = __('Password change required to continue');
require('profile.php'); //profile.php must request this file as require_once to avoid problems.
exit;
}
?>
|
b38b3ca7235002137cc9ff74b3c24a4a78c9c2d1
|
https://github.com/osticket/osticket-1.8
|
repo_delete.php
|
php
|
<?php
# Copyright (c) 2012 John Reese
# Licensed under the MIT license
form_security_validate( 'plugin_Source_repo_delete' );
access_ensure_global_level( plugin_config_get( 'manage_threshold' ) );
$f_repo_id = gpc_get_string( 'id' );
$t_repo = SourceRepo::load( $f_repo_id );
helper_ensure_confirmed( sprintf( plugin_lang_get( 'ensure_delete' ), $t_repo->name ), plugin_lang_get( 'delete_repository' ) );
SourceRepo::delete( $t_repo->id );
form_security_purge( 'plugin_Source_repo_delete' );
print_successful_redirect( plugin_page( 'index', true ) );
|
<?php
# Copyright (c) 2012 John Reese
# Licensed under the MIT license
form_security_validate( 'plugin_Source_repo_delete' );
access_ensure_global_level( plugin_config_get( 'manage_threshold' ) );
$f_repo_id = gpc_get_string( 'id' );
$t_repo = SourceRepo::load( $f_repo_id );
$t_message = sprintf( plugin_lang_get( 'ensure_delete' ), string_attribute( $t_repo->name ) );
helper_ensure_confirmed( $t_message, plugin_lang_get( 'delete_repository' ) );
SourceRepo::delete( $t_repo->id );
form_security_purge( 'plugin_Source_repo_delete' );
print_successful_redirect( plugin_page( 'index', true ) );
|
270675c964c675829fe010f9f0830521dc0835f0
|
https://github.com/mantisbt-plugins/source-integration
|
cfg80211.c
|
c
|
// SPDX-License-Identifier: GPL-2.0
/*
* Copyright (c) 2012 - 2018 Microchip Technology Inc., and its subsidiaries.
* All rights reserved.
*/
#include "cfg80211.h"
#define GO_NEG_REQ 0x00
#define GO_NEG_RSP 0x01
#define GO_NEG_CONF 0x02
#define P2P_INV_REQ 0x03
#define P2P_INV_RSP 0x04
#define WILC_INVALID_CHANNEL 0
/* Operation at 2.4 GHz with channels 1-13 */
#define WILC_WLAN_OPERATING_CLASS_2_4GHZ 0x51
static const struct ieee80211_txrx_stypes
wilc_wfi_cfg80211_mgmt_types[NUM_NL80211_IFTYPES] = {
[NL80211_IFTYPE_STATION] = {
.tx = BIT(IEEE80211_STYPE_ACTION >> 4) |
BIT(IEEE80211_STYPE_AUTH >> 4),
.rx = BIT(IEEE80211_STYPE_ACTION >> 4) |
BIT(IEEE80211_STYPE_PROBE_REQ >> 4) |
BIT(IEEE80211_STYPE_AUTH >> 4)
},
[NL80211_IFTYPE_AP] = {
.tx = 0xffff,
.rx = BIT(IEEE80211_STYPE_ASSOC_REQ >> 4) |
BIT(IEEE80211_STYPE_REASSOC_REQ >> 4) |
BIT(IEEE80211_STYPE_PROBE_REQ >> 4) |
BIT(IEEE80211_STYPE_DISASSOC >> 4) |
BIT(IEEE80211_STYPE_AUTH >> 4) |
BIT(IEEE80211_STYPE_DEAUTH >> 4) |
BIT(IEEE80211_STYPE_ACTION >> 4)
},
[NL80211_IFTYPE_P2P_CLIENT] = {
.tx = 0xffff,
.rx = BIT(IEEE80211_STYPE_ACTION >> 4) |
BIT(IEEE80211_STYPE_PROBE_REQ >> 4) |
BIT(IEEE80211_STYPE_ASSOC_REQ >> 4) |
BIT(IEEE80211_STYPE_REASSOC_REQ >> 4) |
BIT(IEEE80211_STYPE_DISASSOC >> 4) |
BIT(IEEE80211_STYPE_AUTH >> 4) |
BIT(IEEE80211_STYPE_DEAUTH >> 4)
}
};
#ifdef CONFIG_PM
static const struct wiphy_wowlan_support wowlan_support = {
.flags = WIPHY_WOWLAN_ANY
};
#endif
struct wilc_p2p_mgmt_data {
int size;
u8 *buff;
};
struct wilc_p2p_pub_act_frame {
u8 category;
u8 action;
u8 oui[3];
u8 oui_type;
u8 oui_subtype;
u8 dialog_token;
u8 elem[];
} __packed;
struct wilc_vendor_specific_ie {
u8 tag_number;
u8 tag_len;
u8 oui[3];
u8 oui_type;
u8 attr[];
} __packed;
struct wilc_attr_entry {
u8 attr_type;
__le16 attr_len;
u8 val[];
} __packed;
struct wilc_attr_oper_ch {
u8 attr_type;
__le16 attr_len;
u8 country_code[IEEE80211_COUNTRY_STRING_LEN];
u8 op_class;
u8 op_channel;
} __packed;
struct wilc_attr_ch_list {
u8 attr_type;
__le16 attr_len;
u8 country_code[IEEE80211_COUNTRY_STRING_LEN];
u8 elem[];
} __packed;
struct wilc_ch_list_elem {
u8 op_class;
u8 no_of_channels;
u8 ch_list[];
} __packed;
static void cfg_scan_result(enum scan_event scan_event,
struct wilc_rcvd_net_info *info, void *user_void)
{
struct wilc_priv *priv = user_void;
if (!priv->cfg_scanning)
return;
if (scan_event == SCAN_EVENT_NETWORK_FOUND) {
s32 freq;
struct ieee80211_channel *channel;
struct cfg80211_bss *bss;
struct wiphy *wiphy = priv->dev->ieee80211_ptr->wiphy;
if (!wiphy || !info)
return;
freq = ieee80211_channel_to_frequency((s32)info->ch,
NL80211_BAND_2GHZ);
channel = ieee80211_get_channel(wiphy, freq);
if (!channel)
return;
bss = cfg80211_inform_bss_frame(wiphy, channel, info->mgmt,
info->frame_len,
(s32)info->rssi * 100,
GFP_KERNEL);
cfg80211_put_bss(wiphy, bss);
} else if (scan_event == SCAN_EVENT_DONE) {
mutex_lock(&priv->scan_req_lock);
if (priv->scan_req) {
struct cfg80211_scan_info info = {
.aborted = false,
};
cfg80211_scan_done(priv->scan_req, &info);
priv->cfg_scanning = false;
priv->scan_req = NULL;
}
mutex_unlock(&priv->scan_req_lock);
} else if (scan_event == SCAN_EVENT_ABORTED) {
mutex_lock(&priv->scan_req_lock);
if (priv->scan_req) {
struct cfg80211_scan_info info = {
.aborted = false,
};
cfg80211_scan_done(priv->scan_req, &info);
priv->cfg_scanning = false;
priv->scan_req = NULL;
}
mutex_unlock(&priv->scan_req_lock);
}
}
static void cfg_connect_result(enum conn_event conn_disconn_evt, u8 mac_status,
void *priv_data)
{
struct wilc_priv *priv = priv_data;
struct net_device *dev = priv->dev;
struct wilc_vif *vif = netdev_priv(dev);
struct wilc *wl = vif->wilc;
struct host_if_drv *wfi_drv = priv->hif_drv;
struct wilc_conn_info *conn_info = &wfi_drv->conn_info;
struct wiphy *wiphy = dev->ieee80211_ptr->wiphy;
vif->connecting = false;
if (conn_disconn_evt == CONN_DISCONN_EVENT_CONN_RESP) {
u16 connect_status = conn_info->status;
if (mac_status == WILC_MAC_STATUS_DISCONNECTED &&
connect_status == WLAN_STATUS_SUCCESS) {
connect_status = WLAN_STATUS_UNSPECIFIED_FAILURE;
wilc_wlan_set_bssid(priv->dev, NULL, WILC_STATION_MODE);
if (vif->iftype != WILC_CLIENT_MODE)
wl->sta_ch = WILC_INVALID_CHANNEL;
netdev_err(dev, "Unspecified failure\n");
}
if (connect_status == WLAN_STATUS_SUCCESS)
memcpy(priv->associated_bss, conn_info->bssid,
ETH_ALEN);
cfg80211_ref_bss(wiphy, vif->bss);
cfg80211_connect_bss(dev, conn_info->bssid, vif->bss,
conn_info->req_ies,
conn_info->req_ies_len,
conn_info->resp_ies,
conn_info->resp_ies_len,
connect_status, GFP_KERNEL,
NL80211_TIMEOUT_UNSPECIFIED);
vif->bss = NULL;
} else if (conn_disconn_evt == CONN_DISCONN_EVENT_DISCONN_NOTIF) {
u16 reason = 0;
eth_zero_addr(priv->associated_bss);
wilc_wlan_set_bssid(priv->dev, NULL, WILC_STATION_MODE);
if (vif->iftype != WILC_CLIENT_MODE) {
wl->sta_ch = WILC_INVALID_CHANNEL;
} else {
if (wfi_drv->ifc_up)
reason = 3;
else
reason = 1;
}
cfg80211_disconnected(dev, reason, NULL, 0, false, GFP_KERNEL);
}
}
struct wilc_vif *wilc_get_wl_to_vif(struct wilc *wl)
{
struct wilc_vif *vif;
vif = list_first_or_null_rcu(&wl->vif_list, typeof(*vif), list);
if (!vif)
return ERR_PTR(-EINVAL);
return vif;
}
static int set_channel(struct wiphy *wiphy,
struct cfg80211_chan_def *chandef)
{
struct wilc *wl = wiphy_priv(wiphy);
struct wilc_vif *vif;
u32 channelnum;
int result;
int srcu_idx;
srcu_idx = srcu_read_lock(&wl->srcu);
vif = wilc_get_wl_to_vif(wl);
if (IS_ERR(vif)) {
srcu_read_unlock(&wl->srcu, srcu_idx);
return PTR_ERR(vif);
}
channelnum = ieee80211_frequency_to_channel(chandef->chan->center_freq);
wl->op_ch = channelnum;
result = wilc_set_mac_chnl_num(vif, channelnum);
if (result)
netdev_err(vif->ndev, "Error in setting channel\n");
srcu_read_unlock(&wl->srcu, srcu_idx);
return result;
}
static int scan(struct wiphy *wiphy, struct cfg80211_scan_request *request)
{
struct wilc_vif *vif = netdev_priv(request->wdev->netdev);
struct wilc_priv *priv = &vif->priv;
u32 i;
int ret = 0;
u8 scan_ch_list[WILC_MAX_NUM_SCANNED_CH];
u8 scan_type;
if (request->n_channels > WILC_MAX_NUM_SCANNED_CH) {
netdev_err(vif->ndev, "Requested scanned channels over\n");
return -EINVAL;
}
priv->scan_req = request;
priv->cfg_scanning = true;
for (i = 0; i < request->n_channels; i++) {
u16 freq = request->channels[i]->center_freq;
scan_ch_list[i] = ieee80211_frequency_to_channel(freq);
}
if (request->n_ssids)
scan_type = WILC_FW_ACTIVE_SCAN;
else
scan_type = WILC_FW_PASSIVE_SCAN;
ret = wilc_scan(vif, WILC_FW_USER_SCAN, scan_type, scan_ch_list,
request->n_channels, cfg_scan_result, (void *)priv,
request);
if (ret) {
priv->scan_req = NULL;
priv->cfg_scanning = false;
}
return ret;
}
static int connect(struct wiphy *wiphy, struct net_device *dev,
struct cfg80211_connect_params *sme)
{
struct wilc_vif *vif = netdev_priv(dev);
struct wilc_priv *priv = &vif->priv;
struct host_if_drv *wfi_drv = priv->hif_drv;
int ret;
u32 i;
u8 security = WILC_FW_SEC_NO;
enum mfptype mfp_type = WILC_FW_MFP_NONE;
enum authtype auth_type = WILC_FW_AUTH_ANY;
u32 cipher_group;
struct cfg80211_bss *bss;
void *join_params;
u8 ch;
vif->connecting = true;
cipher_group = sme->crypto.cipher_group;
if (cipher_group != 0) {
if (sme->crypto.wpa_versions & NL80211_WPA_VERSION_2) {
if (cipher_group == WLAN_CIPHER_SUITE_TKIP)
security = WILC_FW_SEC_WPA2_TKIP;
else
security = WILC_FW_SEC_WPA2_AES;
} else if (sme->crypto.wpa_versions & NL80211_WPA_VERSION_1) {
if (cipher_group == WLAN_CIPHER_SUITE_TKIP)
security = WILC_FW_SEC_WPA_TKIP;
else
security = WILC_FW_SEC_WPA_AES;
} else {
ret = -ENOTSUPP;
netdev_err(dev, "%s: Unsupported cipher\n",
__func__);
goto out_error;
}
}
if ((sme->crypto.wpa_versions & NL80211_WPA_VERSION_1) ||
(sme->crypto.wpa_versions & NL80211_WPA_VERSION_2)) {
for (i = 0; i < sme->crypto.n_ciphers_pairwise; i++) {
u32 ciphers_pairwise = sme->crypto.ciphers_pairwise[i];
if (ciphers_pairwise == WLAN_CIPHER_SUITE_TKIP)
security |= WILC_FW_TKIP;
else
security |= WILC_FW_AES;
}
}
switch (sme->auth_type) {
case NL80211_AUTHTYPE_OPEN_SYSTEM:
auth_type = WILC_FW_AUTH_OPEN_SYSTEM;
break;
case NL80211_AUTHTYPE_SAE:
auth_type = WILC_FW_AUTH_SAE;
if (sme->ssid_len) {
memcpy(vif->auth.ssid.ssid, sme->ssid, sme->ssid_len);
vif->auth.ssid.ssid_len = sme->ssid_len;
}
vif->auth.key_mgmt_suite = cpu_to_be32(sme->crypto.akm_suites[0]);
ether_addr_copy(vif->auth.bssid, sme->bssid);
break;
default:
break;
}
if (sme->crypto.n_akm_suites) {
if (sme->crypto.akm_suites[0] == WLAN_AKM_SUITE_8021X)
auth_type = WILC_FW_AUTH_IEEE8021;
else if (sme->crypto.akm_suites[0] == WLAN_AKM_SUITE_PSK_SHA256)
auth_type = WILC_FW_AUTH_OPEN_SYSTEM_SHA256;
else if (sme->crypto.akm_suites[0] == WLAN_AKM_SUITE_8021X_SHA256)
auth_type = WILC_FW_AUTH_IEE8021X_SHA256;
}
if (wfi_drv->usr_scan_req.scan_result) {
netdev_err(vif->ndev, "%s: Scan in progress\n", __func__);
ret = -EBUSY;
goto out_error;
}
bss = cfg80211_get_bss(wiphy, sme->channel, sme->bssid, sme->ssid,
sme->ssid_len, IEEE80211_BSS_TYPE_ANY,
IEEE80211_PRIVACY(sme->privacy));
if (!bss) {
ret = -EINVAL;
goto out_error;
}
if (ether_addr_equal_unaligned(vif->bssid, bss->bssid)) {
ret = -EALREADY;
goto out_put_bss;
}
join_params = wilc_parse_join_bss_param(bss, &sme->crypto);
if (!join_params) {
netdev_err(dev, "%s: failed to construct join param\n",
__func__);
ret = -EINVAL;
goto out_put_bss;
}
ch = ieee80211_frequency_to_channel(bss->channel->center_freq);
vif->wilc->op_ch = ch;
if (vif->iftype != WILC_CLIENT_MODE)
vif->wilc->sta_ch = ch;
wilc_wlan_set_bssid(dev, bss->bssid, WILC_STATION_MODE);
wfi_drv->conn_info.security = security;
wfi_drv->conn_info.auth_type = auth_type;
wfi_drv->conn_info.ch = ch;
wfi_drv->conn_info.conn_result = cfg_connect_result;
wfi_drv->conn_info.arg = priv;
wfi_drv->conn_info.param = join_params;
if (sme->mfp == NL80211_MFP_OPTIONAL)
mfp_type = WILC_FW_MFP_OPTIONAL;
else if (sme->mfp == NL80211_MFP_REQUIRED)
mfp_type = WILC_FW_MFP_REQUIRED;
wfi_drv->conn_info.mfp_type = mfp_type;
ret = wilc_set_join_req(vif, bss->bssid, sme->ie, sme->ie_len);
if (ret) {
netdev_err(dev, "wilc_set_join_req(): Error\n");
ret = -ENOENT;
if (vif->iftype != WILC_CLIENT_MODE)
vif->wilc->sta_ch = WILC_INVALID_CHANNEL;
wilc_wlan_set_bssid(dev, NULL, WILC_STATION_MODE);
wfi_drv->conn_info.conn_result = NULL;
kfree(join_params);
goto out_put_bss;
}
kfree(join_params);
vif->bss = bss;
cfg80211_put_bss(wiphy, bss);
return 0;
out_put_bss:
cfg80211_put_bss(wiphy, bss);
out_error:
vif->connecting = false;
return ret;
}
static int disconnect(struct wiphy *wiphy, struct net_device *dev,
u16 reason_code)
{
struct wilc_vif *vif = netdev_priv(dev);
struct wilc_priv *priv = &vif->priv;
struct wilc *wilc = vif->wilc;
int ret;
vif->connecting = false;
if (!wilc)
return -EIO;
if (wilc->close) {
/* already disconnected done */
cfg80211_disconnected(dev, 0, NULL, 0, true, GFP_KERNEL);
return 0;
}
if (vif->iftype != WILC_CLIENT_MODE)
wilc->sta_ch = WILC_INVALID_CHANNEL;
wilc_wlan_set_bssid(priv->dev, NULL, WILC_STATION_MODE);
priv->hif_drv->p2p_timeout = 0;
ret = wilc_disconnect(vif);
if (ret != 0) {
netdev_err(priv->dev, "Error in disconnecting\n");
ret = -EINVAL;
}
vif->bss = NULL;
return ret;
}
static int wilc_wfi_cfg_allocate_wpa_entry(struct wilc_priv *priv, u8 idx)
{
if (!priv->wilc_gtk[idx]) {
priv->wilc_gtk[idx] = kzalloc(sizeof(*priv->wilc_gtk[idx]),
GFP_KERNEL);
if (!priv->wilc_gtk[idx])
return -ENOMEM;
}
if (!priv->wilc_ptk[idx]) {
priv->wilc_ptk[idx] = kzalloc(sizeof(*priv->wilc_ptk[idx]),
GFP_KERNEL);
if (!priv->wilc_ptk[idx])
return -ENOMEM;
}
return 0;
}
static int wilc_wfi_cfg_allocate_wpa_igtk_entry(struct wilc_priv *priv, u8 idx)
{
idx -= 4;
if (!priv->wilc_igtk[idx]) {
priv->wilc_igtk[idx] = kzalloc(sizeof(*priv->wilc_igtk[idx]),
GFP_KERNEL);
if (!priv->wilc_igtk[idx])
return -ENOMEM;
}
return 0;
}
static int wilc_wfi_cfg_copy_wpa_info(struct wilc_wfi_key *key_info,
struct key_params *params)
{
kfree(key_info->key);
key_info->key = kmemdup(params->key, params->key_len, GFP_KERNEL);
if (!key_info->key)
return -ENOMEM;
kfree(key_info->seq);
if (params->seq_len > 0) {
key_info->seq = kmemdup(params->seq, params->seq_len,
GFP_KERNEL);
if (!key_info->seq)
return -ENOMEM;
}
key_info->cipher = params->cipher;
key_info->key_len = params->key_len;
key_info->seq_len = params->seq_len;
return 0;
}
static int add_key(struct wiphy *wiphy, struct net_device *netdev, int link_id,
u8 key_index, bool pairwise, const u8 *mac_addr,
struct key_params *params)
{
int ret = 0, keylen = params->key_len;
const u8 *rx_mic = NULL;
const u8 *tx_mic = NULL;
u8 mode = WILC_FW_SEC_NO;
u8 op_mode;
struct wilc_vif *vif = netdev_priv(netdev);
struct wilc_priv *priv = &vif->priv;
struct wilc_wfi_key *key;
switch (params->cipher) {
case WLAN_CIPHER_SUITE_TKIP:
case WLAN_CIPHER_SUITE_CCMP:
if (priv->wdev.iftype == NL80211_IFTYPE_AP ||
priv->wdev.iftype == NL80211_IFTYPE_P2P_GO) {
struct wilc_wfi_key *key;
ret = wilc_wfi_cfg_allocate_wpa_entry(priv, key_index);
if (ret)
return -ENOMEM;
if (params->key_len > 16 &&
params->cipher == WLAN_CIPHER_SUITE_TKIP) {
tx_mic = params->key + 24;
rx_mic = params->key + 16;
keylen = params->key_len - 16;
}
if (!pairwise) {
if (params->cipher == WLAN_CIPHER_SUITE_TKIP)
mode = WILC_FW_SEC_WPA_TKIP;
else
mode = WILC_FW_SEC_WPA2_AES;
priv->wilc_groupkey = mode;
key = priv->wilc_gtk[key_index];
} else {
if (params->cipher == WLAN_CIPHER_SUITE_TKIP)
mode = WILC_FW_SEC_WPA_TKIP;
else
mode = priv->wilc_groupkey | WILC_FW_AES;
key = priv->wilc_ptk[key_index];
}
ret = wilc_wfi_cfg_copy_wpa_info(key, params);
if (ret)
return -ENOMEM;
op_mode = WILC_AP_MODE;
} else {
if (params->key_len > 16 &&
params->cipher == WLAN_CIPHER_SUITE_TKIP) {
rx_mic = params->key + 24;
tx_mic = params->key + 16;
keylen = params->key_len - 16;
}
op_mode = WILC_STATION_MODE;
}
if (!pairwise)
ret = wilc_add_rx_gtk(vif, params->key, keylen,
key_index, params->seq_len,
params->seq, rx_mic, tx_mic,
op_mode, mode);
else
ret = wilc_add_ptk(vif, params->key, keylen, mac_addr,
rx_mic, tx_mic, op_mode, mode,
key_index);
break;
case WLAN_CIPHER_SUITE_AES_CMAC:
ret = wilc_wfi_cfg_allocate_wpa_igtk_entry(priv, key_index);
if (ret)
return -ENOMEM;
key = priv->wilc_igtk[key_index - 4];
ret = wilc_wfi_cfg_copy_wpa_info(key, params);
if (ret)
return -ENOMEM;
if (priv->wdev.iftype == NL80211_IFTYPE_AP ||
priv->wdev.iftype == NL80211_IFTYPE_P2P_GO)
op_mode = WILC_AP_MODE;
else
op_mode = WILC_STATION_MODE;
ret = wilc_add_igtk(vif, params->key, keylen, params->seq,
params->seq_len, mac_addr, op_mode,
key_index);
break;
default:
netdev_err(netdev, "%s: Unsupported cipher\n", __func__);
ret = -ENOTSUPP;
}
return ret;
}
static int del_key(struct wiphy *wiphy, struct net_device *netdev, int link_id,
u8 key_index,
bool pairwise,
const u8 *mac_addr)
{
struct wilc_vif *vif = netdev_priv(netdev);
struct wilc_priv *priv = &vif->priv;
if (!pairwise && (key_index == 4 || key_index == 5)) {
key_index -= 4;
if (priv->wilc_igtk[key_index]) {
kfree(priv->wilc_igtk[key_index]->key);
priv->wilc_igtk[key_index]->key = NULL;
kfree(priv->wilc_igtk[key_index]->seq);
priv->wilc_igtk[key_index]->seq = NULL;
kfree(priv->wilc_igtk[key_index]);
priv->wilc_igtk[key_index] = NULL;
}
} else {
if (priv->wilc_gtk[key_index]) {
kfree(priv->wilc_gtk[key_index]->key);
priv->wilc_gtk[key_index]->key = NULL;
kfree(priv->wilc_gtk[key_index]->seq);
priv->wilc_gtk[key_index]->seq = NULL;
kfree(priv->wilc_gtk[key_index]);
priv->wilc_gtk[key_index] = NULL;
}
if (priv->wilc_ptk[key_index]) {
kfree(priv->wilc_ptk[key_index]->key);
priv->wilc_ptk[key_index]->key = NULL;
kfree(priv->wilc_ptk[key_index]->seq);
priv->wilc_ptk[key_index]->seq = NULL;
kfree(priv->wilc_ptk[key_index]);
priv->wilc_ptk[key_index] = NULL;
}
}
return 0;
}
static int get_key(struct wiphy *wiphy, struct net_device *netdev, int link_id,
u8 key_index, bool pairwise, const u8 *mac_addr,
void *cookie,
void (*callback)(void *cookie, struct key_params *))
{
struct wilc_vif *vif = netdev_priv(netdev);
struct wilc_priv *priv = &vif->priv;
struct key_params key_params;
if (!pairwise) {
if (key_index == 4 || key_index == 5) {
key_index -= 4;
key_params.key = priv->wilc_igtk[key_index]->key;
key_params.cipher = priv->wilc_igtk[key_index]->cipher;
key_params.key_len = priv->wilc_igtk[key_index]->key_len;
key_params.seq = priv->wilc_igtk[key_index]->seq;
key_params.seq_len = priv->wilc_igtk[key_index]->seq_len;
} else {
key_params.key = priv->wilc_gtk[key_index]->key;
key_params.cipher = priv->wilc_gtk[key_index]->cipher;
key_params.key_len = priv->wilc_gtk[key_index]->key_len;
key_params.seq = priv->wilc_gtk[key_index]->seq;
key_params.seq_len = priv->wilc_gtk[key_index]->seq_len;
}
} else {
key_params.key = priv->wilc_ptk[key_index]->key;
key_params.cipher = priv->wilc_ptk[key_index]->cipher;
key_params.key_len = priv->wilc_ptk[key_index]->key_len;
key_params.seq = priv->wilc_ptk[key_index]->seq;
key_params.seq_len = priv->wilc_ptk[key_index]->seq_len;
}
callback(cookie, &key_params);
return 0;
}
/* wiphy_new_nm() will WARNON if not present */
static int set_default_key(struct wiphy *wiphy, struct net_device *netdev,
int link_id, u8 key_index, bool unicast,
bool multicast)
{
return 0;
}
static int set_default_mgmt_key(struct wiphy *wiphy, struct net_device *netdev,
int link_id, u8 key_index)
{
struct wilc_vif *vif = netdev_priv(netdev);
return wilc_set_default_mgmt_key_index(vif, key_index);
}
static int get_station(struct wiphy *wiphy, struct net_device *dev,
const u8 *mac, struct station_info *sinfo)
{
struct wilc_vif *vif = netdev_priv(dev);
struct wilc_priv *priv = &vif->priv;
struct wilc *wilc = vif->wilc;
u32 i = 0;
u32 associatedsta = ~0;
u32 inactive_time = 0;
if (vif->iftype == WILC_AP_MODE || vif->iftype == WILC_GO_MODE) {
for (i = 0; i < NUM_STA_ASSOCIATED; i++) {
if (!(memcmp(mac,
priv->assoc_stainfo.sta_associated_bss[i],
ETH_ALEN))) {
associatedsta = i;
break;
}
}
if (associatedsta == ~0) {
netdev_err(dev, "sta required is not associated\n");
return -ENOENT;
}
sinfo->filled |= BIT_ULL(NL80211_STA_INFO_INACTIVE_TIME);
wilc_get_inactive_time(vif, mac, &inactive_time);
sinfo->inactive_time = 1000 * inactive_time;
} else if (vif->iftype == WILC_STATION_MODE) {
struct rf_info stats;
if (!wilc->initialized)
return -EBUSY;
wilc_get_statistics(vif, &stats);
sinfo->filled |= BIT_ULL(NL80211_STA_INFO_SIGNAL) |
BIT_ULL(NL80211_STA_INFO_RX_PACKETS) |
BIT_ULL(NL80211_STA_INFO_TX_PACKETS) |
BIT_ULL(NL80211_STA_INFO_TX_FAILED) |
BIT_ULL(NL80211_STA_INFO_TX_BITRATE);
sinfo->signal = stats.rssi;
sinfo->rx_packets = stats.rx_cnt;
sinfo->tx_packets = stats.tx_cnt + stats.tx_fail_cnt;
sinfo->tx_failed = stats.tx_fail_cnt;
sinfo->txrate.legacy = stats.link_speed * 10;
if (stats.link_speed > TCP_ACK_FILTER_LINK_SPEED_THRESH &&
stats.link_speed != DEFAULT_LINK_SPEED)
wilc_enable_tcp_ack_filter(vif, true);
else if (stats.link_speed != DEFAULT_LINK_SPEED)
wilc_enable_tcp_ack_filter(vif, false);
}
return 0;
}
static int change_bss(struct wiphy *wiphy, struct net_device *dev,
struct bss_parameters *params)
{
return 0;
}
static int set_wiphy_params(struct wiphy *wiphy, u32 changed)
{
int ret = -EINVAL;
struct cfg_param_attr cfg_param_val;
struct wilc *wl = wiphy_priv(wiphy);
struct wilc_vif *vif;
struct wilc_priv *priv;
int srcu_idx;
srcu_idx = srcu_read_lock(&wl->srcu);
vif = wilc_get_wl_to_vif(wl);
if (IS_ERR(vif))
goto out;
priv = &vif->priv;
cfg_param_val.flag = 0;
if (changed & WIPHY_PARAM_RETRY_SHORT) {
netdev_dbg(vif->ndev,
"Setting WIPHY_PARAM_RETRY_SHORT %d\n",
wiphy->retry_short);
cfg_param_val.flag |= WILC_CFG_PARAM_RETRY_SHORT;
cfg_param_val.short_retry_limit = wiphy->retry_short;
}
if (changed & WIPHY_PARAM_RETRY_LONG) {
netdev_dbg(vif->ndev,
"Setting WIPHY_PARAM_RETRY_LONG %d\n",
wiphy->retry_long);
cfg_param_val.flag |= WILC_CFG_PARAM_RETRY_LONG;
cfg_param_val.long_retry_limit = wiphy->retry_long;
}
if (changed & WIPHY_PARAM_FRAG_THRESHOLD) {
if (wiphy->frag_threshold > 255 &&
wiphy->frag_threshold < 7937) {
netdev_dbg(vif->ndev,
"Setting WIPHY_PARAM_FRAG_THRESHOLD %d\n",
wiphy->frag_threshold);
cfg_param_val.flag |= WILC_CFG_PARAM_FRAG_THRESHOLD;
cfg_param_val.frag_threshold = wiphy->frag_threshold;
} else {
netdev_err(vif->ndev,
"Fragmentation threshold out of range\n");
goto out;
}
}
if (changed & WIPHY_PARAM_RTS_THRESHOLD) {
if (wiphy->rts_threshold > 255) {
netdev_dbg(vif->ndev,
"Setting WIPHY_PARAM_RTS_THRESHOLD %d\n",
wiphy->rts_threshold);
cfg_param_val.flag |= WILC_CFG_PARAM_RTS_THRESHOLD;
cfg_param_val.rts_threshold = wiphy->rts_threshold;
} else {
netdev_err(vif->ndev, "RTS threshold out of range\n");
goto out;
}
}
ret = wilc_hif_set_cfg(vif, &cfg_param_val);
if (ret)
netdev_err(priv->dev, "Error in setting WIPHY PARAMS\n");
out:
srcu_read_unlock(&wl->srcu, srcu_idx);
return ret;
}
static int set_pmksa(struct wiphy *wiphy, struct net_device *netdev,
struct cfg80211_pmksa *pmksa)
{
struct wilc_vif *vif = netdev_priv(netdev);
struct wilc_priv *priv = &vif->priv;
u32 i;
int ret = 0;
u8 flag = 0;
for (i = 0; i < priv->pmkid_list.numpmkid; i++) {
if (!memcmp(pmksa->bssid, priv->pmkid_list.pmkidlist[i].bssid,
ETH_ALEN)) {
flag = PMKID_FOUND;
break;
}
}
if (i < WILC_MAX_NUM_PMKIDS) {
memcpy(priv->pmkid_list.pmkidlist[i].bssid, pmksa->bssid,
ETH_ALEN);
memcpy(priv->pmkid_list.pmkidlist[i].pmkid, pmksa->pmkid,
WLAN_PMKID_LEN);
if (!(flag == PMKID_FOUND))
priv->pmkid_list.numpmkid++;
} else {
netdev_err(netdev, "Invalid PMKID index\n");
ret = -EINVAL;
}
if (!ret)
ret = wilc_set_pmkid_info(vif, &priv->pmkid_list);
return ret;
}
static int del_pmksa(struct wiphy *wiphy, struct net_device *netdev,
struct cfg80211_pmksa *pmksa)
{
u32 i;
struct wilc_vif *vif = netdev_priv(netdev);
struct wilc_priv *priv = &vif->priv;
for (i = 0; i < priv->pmkid_list.numpmkid; i++) {
if (!memcmp(pmksa->bssid, priv->pmkid_list.pmkidlist[i].bssid,
ETH_ALEN)) {
memset(&priv->pmkid_list.pmkidlist[i], 0,
sizeof(struct wilc_pmkid));
break;
}
}
if (i == priv->pmkid_list.numpmkid)
return -EINVAL;
for (; i < (priv->pmkid_list.numpmkid - 1); i++) {
memcpy(priv->pmkid_list.pmkidlist[i].bssid,
priv->pmkid_list.pmkidlist[i + 1].bssid,
ETH_ALEN);
memcpy(priv->pmkid_list.pmkidlist[i].pmkid,
priv->pmkid_list.pmkidlist[i + 1].pmkid,
WLAN_PMKID_LEN);
}
priv->pmkid_list.numpmkid--;
return 0;
}
static int flush_pmksa(struct wiphy *wiphy, struct net_device *netdev)
{
struct wilc_vif *vif = netdev_priv(netdev);
memset(&vif->priv.pmkid_list, 0, sizeof(struct wilc_pmkid_attr));
return 0;
}
static inline void wilc_wfi_cfg_parse_ch_attr(u8 *buf, u32 len, u8 sta_ch)
{
struct wilc_attr_entry *e;
struct wilc_attr_ch_list *ch_list;
struct wilc_attr_oper_ch *op_ch;
u32 index = 0;
u8 ch_list_idx = 0;
u8 op_ch_idx = 0;
if (sta_ch == WILC_INVALID_CHANNEL)
return;
while (index + sizeof(*e) <= len) {
u16 attr_size;
e = (struct wilc_attr_entry *)&buf[index];
attr_size = le16_to_cpu(e->attr_len);
if (index + sizeof(*e) + attr_size > len)
return;
if (e->attr_type == IEEE80211_P2P_ATTR_CHANNEL_LIST)
ch_list_idx = index;
else if (e->attr_type == IEEE80211_P2P_ATTR_OPER_CHANNEL &&
attr_size == (sizeof(struct wilc_attr_oper_ch) - sizeof(*e)))
op_ch_idx = index;
if (ch_list_idx && op_ch_idx)
break;
index += sizeof(*e) + attr_size;
}
if (ch_list_idx) {
u16 attr_size;
struct wilc_ch_list_elem *e;
int i;
ch_list = (struct wilc_attr_ch_list *)&buf[ch_list_idx];
attr_size = le16_to_cpu(ch_list->attr_len);
for (i = 0; i < attr_size;) {
e = (struct wilc_ch_list_elem *)(ch_list->elem + i);
if (e->op_class == WILC_WLAN_OPERATING_CLASS_2_4GHZ) {
memset(e->ch_list, sta_ch, e->no_of_channels);
break;
}
i += e->no_of_channels;
}
}
if (op_ch_idx) {
op_ch = (struct wilc_attr_oper_ch *)&buf[op_ch_idx];
op_ch->op_class = WILC_WLAN_OPERATING_CLASS_2_4GHZ;
op_ch->op_channel = sta_ch;
}
}
bool wilc_wfi_mgmt_frame_rx(struct wilc_vif *vif, u8 *buff, u32 size)
{
struct wilc *wl = vif->wilc;
struct wilc_priv *priv = &vif->priv;
int freq;
freq = ieee80211_channel_to_frequency(wl->op_ch, NL80211_BAND_2GHZ);
return cfg80211_rx_mgmt(&priv->wdev, freq, 0, buff, size, 0);
}
void wilc_wfi_p2p_rx(struct wilc_vif *vif, u8 *buff, u32 size)
{
struct wilc *wl = vif->wilc;
struct wilc_priv *priv = &vif->priv;
struct host_if_drv *wfi_drv = priv->hif_drv;
struct ieee80211_mgmt *mgmt;
struct wilc_vendor_specific_ie *p;
struct wilc_p2p_pub_act_frame *d;
int ie_offset = offsetof(struct ieee80211_mgmt, u) + sizeof(*d);
const u8 *vendor_ie;
u32 header, pkt_offset;
s32 freq;
header = get_unaligned_le32(buff - HOST_HDR_OFFSET);
pkt_offset = FIELD_GET(WILC_PKT_HDR_OFFSET_FIELD, header);
if (pkt_offset & IS_MANAGMEMENT_CALLBACK) {
bool ack = false;
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)buff;
if (ieee80211_is_probe_resp(hdr->frame_control) ||
pkt_offset & IS_MGMT_STATUS_SUCCES)
ack = true;
cfg80211_mgmt_tx_status(&priv->wdev, priv->tx_cookie, buff,
size, ack, GFP_KERNEL);
return;
}
freq = ieee80211_channel_to_frequency(wl->op_ch, NL80211_BAND_2GHZ);
mgmt = (struct ieee80211_mgmt *)buff;
if (!ieee80211_is_action(mgmt->frame_control))
goto out_rx_mgmt;
if (priv->cfg_scanning &&
time_after_eq(jiffies, (unsigned long)wfi_drv->p2p_timeout)) {
netdev_dbg(vif->ndev, "Receiving action wrong ch\n");
return;
}
if (!ieee80211_is_public_action((struct ieee80211_hdr *)buff, size))
goto out_rx_mgmt;
d = (struct wilc_p2p_pub_act_frame *)(&mgmt->u.action);
if (d->oui_subtype != GO_NEG_REQ && d->oui_subtype != GO_NEG_RSP &&
d->oui_subtype != P2P_INV_REQ && d->oui_subtype != P2P_INV_RSP)
goto out_rx_mgmt;
vendor_ie = cfg80211_find_vendor_ie(WLAN_OUI_WFA, WLAN_OUI_TYPE_WFA_P2P,
buff + ie_offset, size - ie_offset);
if (!vendor_ie)
goto out_rx_mgmt;
p = (struct wilc_vendor_specific_ie *)vendor_ie;
wilc_wfi_cfg_parse_ch_attr(p->attr, p->tag_len - 4, vif->wilc->sta_ch);
out_rx_mgmt:
cfg80211_rx_mgmt(&priv->wdev, freq, 0, buff, size, 0);
}
static void wilc_wfi_mgmt_tx_complete(void *priv, int status)
{
struct wilc_p2p_mgmt_data *pv_data = priv;
kfree(pv_data->buff);
kfree(pv_data);
}
static void wilc_wfi_remain_on_channel_expired(void *data, u64 cookie)
{
struct wilc_vif *vif = data;
struct wilc_priv *priv = &vif->priv;
struct wilc_wfi_p2p_listen_params *params = &priv->remain_on_ch_params;
if (cookie != params->listen_cookie)
return;
priv->p2p_listen_state = false;
cfg80211_remain_on_channel_expired(&priv->wdev, params->listen_cookie,
params->listen_ch, GFP_KERNEL);
}
static int remain_on_channel(struct wiphy *wiphy,
struct wireless_dev *wdev,
struct ieee80211_channel *chan,
unsigned int duration, u64 *cookie)
{
int ret = 0;
struct wilc_vif *vif = netdev_priv(wdev->netdev);
struct wilc_priv *priv = &vif->priv;
u64 id;
if (wdev->iftype == NL80211_IFTYPE_AP) {
netdev_dbg(vif->ndev, "Required while in AP mode\n");
return ret;
}
id = ++priv->inc_roc_cookie;
if (id == 0)
id = ++priv->inc_roc_cookie;
ret = wilc_remain_on_channel(vif, id, duration, chan->hw_value,
wilc_wfi_remain_on_channel_expired,
(void *)vif);
if (ret)
return ret;
vif->wilc->op_ch = chan->hw_value;
priv->remain_on_ch_params.listen_ch = chan;
priv->remain_on_ch_params.listen_cookie = id;
*cookie = id;
priv->p2p_listen_state = true;
priv->remain_on_ch_params.listen_duration = duration;
cfg80211_ready_on_channel(wdev, *cookie, chan, duration, GFP_KERNEL);
mod_timer(&vif->hif_drv->remain_on_ch_timer,
jiffies + msecs_to_jiffies(duration + 1000));
return ret;
}
static int cancel_remain_on_channel(struct wiphy *wiphy,
struct wireless_dev *wdev,
u64 cookie)
{
struct wilc_vif *vif = netdev_priv(wdev->netdev);
struct wilc_priv *priv = &vif->priv;
if (cookie != priv->remain_on_ch_params.listen_cookie)
return -ENOENT;
return wilc_listen_state_expired(vif, cookie);
}
static int mgmt_tx(struct wiphy *wiphy,
struct wireless_dev *wdev,
struct cfg80211_mgmt_tx_params *params,
u64 *cookie)
{
struct ieee80211_channel *chan = params->chan;
unsigned int wait = params->wait;
const u8 *buf = params->buf;
size_t len = params->len;
const struct ieee80211_mgmt *mgmt;
struct wilc_p2p_mgmt_data *mgmt_tx;
struct wilc_vif *vif = netdev_priv(wdev->netdev);
struct wilc_priv *priv = &vif->priv;
struct host_if_drv *wfi_drv = priv->hif_drv;
struct wilc_vendor_specific_ie *p;
struct wilc_p2p_pub_act_frame *d;
int ie_offset = offsetof(struct ieee80211_mgmt, u) + sizeof(*d);
const u8 *vendor_ie;
int ret = 0;
*cookie = get_random_u32();
priv->tx_cookie = *cookie;
mgmt = (const struct ieee80211_mgmt *)buf;
if (!ieee80211_is_mgmt(mgmt->frame_control))
goto out;
mgmt_tx = kmalloc(sizeof(*mgmt_tx), GFP_KERNEL);
if (!mgmt_tx) {
ret = -ENOMEM;
goto out;
}
mgmt_tx->buff = kmemdup(buf, len, GFP_KERNEL);
if (!mgmt_tx->buff) {
ret = -ENOMEM;
kfree(mgmt_tx);
goto out;
}
mgmt_tx->size = len;
if (ieee80211_is_probe_resp(mgmt->frame_control)) {
wilc_set_mac_chnl_num(vif, chan->hw_value);
vif->wilc->op_ch = chan->hw_value;
goto out_txq_add_pkt;
}
if (!ieee80211_is_public_action((struct ieee80211_hdr *)buf, len)) {
if (chan)
wilc_set_mac_chnl_num(vif, chan->hw_value);
else
wilc_set_mac_chnl_num(vif, vif->wilc->op_ch);
goto out_set_timeout;
}
d = (struct wilc_p2p_pub_act_frame *)(&mgmt->u.action);
if (d->oui_type != WLAN_OUI_TYPE_WFA_P2P ||
d->oui_subtype != GO_NEG_CONF) {
wilc_set_mac_chnl_num(vif, chan->hw_value);
vif->wilc->op_ch = chan->hw_value;
}
if (d->oui_subtype != P2P_INV_REQ && d->oui_subtype != P2P_INV_RSP)
goto out_set_timeout;
vendor_ie = cfg80211_find_vendor_ie(WLAN_OUI_WFA, WLAN_OUI_TYPE_WFA_P2P,
mgmt_tx->buff + ie_offset,
len - ie_offset);
if (!vendor_ie)
goto out_set_timeout;
p = (struct wilc_vendor_specific_ie *)vendor_ie;
wilc_wfi_cfg_parse_ch_attr(p->attr, p->tag_len - 4, vif->wilc->sta_ch);
out_set_timeout:
wfi_drv->p2p_timeout = (jiffies + msecs_to_jiffies(wait));
out_txq_add_pkt:
wilc_wlan_txq_add_mgmt_pkt(wdev->netdev, mgmt_tx,
mgmt_tx->buff, mgmt_tx->size,
wilc_wfi_mgmt_tx_complete);
out:
return ret;
}
static int mgmt_tx_cancel_wait(struct wiphy *wiphy,
struct wireless_dev *wdev,
u64 cookie)
{
struct wilc_vif *vif = netdev_priv(wdev->netdev);
struct wilc_priv *priv = &vif->priv;
struct host_if_drv *wfi_drv = priv->hif_drv;
wfi_drv->p2p_timeout = jiffies;
if (!priv->p2p_listen_state) {
struct wilc_wfi_p2p_listen_params *params;
params = &priv->remain_on_ch_params;
cfg80211_remain_on_channel_expired(wdev,
params->listen_cookie,
params->listen_ch,
GFP_KERNEL);
}
return 0;
}
void wilc_update_mgmt_frame_registrations(struct wiphy *wiphy,
struct wireless_dev *wdev,
struct mgmt_frame_regs *upd)
{
struct wilc *wl = wiphy_priv(wiphy);
struct wilc_vif *vif = netdev_priv(wdev->netdev);
u32 presp_bit = BIT(IEEE80211_STYPE_PROBE_REQ >> 4);
u32 action_bit = BIT(IEEE80211_STYPE_ACTION >> 4);
u32 pauth_bit = BIT(IEEE80211_STYPE_AUTH >> 4);
if (wl->initialized) {
bool prev = vif->mgmt_reg_stypes & presp_bit;
bool now = upd->interface_stypes & presp_bit;
if (now != prev)
wilc_frame_register(vif, IEEE80211_STYPE_PROBE_REQ, now);
prev = vif->mgmt_reg_stypes & action_bit;
now = upd->interface_stypes & action_bit;
if (now != prev)
wilc_frame_register(vif, IEEE80211_STYPE_ACTION, now);
prev = vif->mgmt_reg_stypes & pauth_bit;
now = upd->interface_stypes & pauth_bit;
if (now != prev)
wilc_frame_register(vif, IEEE80211_STYPE_AUTH, now);
}
vif->mgmt_reg_stypes =
upd->interface_stypes & (presp_bit | action_bit | pauth_bit);
}
static int external_auth(struct wiphy *wiphy, struct net_device *dev,
struct cfg80211_external_auth_params *auth)
{
struct wilc_vif *vif = netdev_priv(dev);
if (auth->status == WLAN_STATUS_SUCCESS)
wilc_set_external_auth_param(vif, auth);
return 0;
}
static int set_cqm_rssi_config(struct wiphy *wiphy, struct net_device *dev,
s32 rssi_thold, u32 rssi_hyst)
{
return 0;
}
static int dump_station(struct wiphy *wiphy, struct net_device *dev,
int idx, u8 *mac, struct station_info *sinfo)
{
struct wilc_vif *vif = netdev_priv(dev);
int ret;
if (idx != 0)
return -ENOENT;
ret = wilc_get_rssi(vif, &sinfo->signal);
if (ret)
return ret;
sinfo->filled |= BIT_ULL(NL80211_STA_INFO_SIGNAL);
memcpy(mac, vif->priv.associated_bss, ETH_ALEN);
return 0;
}
static int set_power_mgmt(struct wiphy *wiphy, struct net_device *dev,
bool enabled, int timeout)
{
struct wilc_vif *vif = netdev_priv(dev);
struct wilc_priv *priv = &vif->priv;
if (!priv->hif_drv)
return -EIO;
wilc_set_power_mgmt(vif, enabled, timeout);
return 0;
}
static int change_virtual_intf(struct wiphy *wiphy, struct net_device *dev,
enum nl80211_iftype type,
struct vif_params *params)
{
struct wilc *wl = wiphy_priv(wiphy);
struct wilc_vif *vif = netdev_priv(dev);
struct wilc_priv *priv = &vif->priv;
switch (type) {
case NL80211_IFTYPE_STATION:
vif->connecting = false;
dev->ieee80211_ptr->iftype = type;
priv->wdev.iftype = type;
vif->monitor_flag = 0;
if (vif->iftype == WILC_AP_MODE || vif->iftype == WILC_GO_MODE)
wilc_wfi_deinit_mon_interface(wl, true);
vif->iftype = WILC_STATION_MODE;
if (wl->initialized)
wilc_set_operation_mode(vif, wilc_get_vif_idx(vif),
WILC_STATION_MODE, vif->idx);
memset(priv->assoc_stainfo.sta_associated_bss, 0,
WILC_MAX_NUM_STA * ETH_ALEN);
break;
case NL80211_IFTYPE_P2P_CLIENT:
vif->connecting = false;
dev->ieee80211_ptr->iftype = type;
priv->wdev.iftype = type;
vif->monitor_flag = 0;
vif->iftype = WILC_CLIENT_MODE;
if (wl->initialized)
wilc_set_operation_mode(vif, wilc_get_vif_idx(vif),
WILC_STATION_MODE, vif->idx);
break;
case NL80211_IFTYPE_AP:
dev->ieee80211_ptr->iftype = type;
priv->wdev.iftype = type;
vif->iftype = WILC_AP_MODE;
if (wl->initialized)
wilc_set_operation_mode(vif, wilc_get_vif_idx(vif),
WILC_AP_MODE, vif->idx);
break;
case NL80211_IFTYPE_P2P_GO:
dev->ieee80211_ptr->iftype = type;
priv->wdev.iftype = type;
vif->iftype = WILC_GO_MODE;
if (wl->initialized)
wilc_set_operation_mode(vif, wilc_get_vif_idx(vif),
WILC_AP_MODE, vif->idx);
break;
default:
netdev_err(dev, "Unknown interface type= %d\n", type);
return -EINVAL;
}
return 0;
}
static int start_ap(struct wiphy *wiphy, struct net_device *dev,
struct cfg80211_ap_settings *settings)
{
struct wilc_vif *vif = netdev_priv(dev);
int ret;
ret = set_channel(wiphy, &settings->chandef);
if (ret != 0)
netdev_err(dev, "Error in setting channel\n");
wilc_wlan_set_bssid(dev, dev->dev_addr, WILC_AP_MODE);
return wilc_add_beacon(vif, settings->beacon_interval,
settings->dtim_period, &settings->beacon);
}
static int change_beacon(struct wiphy *wiphy, struct net_device *dev,
struct cfg80211_beacon_data *beacon)
{
struct wilc_vif *vif = netdev_priv(dev);
return wilc_add_beacon(vif, 0, 0, beacon);
}
static int stop_ap(struct wiphy *wiphy, struct net_device *dev,
unsigned int link_id)
{
int ret;
struct wilc_vif *vif = netdev_priv(dev);
wilc_wlan_set_bssid(dev, NULL, WILC_AP_MODE);
ret = wilc_del_beacon(vif);
if (ret)
netdev_err(dev, "Host delete beacon fail\n");
return ret;
}
static int add_station(struct wiphy *wiphy, struct net_device *dev,
const u8 *mac, struct station_parameters *params)
{
int ret = 0;
struct wilc_vif *vif = netdev_priv(dev);
struct wilc_priv *priv = &vif->priv;
if (vif->iftype == WILC_AP_MODE || vif->iftype == WILC_GO_MODE) {
memcpy(priv->assoc_stainfo.sta_associated_bss[params->aid], mac,
ETH_ALEN);
ret = wilc_add_station(vif, mac, params);
if (ret)
netdev_err(dev, "Host add station fail\n");
}
return ret;
}
static int del_station(struct wiphy *wiphy, struct net_device *dev,
struct station_del_parameters *params)
{
const u8 *mac = params->mac;
int ret = 0;
struct wilc_vif *vif = netdev_priv(dev);
struct wilc_priv *priv = &vif->priv;
struct sta_info *info;
if (!(vif->iftype == WILC_AP_MODE || vif->iftype == WILC_GO_MODE))
return ret;
info = &priv->assoc_stainfo;
if (!mac)
ret = wilc_del_allstation(vif, info->sta_associated_bss);
ret = wilc_del_station(vif, mac);
if (ret)
netdev_err(dev, "Host delete station fail\n");
return ret;
}
static int change_station(struct wiphy *wiphy, struct net_device *dev,
const u8 *mac, struct station_parameters *params)
{
int ret = 0;
struct wilc_vif *vif = netdev_priv(dev);
if (vif->iftype == WILC_AP_MODE || vif->iftype == WILC_GO_MODE) {
ret = wilc_edit_station(vif, mac, params);
if (ret)
netdev_err(dev, "Host edit station fail\n");
}
return ret;
}
static struct wilc_vif *wilc_get_vif_from_type(struct wilc *wl, int type)
{
struct wilc_vif *vif;
list_for_each_entry_rcu(vif, &wl->vif_list, list) {
if (vif->iftype == type)
return vif;
}
return NULL;
}
static struct wireless_dev *add_virtual_intf(struct wiphy *wiphy,
const char *name,
unsigned char name_assign_type,
enum nl80211_iftype type,
struct vif_params *params)
{
struct wilc *wl = wiphy_priv(wiphy);
struct wilc_vif *vif;
struct wireless_dev *wdev;
int iftype;
if (type == NL80211_IFTYPE_MONITOR) {
struct net_device *ndev;
int srcu_idx;
srcu_idx = srcu_read_lock(&wl->srcu);
vif = wilc_get_vif_from_type(wl, WILC_AP_MODE);
if (!vif) {
vif = wilc_get_vif_from_type(wl, WILC_GO_MODE);
if (!vif) {
srcu_read_unlock(&wl->srcu, srcu_idx);
goto validate_interface;
}
}
if (vif->monitor_flag) {
srcu_read_unlock(&wl->srcu, srcu_idx);
goto validate_interface;
}
ndev = wilc_wfi_init_mon_interface(wl, name, vif->ndev);
if (ndev) {
vif->monitor_flag = 1;
} else {
srcu_read_unlock(&wl->srcu, srcu_idx);
return ERR_PTR(-EINVAL);
}
wdev = &vif->priv.wdev;
srcu_read_unlock(&wl->srcu, srcu_idx);
return wdev;
}
validate_interface:
mutex_lock(&wl->vif_mutex);
if (wl->vif_num == WILC_NUM_CONCURRENT_IFC) {
pr_err("Reached maximum number of interface\n");
mutex_unlock(&wl->vif_mutex);
return ERR_PTR(-EINVAL);
}
mutex_unlock(&wl->vif_mutex);
switch (type) {
case NL80211_IFTYPE_STATION:
iftype = WILC_STATION_MODE;
break;
case NL80211_IFTYPE_AP:
iftype = WILC_AP_MODE;
break;
default:
return ERR_PTR(-EOPNOTSUPP);
}
vif = wilc_netdev_ifc_init(wl, name, iftype, type, true);
if (IS_ERR(vif))
return ERR_CAST(vif);
return &vif->priv.wdev;
}
static int del_virtual_intf(struct wiphy *wiphy, struct wireless_dev *wdev)
{
struct wilc *wl = wiphy_priv(wiphy);
struct wilc_vif *vif;
if (wdev->iftype == NL80211_IFTYPE_AP ||
wdev->iftype == NL80211_IFTYPE_P2P_GO)
wilc_wfi_deinit_mon_interface(wl, true);
vif = netdev_priv(wdev->netdev);
cfg80211_stop_iface(wiphy, wdev, GFP_KERNEL);
cfg80211_unregister_netdevice(vif->ndev);
vif->monitor_flag = 0;
wilc_set_operation_mode(vif, 0, 0, 0);
mutex_lock(&wl->vif_mutex);
list_del_rcu(&vif->list);
wl->vif_num--;
mutex_unlock(&wl->vif_mutex);
synchronize_srcu(&wl->srcu);
return 0;
}
static int wilc_suspend(struct wiphy *wiphy, struct cfg80211_wowlan *wow)
{
struct wilc *wl = wiphy_priv(wiphy);
if (!wow && wilc_wlan_get_num_conn_ifcs(wl))
wl->suspend_event = true;
else
wl->suspend_event = false;
return 0;
}
static int wilc_resume(struct wiphy *wiphy)
{
return 0;
}
static void wilc_set_wakeup(struct wiphy *wiphy, bool enabled)
{
struct wilc *wl = wiphy_priv(wiphy);
struct wilc_vif *vif;
int srcu_idx;
srcu_idx = srcu_read_lock(&wl->srcu);
vif = wilc_get_wl_to_vif(wl);
if (IS_ERR(vif)) {
srcu_read_unlock(&wl->srcu, srcu_idx);
return;
}
netdev_info(vif->ndev, "cfg set wake up = %d\n", enabled);
wilc_set_wowlan_trigger(vif, enabled);
srcu_read_unlock(&wl->srcu, srcu_idx);
}
static int set_tx_power(struct wiphy *wiphy, struct wireless_dev *wdev,
enum nl80211_tx_power_setting type, int mbm)
{
int ret;
int srcu_idx;
s32 tx_power = MBM_TO_DBM(mbm);
struct wilc *wl = wiphy_priv(wiphy);
struct wilc_vif *vif;
if (!wl->initialized)
return -EIO;
srcu_idx = srcu_read_lock(&wl->srcu);
vif = wilc_get_wl_to_vif(wl);
if (IS_ERR(vif)) {
srcu_read_unlock(&wl->srcu, srcu_idx);
return -EINVAL;
}
netdev_info(vif->ndev, "Setting tx power %d\n", tx_power);
if (tx_power < 0)
tx_power = 0;
else if (tx_power > 18)
tx_power = 18;
ret = wilc_set_tx_power(vif, tx_power);
if (ret)
netdev_err(vif->ndev, "Failed to set tx power\n");
srcu_read_unlock(&wl->srcu, srcu_idx);
return ret;
}
static int get_tx_power(struct wiphy *wiphy, struct wireless_dev *wdev,
int *dbm)
{
int ret;
struct wilc_vif *vif = netdev_priv(wdev->netdev);
struct wilc *wl = vif->wilc;
/* If firmware is not started, return. */
if (!wl->initialized)
return -EIO;
ret = wilc_get_tx_power(vif, (u8 *)dbm);
if (ret)
netdev_err(vif->ndev, "Failed to get tx power\n");
return ret;
}
static const struct cfg80211_ops wilc_cfg80211_ops = {
.set_monitor_channel = set_channel,
.scan = scan,
.connect = connect,
.disconnect = disconnect,
.add_key = add_key,
.del_key = del_key,
.get_key = get_key,
.set_default_key = set_default_key,
.set_default_mgmt_key = set_default_mgmt_key,
.add_virtual_intf = add_virtual_intf,
.del_virtual_intf = del_virtual_intf,
.change_virtual_intf = change_virtual_intf,
.start_ap = start_ap,
.change_beacon = change_beacon,
.stop_ap = stop_ap,
.add_station = add_station,
.del_station = del_station,
.change_station = change_station,
.get_station = get_station,
.dump_station = dump_station,
.change_bss = change_bss,
.set_wiphy_params = set_wiphy_params,
.external_auth = external_auth,
.set_pmksa = set_pmksa,
.del_pmksa = del_pmksa,
.flush_pmksa = flush_pmksa,
.remain_on_channel = remain_on_channel,
.cancel_remain_on_channel = cancel_remain_on_channel,
.mgmt_tx_cancel_wait = mgmt_tx_cancel_wait,
.mgmt_tx = mgmt_tx,
.update_mgmt_frame_registrations = wilc_update_mgmt_frame_registrations,
.set_power_mgmt = set_power_mgmt,
.set_cqm_rssi_config = set_cqm_rssi_config,
.suspend = wilc_suspend,
.resume = wilc_resume,
.set_wakeup = wilc_set_wakeup,
.set_tx_power = set_tx_power,
.get_tx_power = get_tx_power,
};
static void wlan_init_locks(struct wilc *wl)
{
mutex_init(&wl->hif_cs);
mutex_init(&wl->rxq_cs);
mutex_init(&wl->cfg_cmd_lock);
mutex_init(&wl->vif_mutex);
mutex_init(&wl->deinit_lock);
spin_lock_init(&wl->txq_spinlock);
mutex_init(&wl->txq_add_to_head_cs);
init_completion(&wl->txq_event);
init_completion(&wl->cfg_event);
init_completion(&wl->sync_event);
init_completion(&wl->txq_thread_started);
init_srcu_struct(&wl->srcu);
}
void wlan_deinit_locks(struct wilc *wilc)
{
mutex_destroy(&wilc->hif_cs);
mutex_destroy(&wilc->rxq_cs);
mutex_destroy(&wilc->cfg_cmd_lock);
mutex_destroy(&wilc->txq_add_to_head_cs);
mutex_destroy(&wilc->vif_mutex);
mutex_destroy(&wilc->deinit_lock);
cleanup_srcu_struct(&wilc->srcu);
}
int wilc_cfg80211_init(struct wilc **wilc, struct device *dev, int io_type,
const struct wilc_hif_func *ops)
{
struct wilc *wl;
struct wilc_vif *vif;
int ret, i;
wl = wilc_create_wiphy(dev);
if (!wl)
return -EINVAL;
wlan_init_locks(wl);
ret = wilc_wlan_cfg_init(wl);
if (ret)
goto free_wl;
*wilc = wl;
wl->io_type = io_type;
wl->hif_func = ops;
for (i = 0; i < NQUEUES; i++)
INIT_LIST_HEAD(&wl->txq[i].txq_head.list);
INIT_LIST_HEAD(&wl->rxq_head.list);
INIT_LIST_HEAD(&wl->vif_list);
vif = wilc_netdev_ifc_init(wl, "wlan%d", WILC_STATION_MODE,
NL80211_IFTYPE_STATION, false);
if (IS_ERR(vif)) {
ret = PTR_ERR(vif);
goto free_cfg;
}
return 0;
free_cfg:
wilc_wlan_cfg_deinit(wl);
free_wl:
wlan_deinit_locks(wl);
wiphy_unregister(wl->wiphy);
wiphy_free(wl->wiphy);
return ret;
}
EXPORT_SYMBOL_GPL(wilc_cfg80211_init);
struct wilc *wilc_create_wiphy(struct device *dev)
{
struct wiphy *wiphy;
struct wilc *wl;
int ret;
wiphy = wiphy_new(&wilc_cfg80211_ops, sizeof(*wl));
if (!wiphy)
return NULL;
wl = wiphy_priv(wiphy);
memcpy(wl->bitrates, wilc_bitrates, sizeof(wilc_bitrates));
memcpy(wl->channels, wilc_2ghz_channels, sizeof(wilc_2ghz_channels));
wl->band.bitrates = wl->bitrates;
wl->band.n_bitrates = ARRAY_SIZE(wl->bitrates);
wl->band.channels = wl->channels;
wl->band.n_channels = ARRAY_SIZE(wilc_2ghz_channels);
wl->band.ht_cap.ht_supported = 1;
wl->band.ht_cap.cap |= (1 << IEEE80211_HT_CAP_RX_STBC_SHIFT);
wl->band.ht_cap.mcs.rx_mask[0] = 0xff;
wl->band.ht_cap.ampdu_factor = IEEE80211_HT_MAX_AMPDU_8K;
wl->band.ht_cap.ampdu_density = IEEE80211_HT_MPDU_DENSITY_NONE;
wiphy->bands[NL80211_BAND_2GHZ] = &wl->band;
wiphy->max_scan_ssids = WILC_MAX_NUM_PROBED_SSID;
#ifdef CONFIG_PM
wiphy->wowlan = &wowlan_support;
#endif
wiphy->max_num_pmkids = WILC_MAX_NUM_PMKIDS;
wiphy->max_scan_ie_len = 1000;
wiphy->signal_type = CFG80211_SIGNAL_TYPE_MBM;
memcpy(wl->cipher_suites, wilc_cipher_suites,
sizeof(wilc_cipher_suites));
wiphy->cipher_suites = wl->cipher_suites;
wiphy->n_cipher_suites = ARRAY_SIZE(wilc_cipher_suites);
wiphy->mgmt_stypes = wilc_wfi_cfg80211_mgmt_types;
wiphy->max_remain_on_channel_duration = 500;
wiphy->interface_modes = BIT(NL80211_IFTYPE_STATION) |
BIT(NL80211_IFTYPE_AP) |
BIT(NL80211_IFTYPE_MONITOR) |
BIT(NL80211_IFTYPE_P2P_GO) |
BIT(NL80211_IFTYPE_P2P_CLIENT);
wiphy->flags |= WIPHY_FLAG_HAS_REMAIN_ON_CHANNEL;
wiphy->features |= NL80211_FEATURE_SAE;
set_wiphy_dev(wiphy, dev);
wl->wiphy = wiphy;
ret = wiphy_register(wiphy);
if (ret) {
wiphy_free(wiphy);
return NULL;
}
return wl;
}
int wilc_init_host_int(struct net_device *net)
{
int ret;
struct wilc_vif *vif = netdev_priv(net);
struct wilc_priv *priv = &vif->priv;
priv->p2p_listen_state = false;
mutex_init(&priv->scan_req_lock);
ret = wilc_init(net, &priv->hif_drv);
if (ret)
netdev_err(net, "Error while initializing hostinterface\n");
return ret;
}
void wilc_deinit_host_int(struct net_device *net)
{
int ret;
struct wilc_vif *vif = netdev_priv(net);
struct wilc_priv *priv = &vif->priv;
priv->p2p_listen_state = false;
flush_workqueue(vif->wilc->hif_workqueue);
mutex_destroy(&priv->scan_req_lock);
ret = wilc_deinit(vif);
if (ret)
netdev_err(net, "Error while deinitializing host interface\n");
}
|
// SPDX-License-Identifier: GPL-2.0
/*
* Copyright (c) 2012 - 2018 Microchip Technology Inc., and its subsidiaries.
* All rights reserved.
*/
#include "cfg80211.h"
#define GO_NEG_REQ 0x00
#define GO_NEG_RSP 0x01
#define GO_NEG_CONF 0x02
#define P2P_INV_REQ 0x03
#define P2P_INV_RSP 0x04
#define WILC_INVALID_CHANNEL 0
/* Operation at 2.4 GHz with channels 1-13 */
#define WILC_WLAN_OPERATING_CLASS_2_4GHZ 0x51
static const struct ieee80211_txrx_stypes
wilc_wfi_cfg80211_mgmt_types[NUM_NL80211_IFTYPES] = {
[NL80211_IFTYPE_STATION] = {
.tx = BIT(IEEE80211_STYPE_ACTION >> 4) |
BIT(IEEE80211_STYPE_AUTH >> 4),
.rx = BIT(IEEE80211_STYPE_ACTION >> 4) |
BIT(IEEE80211_STYPE_PROBE_REQ >> 4) |
BIT(IEEE80211_STYPE_AUTH >> 4)
},
[NL80211_IFTYPE_AP] = {
.tx = 0xffff,
.rx = BIT(IEEE80211_STYPE_ASSOC_REQ >> 4) |
BIT(IEEE80211_STYPE_REASSOC_REQ >> 4) |
BIT(IEEE80211_STYPE_PROBE_REQ >> 4) |
BIT(IEEE80211_STYPE_DISASSOC >> 4) |
BIT(IEEE80211_STYPE_AUTH >> 4) |
BIT(IEEE80211_STYPE_DEAUTH >> 4) |
BIT(IEEE80211_STYPE_ACTION >> 4)
},
[NL80211_IFTYPE_P2P_CLIENT] = {
.tx = 0xffff,
.rx = BIT(IEEE80211_STYPE_ACTION >> 4) |
BIT(IEEE80211_STYPE_PROBE_REQ >> 4) |
BIT(IEEE80211_STYPE_ASSOC_REQ >> 4) |
BIT(IEEE80211_STYPE_REASSOC_REQ >> 4) |
BIT(IEEE80211_STYPE_DISASSOC >> 4) |
BIT(IEEE80211_STYPE_AUTH >> 4) |
BIT(IEEE80211_STYPE_DEAUTH >> 4)
}
};
#ifdef CONFIG_PM
static const struct wiphy_wowlan_support wowlan_support = {
.flags = WIPHY_WOWLAN_ANY
};
#endif
struct wilc_p2p_mgmt_data {
int size;
u8 *buff;
};
struct wilc_p2p_pub_act_frame {
u8 category;
u8 action;
u8 oui[3];
u8 oui_type;
u8 oui_subtype;
u8 dialog_token;
u8 elem[];
} __packed;
struct wilc_vendor_specific_ie {
u8 tag_number;
u8 tag_len;
u8 oui[3];
u8 oui_type;
u8 attr[];
} __packed;
struct wilc_attr_entry {
u8 attr_type;
__le16 attr_len;
u8 val[];
} __packed;
struct wilc_attr_oper_ch {
u8 attr_type;
__le16 attr_len;
u8 country_code[IEEE80211_COUNTRY_STRING_LEN];
u8 op_class;
u8 op_channel;
} __packed;
struct wilc_attr_ch_list {
u8 attr_type;
__le16 attr_len;
u8 country_code[IEEE80211_COUNTRY_STRING_LEN];
u8 elem[];
} __packed;
struct wilc_ch_list_elem {
u8 op_class;
u8 no_of_channels;
u8 ch_list[];
} __packed;
static void cfg_scan_result(enum scan_event scan_event,
struct wilc_rcvd_net_info *info, void *user_void)
{
struct wilc_priv *priv = user_void;
if (!priv->cfg_scanning)
return;
if (scan_event == SCAN_EVENT_NETWORK_FOUND) {
s32 freq;
struct ieee80211_channel *channel;
struct cfg80211_bss *bss;
struct wiphy *wiphy = priv->dev->ieee80211_ptr->wiphy;
if (!wiphy || !info)
return;
freq = ieee80211_channel_to_frequency((s32)info->ch,
NL80211_BAND_2GHZ);
channel = ieee80211_get_channel(wiphy, freq);
if (!channel)
return;
bss = cfg80211_inform_bss_frame(wiphy, channel, info->mgmt,
info->frame_len,
(s32)info->rssi * 100,
GFP_KERNEL);
cfg80211_put_bss(wiphy, bss);
} else if (scan_event == SCAN_EVENT_DONE) {
mutex_lock(&priv->scan_req_lock);
if (priv->scan_req) {
struct cfg80211_scan_info info = {
.aborted = false,
};
cfg80211_scan_done(priv->scan_req, &info);
priv->cfg_scanning = false;
priv->scan_req = NULL;
}
mutex_unlock(&priv->scan_req_lock);
} else if (scan_event == SCAN_EVENT_ABORTED) {
mutex_lock(&priv->scan_req_lock);
if (priv->scan_req) {
struct cfg80211_scan_info info = {
.aborted = false,
};
cfg80211_scan_done(priv->scan_req, &info);
priv->cfg_scanning = false;
priv->scan_req = NULL;
}
mutex_unlock(&priv->scan_req_lock);
}
}
static void cfg_connect_result(enum conn_event conn_disconn_evt, u8 mac_status,
void *priv_data)
{
struct wilc_priv *priv = priv_data;
struct net_device *dev = priv->dev;
struct wilc_vif *vif = netdev_priv(dev);
struct wilc *wl = vif->wilc;
struct host_if_drv *wfi_drv = priv->hif_drv;
struct wilc_conn_info *conn_info = &wfi_drv->conn_info;
struct wiphy *wiphy = dev->ieee80211_ptr->wiphy;
vif->connecting = false;
if (conn_disconn_evt == CONN_DISCONN_EVENT_CONN_RESP) {
u16 connect_status = conn_info->status;
if (mac_status == WILC_MAC_STATUS_DISCONNECTED &&
connect_status == WLAN_STATUS_SUCCESS) {
connect_status = WLAN_STATUS_UNSPECIFIED_FAILURE;
wilc_wlan_set_bssid(priv->dev, NULL, WILC_STATION_MODE);
if (vif->iftype != WILC_CLIENT_MODE)
wl->sta_ch = WILC_INVALID_CHANNEL;
netdev_err(dev, "Unspecified failure\n");
}
if (connect_status == WLAN_STATUS_SUCCESS)
memcpy(priv->associated_bss, conn_info->bssid,
ETH_ALEN);
cfg80211_ref_bss(wiphy, vif->bss);
cfg80211_connect_bss(dev, conn_info->bssid, vif->bss,
conn_info->req_ies,
conn_info->req_ies_len,
conn_info->resp_ies,
conn_info->resp_ies_len,
connect_status, GFP_KERNEL,
NL80211_TIMEOUT_UNSPECIFIED);
vif->bss = NULL;
} else if (conn_disconn_evt == CONN_DISCONN_EVENT_DISCONN_NOTIF) {
u16 reason = 0;
eth_zero_addr(priv->associated_bss);
wilc_wlan_set_bssid(priv->dev, NULL, WILC_STATION_MODE);
if (vif->iftype != WILC_CLIENT_MODE) {
wl->sta_ch = WILC_INVALID_CHANNEL;
} else {
if (wfi_drv->ifc_up)
reason = 3;
else
reason = 1;
}
cfg80211_disconnected(dev, reason, NULL, 0, false, GFP_KERNEL);
}
}
struct wilc_vif *wilc_get_wl_to_vif(struct wilc *wl)
{
struct wilc_vif *vif;
vif = list_first_or_null_rcu(&wl->vif_list, typeof(*vif), list);
if (!vif)
return ERR_PTR(-EINVAL);
return vif;
}
static int set_channel(struct wiphy *wiphy,
struct cfg80211_chan_def *chandef)
{
struct wilc *wl = wiphy_priv(wiphy);
struct wilc_vif *vif;
u32 channelnum;
int result;
int srcu_idx;
srcu_idx = srcu_read_lock(&wl->srcu);
vif = wilc_get_wl_to_vif(wl);
if (IS_ERR(vif)) {
srcu_read_unlock(&wl->srcu, srcu_idx);
return PTR_ERR(vif);
}
channelnum = ieee80211_frequency_to_channel(chandef->chan->center_freq);
wl->op_ch = channelnum;
result = wilc_set_mac_chnl_num(vif, channelnum);
if (result)
netdev_err(vif->ndev, "Error in setting channel\n");
srcu_read_unlock(&wl->srcu, srcu_idx);
return result;
}
static int scan(struct wiphy *wiphy, struct cfg80211_scan_request *request)
{
struct wilc_vif *vif = netdev_priv(request->wdev->netdev);
struct wilc_priv *priv = &vif->priv;
u32 i;
int ret = 0;
u8 scan_ch_list[WILC_MAX_NUM_SCANNED_CH];
u8 scan_type;
if (request->n_channels > WILC_MAX_NUM_SCANNED_CH) {
netdev_err(vif->ndev, "Requested scanned channels over\n");
return -EINVAL;
}
priv->scan_req = request;
priv->cfg_scanning = true;
for (i = 0; i < request->n_channels; i++) {
u16 freq = request->channels[i]->center_freq;
scan_ch_list[i] = ieee80211_frequency_to_channel(freq);
}
if (request->n_ssids)
scan_type = WILC_FW_ACTIVE_SCAN;
else
scan_type = WILC_FW_PASSIVE_SCAN;
ret = wilc_scan(vif, WILC_FW_USER_SCAN, scan_type, scan_ch_list,
request->n_channels, cfg_scan_result, (void *)priv,
request);
if (ret) {
priv->scan_req = NULL;
priv->cfg_scanning = false;
}
return ret;
}
static int connect(struct wiphy *wiphy, struct net_device *dev,
struct cfg80211_connect_params *sme)
{
struct wilc_vif *vif = netdev_priv(dev);
struct wilc_priv *priv = &vif->priv;
struct host_if_drv *wfi_drv = priv->hif_drv;
int ret;
u32 i;
u8 security = WILC_FW_SEC_NO;
enum mfptype mfp_type = WILC_FW_MFP_NONE;
enum authtype auth_type = WILC_FW_AUTH_ANY;
u32 cipher_group;
struct cfg80211_bss *bss;
void *join_params;
u8 ch;
vif->connecting = true;
cipher_group = sme->crypto.cipher_group;
if (cipher_group != 0) {
if (sme->crypto.wpa_versions & NL80211_WPA_VERSION_2) {
if (cipher_group == WLAN_CIPHER_SUITE_TKIP)
security = WILC_FW_SEC_WPA2_TKIP;
else
security = WILC_FW_SEC_WPA2_AES;
} else if (sme->crypto.wpa_versions & NL80211_WPA_VERSION_1) {
if (cipher_group == WLAN_CIPHER_SUITE_TKIP)
security = WILC_FW_SEC_WPA_TKIP;
else
security = WILC_FW_SEC_WPA_AES;
} else {
ret = -ENOTSUPP;
netdev_err(dev, "%s: Unsupported cipher\n",
__func__);
goto out_error;
}
}
if ((sme->crypto.wpa_versions & NL80211_WPA_VERSION_1) ||
(sme->crypto.wpa_versions & NL80211_WPA_VERSION_2)) {
for (i = 0; i < sme->crypto.n_ciphers_pairwise; i++) {
u32 ciphers_pairwise = sme->crypto.ciphers_pairwise[i];
if (ciphers_pairwise == WLAN_CIPHER_SUITE_TKIP)
security |= WILC_FW_TKIP;
else
security |= WILC_FW_AES;
}
}
switch (sme->auth_type) {
case NL80211_AUTHTYPE_OPEN_SYSTEM:
auth_type = WILC_FW_AUTH_OPEN_SYSTEM;
break;
case NL80211_AUTHTYPE_SAE:
auth_type = WILC_FW_AUTH_SAE;
if (sme->ssid_len) {
memcpy(vif->auth.ssid.ssid, sme->ssid, sme->ssid_len);
vif->auth.ssid.ssid_len = sme->ssid_len;
}
vif->auth.key_mgmt_suite = cpu_to_be32(sme->crypto.akm_suites[0]);
ether_addr_copy(vif->auth.bssid, sme->bssid);
break;
default:
break;
}
if (sme->crypto.n_akm_suites) {
if (sme->crypto.akm_suites[0] == WLAN_AKM_SUITE_8021X)
auth_type = WILC_FW_AUTH_IEEE8021;
else if (sme->crypto.akm_suites[0] == WLAN_AKM_SUITE_PSK_SHA256)
auth_type = WILC_FW_AUTH_OPEN_SYSTEM_SHA256;
else if (sme->crypto.akm_suites[0] == WLAN_AKM_SUITE_8021X_SHA256)
auth_type = WILC_FW_AUTH_IEE8021X_SHA256;
}
if (wfi_drv->usr_scan_req.scan_result) {
netdev_err(vif->ndev, "%s: Scan in progress\n", __func__);
ret = -EBUSY;
goto out_error;
}
bss = cfg80211_get_bss(wiphy, sme->channel, sme->bssid, sme->ssid,
sme->ssid_len, IEEE80211_BSS_TYPE_ANY,
IEEE80211_PRIVACY(sme->privacy));
if (!bss) {
ret = -EINVAL;
goto out_error;
}
if (ether_addr_equal_unaligned(vif->bssid, bss->bssid)) {
ret = -EALREADY;
goto out_put_bss;
}
join_params = wilc_parse_join_bss_param(bss, &sme->crypto);
if (!join_params) {
netdev_err(dev, "%s: failed to construct join param\n",
__func__);
ret = -EINVAL;
goto out_put_bss;
}
ch = ieee80211_frequency_to_channel(bss->channel->center_freq);
vif->wilc->op_ch = ch;
if (vif->iftype != WILC_CLIENT_MODE)
vif->wilc->sta_ch = ch;
wilc_wlan_set_bssid(dev, bss->bssid, WILC_STATION_MODE);
wfi_drv->conn_info.security = security;
wfi_drv->conn_info.auth_type = auth_type;
wfi_drv->conn_info.ch = ch;
wfi_drv->conn_info.conn_result = cfg_connect_result;
wfi_drv->conn_info.arg = priv;
wfi_drv->conn_info.param = join_params;
if (sme->mfp == NL80211_MFP_OPTIONAL)
mfp_type = WILC_FW_MFP_OPTIONAL;
else if (sme->mfp == NL80211_MFP_REQUIRED)
mfp_type = WILC_FW_MFP_REQUIRED;
wfi_drv->conn_info.mfp_type = mfp_type;
ret = wilc_set_join_req(vif, bss->bssid, sme->ie, sme->ie_len);
if (ret) {
netdev_err(dev, "wilc_set_join_req(): Error\n");
ret = -ENOENT;
if (vif->iftype != WILC_CLIENT_MODE)
vif->wilc->sta_ch = WILC_INVALID_CHANNEL;
wilc_wlan_set_bssid(dev, NULL, WILC_STATION_MODE);
wfi_drv->conn_info.conn_result = NULL;
kfree(join_params);
goto out_put_bss;
}
kfree(join_params);
vif->bss = bss;
cfg80211_put_bss(wiphy, bss);
return 0;
out_put_bss:
cfg80211_put_bss(wiphy, bss);
out_error:
vif->connecting = false;
return ret;
}
static int disconnect(struct wiphy *wiphy, struct net_device *dev,
u16 reason_code)
{
struct wilc_vif *vif = netdev_priv(dev);
struct wilc_priv *priv = &vif->priv;
struct wilc *wilc = vif->wilc;
int ret;
vif->connecting = false;
if (!wilc)
return -EIO;
if (wilc->close) {
/* already disconnected done */
cfg80211_disconnected(dev, 0, NULL, 0, true, GFP_KERNEL);
return 0;
}
if (vif->iftype != WILC_CLIENT_MODE)
wilc->sta_ch = WILC_INVALID_CHANNEL;
wilc_wlan_set_bssid(priv->dev, NULL, WILC_STATION_MODE);
priv->hif_drv->p2p_timeout = 0;
ret = wilc_disconnect(vif);
if (ret != 0) {
netdev_err(priv->dev, "Error in disconnecting\n");
ret = -EINVAL;
}
vif->bss = NULL;
return ret;
}
static int wilc_wfi_cfg_allocate_wpa_entry(struct wilc_priv *priv, u8 idx)
{
if (!priv->wilc_gtk[idx]) {
priv->wilc_gtk[idx] = kzalloc(sizeof(*priv->wilc_gtk[idx]),
GFP_KERNEL);
if (!priv->wilc_gtk[idx])
return -ENOMEM;
}
if (!priv->wilc_ptk[idx]) {
priv->wilc_ptk[idx] = kzalloc(sizeof(*priv->wilc_ptk[idx]),
GFP_KERNEL);
if (!priv->wilc_ptk[idx])
return -ENOMEM;
}
return 0;
}
static int wilc_wfi_cfg_allocate_wpa_igtk_entry(struct wilc_priv *priv, u8 idx)
{
idx -= 4;
if (!priv->wilc_igtk[idx]) {
priv->wilc_igtk[idx] = kzalloc(sizeof(*priv->wilc_igtk[idx]),
GFP_KERNEL);
if (!priv->wilc_igtk[idx])
return -ENOMEM;
}
return 0;
}
static int wilc_wfi_cfg_copy_wpa_info(struct wilc_wfi_key *key_info,
struct key_params *params)
{
kfree(key_info->key);
key_info->key = kmemdup(params->key, params->key_len, GFP_KERNEL);
if (!key_info->key)
return -ENOMEM;
kfree(key_info->seq);
if (params->seq_len > 0) {
key_info->seq = kmemdup(params->seq, params->seq_len,
GFP_KERNEL);
if (!key_info->seq)
return -ENOMEM;
}
key_info->cipher = params->cipher;
key_info->key_len = params->key_len;
key_info->seq_len = params->seq_len;
return 0;
}
static int add_key(struct wiphy *wiphy, struct net_device *netdev, int link_id,
u8 key_index, bool pairwise, const u8 *mac_addr,
struct key_params *params)
{
int ret = 0, keylen = params->key_len;
const u8 *rx_mic = NULL;
const u8 *tx_mic = NULL;
u8 mode = WILC_FW_SEC_NO;
u8 op_mode;
struct wilc_vif *vif = netdev_priv(netdev);
struct wilc_priv *priv = &vif->priv;
struct wilc_wfi_key *key;
switch (params->cipher) {
case WLAN_CIPHER_SUITE_TKIP:
case WLAN_CIPHER_SUITE_CCMP:
if (priv->wdev.iftype == NL80211_IFTYPE_AP ||
priv->wdev.iftype == NL80211_IFTYPE_P2P_GO) {
struct wilc_wfi_key *key;
ret = wilc_wfi_cfg_allocate_wpa_entry(priv, key_index);
if (ret)
return -ENOMEM;
if (params->key_len > 16 &&
params->cipher == WLAN_CIPHER_SUITE_TKIP) {
tx_mic = params->key + 24;
rx_mic = params->key + 16;
keylen = params->key_len - 16;
}
if (!pairwise) {
if (params->cipher == WLAN_CIPHER_SUITE_TKIP)
mode = WILC_FW_SEC_WPA_TKIP;
else
mode = WILC_FW_SEC_WPA2_AES;
priv->wilc_groupkey = mode;
key = priv->wilc_gtk[key_index];
} else {
if (params->cipher == WLAN_CIPHER_SUITE_TKIP)
mode = WILC_FW_SEC_WPA_TKIP;
else
mode = priv->wilc_groupkey | WILC_FW_AES;
key = priv->wilc_ptk[key_index];
}
ret = wilc_wfi_cfg_copy_wpa_info(key, params);
if (ret)
return -ENOMEM;
op_mode = WILC_AP_MODE;
} else {
if (params->key_len > 16 &&
params->cipher == WLAN_CIPHER_SUITE_TKIP) {
rx_mic = params->key + 24;
tx_mic = params->key + 16;
keylen = params->key_len - 16;
}
op_mode = WILC_STATION_MODE;
}
if (!pairwise)
ret = wilc_add_rx_gtk(vif, params->key, keylen,
key_index, params->seq_len,
params->seq, rx_mic, tx_mic,
op_mode, mode);
else
ret = wilc_add_ptk(vif, params->key, keylen, mac_addr,
rx_mic, tx_mic, op_mode, mode,
key_index);
break;
case WLAN_CIPHER_SUITE_AES_CMAC:
ret = wilc_wfi_cfg_allocate_wpa_igtk_entry(priv, key_index);
if (ret)
return -ENOMEM;
key = priv->wilc_igtk[key_index - 4];
ret = wilc_wfi_cfg_copy_wpa_info(key, params);
if (ret)
return -ENOMEM;
if (priv->wdev.iftype == NL80211_IFTYPE_AP ||
priv->wdev.iftype == NL80211_IFTYPE_P2P_GO)
op_mode = WILC_AP_MODE;
else
op_mode = WILC_STATION_MODE;
ret = wilc_add_igtk(vif, params->key, keylen, params->seq,
params->seq_len, mac_addr, op_mode,
key_index);
break;
default:
netdev_err(netdev, "%s: Unsupported cipher\n", __func__);
ret = -ENOTSUPP;
}
return ret;
}
static int del_key(struct wiphy *wiphy, struct net_device *netdev, int link_id,
u8 key_index,
bool pairwise,
const u8 *mac_addr)
{
struct wilc_vif *vif = netdev_priv(netdev);
struct wilc_priv *priv = &vif->priv;
if (!pairwise && (key_index == 4 || key_index == 5)) {
key_index -= 4;
if (priv->wilc_igtk[key_index]) {
kfree(priv->wilc_igtk[key_index]->key);
priv->wilc_igtk[key_index]->key = NULL;
kfree(priv->wilc_igtk[key_index]->seq);
priv->wilc_igtk[key_index]->seq = NULL;
kfree(priv->wilc_igtk[key_index]);
priv->wilc_igtk[key_index] = NULL;
}
} else {
if (priv->wilc_gtk[key_index]) {
kfree(priv->wilc_gtk[key_index]->key);
priv->wilc_gtk[key_index]->key = NULL;
kfree(priv->wilc_gtk[key_index]->seq);
priv->wilc_gtk[key_index]->seq = NULL;
kfree(priv->wilc_gtk[key_index]);
priv->wilc_gtk[key_index] = NULL;
}
if (priv->wilc_ptk[key_index]) {
kfree(priv->wilc_ptk[key_index]->key);
priv->wilc_ptk[key_index]->key = NULL;
kfree(priv->wilc_ptk[key_index]->seq);
priv->wilc_ptk[key_index]->seq = NULL;
kfree(priv->wilc_ptk[key_index]);
priv->wilc_ptk[key_index] = NULL;
}
}
return 0;
}
static int get_key(struct wiphy *wiphy, struct net_device *netdev, int link_id,
u8 key_index, bool pairwise, const u8 *mac_addr,
void *cookie,
void (*callback)(void *cookie, struct key_params *))
{
struct wilc_vif *vif = netdev_priv(netdev);
struct wilc_priv *priv = &vif->priv;
struct key_params key_params;
if (!pairwise) {
if (key_index == 4 || key_index == 5) {
key_index -= 4;
key_params.key = priv->wilc_igtk[key_index]->key;
key_params.cipher = priv->wilc_igtk[key_index]->cipher;
key_params.key_len = priv->wilc_igtk[key_index]->key_len;
key_params.seq = priv->wilc_igtk[key_index]->seq;
key_params.seq_len = priv->wilc_igtk[key_index]->seq_len;
} else {
key_params.key = priv->wilc_gtk[key_index]->key;
key_params.cipher = priv->wilc_gtk[key_index]->cipher;
key_params.key_len = priv->wilc_gtk[key_index]->key_len;
key_params.seq = priv->wilc_gtk[key_index]->seq;
key_params.seq_len = priv->wilc_gtk[key_index]->seq_len;
}
} else {
key_params.key = priv->wilc_ptk[key_index]->key;
key_params.cipher = priv->wilc_ptk[key_index]->cipher;
key_params.key_len = priv->wilc_ptk[key_index]->key_len;
key_params.seq = priv->wilc_ptk[key_index]->seq;
key_params.seq_len = priv->wilc_ptk[key_index]->seq_len;
}
callback(cookie, &key_params);
return 0;
}
/* wiphy_new_nm() will WARNON if not present */
static int set_default_key(struct wiphy *wiphy, struct net_device *netdev,
int link_id, u8 key_index, bool unicast,
bool multicast)
{
return 0;
}
static int set_default_mgmt_key(struct wiphy *wiphy, struct net_device *netdev,
int link_id, u8 key_index)
{
struct wilc_vif *vif = netdev_priv(netdev);
return wilc_set_default_mgmt_key_index(vif, key_index);
}
static int get_station(struct wiphy *wiphy, struct net_device *dev,
const u8 *mac, struct station_info *sinfo)
{
struct wilc_vif *vif = netdev_priv(dev);
struct wilc_priv *priv = &vif->priv;
struct wilc *wilc = vif->wilc;
u32 i = 0;
u32 associatedsta = ~0;
u32 inactive_time = 0;
if (vif->iftype == WILC_AP_MODE || vif->iftype == WILC_GO_MODE) {
for (i = 0; i < NUM_STA_ASSOCIATED; i++) {
if (!(memcmp(mac,
priv->assoc_stainfo.sta_associated_bss[i],
ETH_ALEN))) {
associatedsta = i;
break;
}
}
if (associatedsta == ~0) {
netdev_err(dev, "sta required is not associated\n");
return -ENOENT;
}
sinfo->filled |= BIT_ULL(NL80211_STA_INFO_INACTIVE_TIME);
wilc_get_inactive_time(vif, mac, &inactive_time);
sinfo->inactive_time = 1000 * inactive_time;
} else if (vif->iftype == WILC_STATION_MODE) {
struct rf_info stats;
if (!wilc->initialized)
return -EBUSY;
wilc_get_statistics(vif, &stats);
sinfo->filled |= BIT_ULL(NL80211_STA_INFO_SIGNAL) |
BIT_ULL(NL80211_STA_INFO_RX_PACKETS) |
BIT_ULL(NL80211_STA_INFO_TX_PACKETS) |
BIT_ULL(NL80211_STA_INFO_TX_FAILED) |
BIT_ULL(NL80211_STA_INFO_TX_BITRATE);
sinfo->signal = stats.rssi;
sinfo->rx_packets = stats.rx_cnt;
sinfo->tx_packets = stats.tx_cnt + stats.tx_fail_cnt;
sinfo->tx_failed = stats.tx_fail_cnt;
sinfo->txrate.legacy = stats.link_speed * 10;
if (stats.link_speed > TCP_ACK_FILTER_LINK_SPEED_THRESH &&
stats.link_speed != DEFAULT_LINK_SPEED)
wilc_enable_tcp_ack_filter(vif, true);
else if (stats.link_speed != DEFAULT_LINK_SPEED)
wilc_enable_tcp_ack_filter(vif, false);
}
return 0;
}
static int change_bss(struct wiphy *wiphy, struct net_device *dev,
struct bss_parameters *params)
{
return 0;
}
static int set_wiphy_params(struct wiphy *wiphy, u32 changed)
{
int ret = -EINVAL;
struct cfg_param_attr cfg_param_val;
struct wilc *wl = wiphy_priv(wiphy);
struct wilc_vif *vif;
struct wilc_priv *priv;
int srcu_idx;
srcu_idx = srcu_read_lock(&wl->srcu);
vif = wilc_get_wl_to_vif(wl);
if (IS_ERR(vif))
goto out;
priv = &vif->priv;
cfg_param_val.flag = 0;
if (changed & WIPHY_PARAM_RETRY_SHORT) {
netdev_dbg(vif->ndev,
"Setting WIPHY_PARAM_RETRY_SHORT %d\n",
wiphy->retry_short);
cfg_param_val.flag |= WILC_CFG_PARAM_RETRY_SHORT;
cfg_param_val.short_retry_limit = wiphy->retry_short;
}
if (changed & WIPHY_PARAM_RETRY_LONG) {
netdev_dbg(vif->ndev,
"Setting WIPHY_PARAM_RETRY_LONG %d\n",
wiphy->retry_long);
cfg_param_val.flag |= WILC_CFG_PARAM_RETRY_LONG;
cfg_param_val.long_retry_limit = wiphy->retry_long;
}
if (changed & WIPHY_PARAM_FRAG_THRESHOLD) {
if (wiphy->frag_threshold > 255 &&
wiphy->frag_threshold < 7937) {
netdev_dbg(vif->ndev,
"Setting WIPHY_PARAM_FRAG_THRESHOLD %d\n",
wiphy->frag_threshold);
cfg_param_val.flag |= WILC_CFG_PARAM_FRAG_THRESHOLD;
cfg_param_val.frag_threshold = wiphy->frag_threshold;
} else {
netdev_err(vif->ndev,
"Fragmentation threshold out of range\n");
goto out;
}
}
if (changed & WIPHY_PARAM_RTS_THRESHOLD) {
if (wiphy->rts_threshold > 255) {
netdev_dbg(vif->ndev,
"Setting WIPHY_PARAM_RTS_THRESHOLD %d\n",
wiphy->rts_threshold);
cfg_param_val.flag |= WILC_CFG_PARAM_RTS_THRESHOLD;
cfg_param_val.rts_threshold = wiphy->rts_threshold;
} else {
netdev_err(vif->ndev, "RTS threshold out of range\n");
goto out;
}
}
ret = wilc_hif_set_cfg(vif, &cfg_param_val);
if (ret)
netdev_err(priv->dev, "Error in setting WIPHY PARAMS\n");
out:
srcu_read_unlock(&wl->srcu, srcu_idx);
return ret;
}
static int set_pmksa(struct wiphy *wiphy, struct net_device *netdev,
struct cfg80211_pmksa *pmksa)
{
struct wilc_vif *vif = netdev_priv(netdev);
struct wilc_priv *priv = &vif->priv;
u32 i;
int ret = 0;
u8 flag = 0;
for (i = 0; i < priv->pmkid_list.numpmkid; i++) {
if (!memcmp(pmksa->bssid, priv->pmkid_list.pmkidlist[i].bssid,
ETH_ALEN)) {
flag = PMKID_FOUND;
break;
}
}
if (i < WILC_MAX_NUM_PMKIDS) {
memcpy(priv->pmkid_list.pmkidlist[i].bssid, pmksa->bssid,
ETH_ALEN);
memcpy(priv->pmkid_list.pmkidlist[i].pmkid, pmksa->pmkid,
WLAN_PMKID_LEN);
if (!(flag == PMKID_FOUND))
priv->pmkid_list.numpmkid++;
} else {
netdev_err(netdev, "Invalid PMKID index\n");
ret = -EINVAL;
}
if (!ret)
ret = wilc_set_pmkid_info(vif, &priv->pmkid_list);
return ret;
}
static int del_pmksa(struct wiphy *wiphy, struct net_device *netdev,
struct cfg80211_pmksa *pmksa)
{
u32 i;
struct wilc_vif *vif = netdev_priv(netdev);
struct wilc_priv *priv = &vif->priv;
for (i = 0; i < priv->pmkid_list.numpmkid; i++) {
if (!memcmp(pmksa->bssid, priv->pmkid_list.pmkidlist[i].bssid,
ETH_ALEN)) {
memset(&priv->pmkid_list.pmkidlist[i], 0,
sizeof(struct wilc_pmkid));
break;
}
}
if (i == priv->pmkid_list.numpmkid)
return -EINVAL;
for (; i < (priv->pmkid_list.numpmkid - 1); i++) {
memcpy(priv->pmkid_list.pmkidlist[i].bssid,
priv->pmkid_list.pmkidlist[i + 1].bssid,
ETH_ALEN);
memcpy(priv->pmkid_list.pmkidlist[i].pmkid,
priv->pmkid_list.pmkidlist[i + 1].pmkid,
WLAN_PMKID_LEN);
}
priv->pmkid_list.numpmkid--;
return 0;
}
static int flush_pmksa(struct wiphy *wiphy, struct net_device *netdev)
{
struct wilc_vif *vif = netdev_priv(netdev);
memset(&vif->priv.pmkid_list, 0, sizeof(struct wilc_pmkid_attr));
return 0;
}
static inline void wilc_wfi_cfg_parse_ch_attr(u8 *buf, u32 len, u8 sta_ch)
{
struct wilc_attr_entry *e;
struct wilc_attr_ch_list *ch_list;
struct wilc_attr_oper_ch *op_ch;
u32 index = 0;
u8 ch_list_idx = 0;
u8 op_ch_idx = 0;
if (sta_ch == WILC_INVALID_CHANNEL)
return;
while (index + sizeof(*e) <= len) {
u16 attr_size;
e = (struct wilc_attr_entry *)&buf[index];
attr_size = le16_to_cpu(e->attr_len);
if (index + sizeof(*e) + attr_size > len)
return;
if (e->attr_type == IEEE80211_P2P_ATTR_CHANNEL_LIST &&
attr_size >= (sizeof(struct wilc_attr_ch_list) - sizeof(*e)))
ch_list_idx = index;
else if (e->attr_type == IEEE80211_P2P_ATTR_OPER_CHANNEL &&
attr_size == (sizeof(struct wilc_attr_oper_ch) - sizeof(*e)))
op_ch_idx = index;
if (ch_list_idx && op_ch_idx)
break;
index += sizeof(*e) + attr_size;
}
if (ch_list_idx) {
u16 attr_size;
struct wilc_ch_list_elem *e;
int i;
ch_list = (struct wilc_attr_ch_list *)&buf[ch_list_idx];
attr_size = le16_to_cpu(ch_list->attr_len);
for (i = 0; i < attr_size;) {
e = (struct wilc_ch_list_elem *)(ch_list->elem + i);
if (e->op_class == WILC_WLAN_OPERATING_CLASS_2_4GHZ) {
memset(e->ch_list, sta_ch, e->no_of_channels);
break;
}
i += e->no_of_channels;
}
}
if (op_ch_idx) {
op_ch = (struct wilc_attr_oper_ch *)&buf[op_ch_idx];
op_ch->op_class = WILC_WLAN_OPERATING_CLASS_2_4GHZ;
op_ch->op_channel = sta_ch;
}
}
bool wilc_wfi_mgmt_frame_rx(struct wilc_vif *vif, u8 *buff, u32 size)
{
struct wilc *wl = vif->wilc;
struct wilc_priv *priv = &vif->priv;
int freq;
freq = ieee80211_channel_to_frequency(wl->op_ch, NL80211_BAND_2GHZ);
return cfg80211_rx_mgmt(&priv->wdev, freq, 0, buff, size, 0);
}
void wilc_wfi_p2p_rx(struct wilc_vif *vif, u8 *buff, u32 size)
{
struct wilc *wl = vif->wilc;
struct wilc_priv *priv = &vif->priv;
struct host_if_drv *wfi_drv = priv->hif_drv;
struct ieee80211_mgmt *mgmt;
struct wilc_vendor_specific_ie *p;
struct wilc_p2p_pub_act_frame *d;
int ie_offset = offsetof(struct ieee80211_mgmt, u) + sizeof(*d);
const u8 *vendor_ie;
u32 header, pkt_offset;
s32 freq;
header = get_unaligned_le32(buff - HOST_HDR_OFFSET);
pkt_offset = FIELD_GET(WILC_PKT_HDR_OFFSET_FIELD, header);
if (pkt_offset & IS_MANAGMEMENT_CALLBACK) {
bool ack = false;
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)buff;
if (ieee80211_is_probe_resp(hdr->frame_control) ||
pkt_offset & IS_MGMT_STATUS_SUCCES)
ack = true;
cfg80211_mgmt_tx_status(&priv->wdev, priv->tx_cookie, buff,
size, ack, GFP_KERNEL);
return;
}
freq = ieee80211_channel_to_frequency(wl->op_ch, NL80211_BAND_2GHZ);
mgmt = (struct ieee80211_mgmt *)buff;
if (!ieee80211_is_action(mgmt->frame_control))
goto out_rx_mgmt;
if (priv->cfg_scanning &&
time_after_eq(jiffies, (unsigned long)wfi_drv->p2p_timeout)) {
netdev_dbg(vif->ndev, "Receiving action wrong ch\n");
return;
}
if (!ieee80211_is_public_action((struct ieee80211_hdr *)buff, size))
goto out_rx_mgmt;
d = (struct wilc_p2p_pub_act_frame *)(&mgmt->u.action);
if (d->oui_subtype != GO_NEG_REQ && d->oui_subtype != GO_NEG_RSP &&
d->oui_subtype != P2P_INV_REQ && d->oui_subtype != P2P_INV_RSP)
goto out_rx_mgmt;
vendor_ie = cfg80211_find_vendor_ie(WLAN_OUI_WFA, WLAN_OUI_TYPE_WFA_P2P,
buff + ie_offset, size - ie_offset);
if (!vendor_ie)
goto out_rx_mgmt;
p = (struct wilc_vendor_specific_ie *)vendor_ie;
wilc_wfi_cfg_parse_ch_attr(p->attr, p->tag_len - 4, vif->wilc->sta_ch);
out_rx_mgmt:
cfg80211_rx_mgmt(&priv->wdev, freq, 0, buff, size, 0);
}
static void wilc_wfi_mgmt_tx_complete(void *priv, int status)
{
struct wilc_p2p_mgmt_data *pv_data = priv;
kfree(pv_data->buff);
kfree(pv_data);
}
static void wilc_wfi_remain_on_channel_expired(void *data, u64 cookie)
{
struct wilc_vif *vif = data;
struct wilc_priv *priv = &vif->priv;
struct wilc_wfi_p2p_listen_params *params = &priv->remain_on_ch_params;
if (cookie != params->listen_cookie)
return;
priv->p2p_listen_state = false;
cfg80211_remain_on_channel_expired(&priv->wdev, params->listen_cookie,
params->listen_ch, GFP_KERNEL);
}
static int remain_on_channel(struct wiphy *wiphy,
struct wireless_dev *wdev,
struct ieee80211_channel *chan,
unsigned int duration, u64 *cookie)
{
int ret = 0;
struct wilc_vif *vif = netdev_priv(wdev->netdev);
struct wilc_priv *priv = &vif->priv;
u64 id;
if (wdev->iftype == NL80211_IFTYPE_AP) {
netdev_dbg(vif->ndev, "Required while in AP mode\n");
return ret;
}
id = ++priv->inc_roc_cookie;
if (id == 0)
id = ++priv->inc_roc_cookie;
ret = wilc_remain_on_channel(vif, id, duration, chan->hw_value,
wilc_wfi_remain_on_channel_expired,
(void *)vif);
if (ret)
return ret;
vif->wilc->op_ch = chan->hw_value;
priv->remain_on_ch_params.listen_ch = chan;
priv->remain_on_ch_params.listen_cookie = id;
*cookie = id;
priv->p2p_listen_state = true;
priv->remain_on_ch_params.listen_duration = duration;
cfg80211_ready_on_channel(wdev, *cookie, chan, duration, GFP_KERNEL);
mod_timer(&vif->hif_drv->remain_on_ch_timer,
jiffies + msecs_to_jiffies(duration + 1000));
return ret;
}
static int cancel_remain_on_channel(struct wiphy *wiphy,
struct wireless_dev *wdev,
u64 cookie)
{
struct wilc_vif *vif = netdev_priv(wdev->netdev);
struct wilc_priv *priv = &vif->priv;
if (cookie != priv->remain_on_ch_params.listen_cookie)
return -ENOENT;
return wilc_listen_state_expired(vif, cookie);
}
static int mgmt_tx(struct wiphy *wiphy,
struct wireless_dev *wdev,
struct cfg80211_mgmt_tx_params *params,
u64 *cookie)
{
struct ieee80211_channel *chan = params->chan;
unsigned int wait = params->wait;
const u8 *buf = params->buf;
size_t len = params->len;
const struct ieee80211_mgmt *mgmt;
struct wilc_p2p_mgmt_data *mgmt_tx;
struct wilc_vif *vif = netdev_priv(wdev->netdev);
struct wilc_priv *priv = &vif->priv;
struct host_if_drv *wfi_drv = priv->hif_drv;
struct wilc_vendor_specific_ie *p;
struct wilc_p2p_pub_act_frame *d;
int ie_offset = offsetof(struct ieee80211_mgmt, u) + sizeof(*d);
const u8 *vendor_ie;
int ret = 0;
*cookie = get_random_u32();
priv->tx_cookie = *cookie;
mgmt = (const struct ieee80211_mgmt *)buf;
if (!ieee80211_is_mgmt(mgmt->frame_control))
goto out;
mgmt_tx = kmalloc(sizeof(*mgmt_tx), GFP_KERNEL);
if (!mgmt_tx) {
ret = -ENOMEM;
goto out;
}
mgmt_tx->buff = kmemdup(buf, len, GFP_KERNEL);
if (!mgmt_tx->buff) {
ret = -ENOMEM;
kfree(mgmt_tx);
goto out;
}
mgmt_tx->size = len;
if (ieee80211_is_probe_resp(mgmt->frame_control)) {
wilc_set_mac_chnl_num(vif, chan->hw_value);
vif->wilc->op_ch = chan->hw_value;
goto out_txq_add_pkt;
}
if (!ieee80211_is_public_action((struct ieee80211_hdr *)buf, len)) {
if (chan)
wilc_set_mac_chnl_num(vif, chan->hw_value);
else
wilc_set_mac_chnl_num(vif, vif->wilc->op_ch);
goto out_set_timeout;
}
d = (struct wilc_p2p_pub_act_frame *)(&mgmt->u.action);
if (d->oui_type != WLAN_OUI_TYPE_WFA_P2P ||
d->oui_subtype != GO_NEG_CONF) {
wilc_set_mac_chnl_num(vif, chan->hw_value);
vif->wilc->op_ch = chan->hw_value;
}
if (d->oui_subtype != P2P_INV_REQ && d->oui_subtype != P2P_INV_RSP)
goto out_set_timeout;
vendor_ie = cfg80211_find_vendor_ie(WLAN_OUI_WFA, WLAN_OUI_TYPE_WFA_P2P,
mgmt_tx->buff + ie_offset,
len - ie_offset);
if (!vendor_ie)
goto out_set_timeout;
p = (struct wilc_vendor_specific_ie *)vendor_ie;
wilc_wfi_cfg_parse_ch_attr(p->attr, p->tag_len - 4, vif->wilc->sta_ch);
out_set_timeout:
wfi_drv->p2p_timeout = (jiffies + msecs_to_jiffies(wait));
out_txq_add_pkt:
wilc_wlan_txq_add_mgmt_pkt(wdev->netdev, mgmt_tx,
mgmt_tx->buff, mgmt_tx->size,
wilc_wfi_mgmt_tx_complete);
out:
return ret;
}
static int mgmt_tx_cancel_wait(struct wiphy *wiphy,
struct wireless_dev *wdev,
u64 cookie)
{
struct wilc_vif *vif = netdev_priv(wdev->netdev);
struct wilc_priv *priv = &vif->priv;
struct host_if_drv *wfi_drv = priv->hif_drv;
wfi_drv->p2p_timeout = jiffies;
if (!priv->p2p_listen_state) {
struct wilc_wfi_p2p_listen_params *params;
params = &priv->remain_on_ch_params;
cfg80211_remain_on_channel_expired(wdev,
params->listen_cookie,
params->listen_ch,
GFP_KERNEL);
}
return 0;
}
void wilc_update_mgmt_frame_registrations(struct wiphy *wiphy,
struct wireless_dev *wdev,
struct mgmt_frame_regs *upd)
{
struct wilc *wl = wiphy_priv(wiphy);
struct wilc_vif *vif = netdev_priv(wdev->netdev);
u32 presp_bit = BIT(IEEE80211_STYPE_PROBE_REQ >> 4);
u32 action_bit = BIT(IEEE80211_STYPE_ACTION >> 4);
u32 pauth_bit = BIT(IEEE80211_STYPE_AUTH >> 4);
if (wl->initialized) {
bool prev = vif->mgmt_reg_stypes & presp_bit;
bool now = upd->interface_stypes & presp_bit;
if (now != prev)
wilc_frame_register(vif, IEEE80211_STYPE_PROBE_REQ, now);
prev = vif->mgmt_reg_stypes & action_bit;
now = upd->interface_stypes & action_bit;
if (now != prev)
wilc_frame_register(vif, IEEE80211_STYPE_ACTION, now);
prev = vif->mgmt_reg_stypes & pauth_bit;
now = upd->interface_stypes & pauth_bit;
if (now != prev)
wilc_frame_register(vif, IEEE80211_STYPE_AUTH, now);
}
vif->mgmt_reg_stypes =
upd->interface_stypes & (presp_bit | action_bit | pauth_bit);
}
static int external_auth(struct wiphy *wiphy, struct net_device *dev,
struct cfg80211_external_auth_params *auth)
{
struct wilc_vif *vif = netdev_priv(dev);
if (auth->status == WLAN_STATUS_SUCCESS)
wilc_set_external_auth_param(vif, auth);
return 0;
}
static int set_cqm_rssi_config(struct wiphy *wiphy, struct net_device *dev,
s32 rssi_thold, u32 rssi_hyst)
{
return 0;
}
static int dump_station(struct wiphy *wiphy, struct net_device *dev,
int idx, u8 *mac, struct station_info *sinfo)
{
struct wilc_vif *vif = netdev_priv(dev);
int ret;
if (idx != 0)
return -ENOENT;
ret = wilc_get_rssi(vif, &sinfo->signal);
if (ret)
return ret;
sinfo->filled |= BIT_ULL(NL80211_STA_INFO_SIGNAL);
memcpy(mac, vif->priv.associated_bss, ETH_ALEN);
return 0;
}
static int set_power_mgmt(struct wiphy *wiphy, struct net_device *dev,
bool enabled, int timeout)
{
struct wilc_vif *vif = netdev_priv(dev);
struct wilc_priv *priv = &vif->priv;
if (!priv->hif_drv)
return -EIO;
wilc_set_power_mgmt(vif, enabled, timeout);
return 0;
}
static int change_virtual_intf(struct wiphy *wiphy, struct net_device *dev,
enum nl80211_iftype type,
struct vif_params *params)
{
struct wilc *wl = wiphy_priv(wiphy);
struct wilc_vif *vif = netdev_priv(dev);
struct wilc_priv *priv = &vif->priv;
switch (type) {
case NL80211_IFTYPE_STATION:
vif->connecting = false;
dev->ieee80211_ptr->iftype = type;
priv->wdev.iftype = type;
vif->monitor_flag = 0;
if (vif->iftype == WILC_AP_MODE || vif->iftype == WILC_GO_MODE)
wilc_wfi_deinit_mon_interface(wl, true);
vif->iftype = WILC_STATION_MODE;
if (wl->initialized)
wilc_set_operation_mode(vif, wilc_get_vif_idx(vif),
WILC_STATION_MODE, vif->idx);
memset(priv->assoc_stainfo.sta_associated_bss, 0,
WILC_MAX_NUM_STA * ETH_ALEN);
break;
case NL80211_IFTYPE_P2P_CLIENT:
vif->connecting = false;
dev->ieee80211_ptr->iftype = type;
priv->wdev.iftype = type;
vif->monitor_flag = 0;
vif->iftype = WILC_CLIENT_MODE;
if (wl->initialized)
wilc_set_operation_mode(vif, wilc_get_vif_idx(vif),
WILC_STATION_MODE, vif->idx);
break;
case NL80211_IFTYPE_AP:
dev->ieee80211_ptr->iftype = type;
priv->wdev.iftype = type;
vif->iftype = WILC_AP_MODE;
if (wl->initialized)
wilc_set_operation_mode(vif, wilc_get_vif_idx(vif),
WILC_AP_MODE, vif->idx);
break;
case NL80211_IFTYPE_P2P_GO:
dev->ieee80211_ptr->iftype = type;
priv->wdev.iftype = type;
vif->iftype = WILC_GO_MODE;
if (wl->initialized)
wilc_set_operation_mode(vif, wilc_get_vif_idx(vif),
WILC_AP_MODE, vif->idx);
break;
default:
netdev_err(dev, "Unknown interface type= %d\n", type);
return -EINVAL;
}
return 0;
}
static int start_ap(struct wiphy *wiphy, struct net_device *dev,
struct cfg80211_ap_settings *settings)
{
struct wilc_vif *vif = netdev_priv(dev);
int ret;
ret = set_channel(wiphy, &settings->chandef);
if (ret != 0)
netdev_err(dev, "Error in setting channel\n");
wilc_wlan_set_bssid(dev, dev->dev_addr, WILC_AP_MODE);
return wilc_add_beacon(vif, settings->beacon_interval,
settings->dtim_period, &settings->beacon);
}
static int change_beacon(struct wiphy *wiphy, struct net_device *dev,
struct cfg80211_beacon_data *beacon)
{
struct wilc_vif *vif = netdev_priv(dev);
return wilc_add_beacon(vif, 0, 0, beacon);
}
static int stop_ap(struct wiphy *wiphy, struct net_device *dev,
unsigned int link_id)
{
int ret;
struct wilc_vif *vif = netdev_priv(dev);
wilc_wlan_set_bssid(dev, NULL, WILC_AP_MODE);
ret = wilc_del_beacon(vif);
if (ret)
netdev_err(dev, "Host delete beacon fail\n");
return ret;
}
static int add_station(struct wiphy *wiphy, struct net_device *dev,
const u8 *mac, struct station_parameters *params)
{
int ret = 0;
struct wilc_vif *vif = netdev_priv(dev);
struct wilc_priv *priv = &vif->priv;
if (vif->iftype == WILC_AP_MODE || vif->iftype == WILC_GO_MODE) {
memcpy(priv->assoc_stainfo.sta_associated_bss[params->aid], mac,
ETH_ALEN);
ret = wilc_add_station(vif, mac, params);
if (ret)
netdev_err(dev, "Host add station fail\n");
}
return ret;
}
static int del_station(struct wiphy *wiphy, struct net_device *dev,
struct station_del_parameters *params)
{
const u8 *mac = params->mac;
int ret = 0;
struct wilc_vif *vif = netdev_priv(dev);
struct wilc_priv *priv = &vif->priv;
struct sta_info *info;
if (!(vif->iftype == WILC_AP_MODE || vif->iftype == WILC_GO_MODE))
return ret;
info = &priv->assoc_stainfo;
if (!mac)
ret = wilc_del_allstation(vif, info->sta_associated_bss);
ret = wilc_del_station(vif, mac);
if (ret)
netdev_err(dev, "Host delete station fail\n");
return ret;
}
static int change_station(struct wiphy *wiphy, struct net_device *dev,
const u8 *mac, struct station_parameters *params)
{
int ret = 0;
struct wilc_vif *vif = netdev_priv(dev);
if (vif->iftype == WILC_AP_MODE || vif->iftype == WILC_GO_MODE) {
ret = wilc_edit_station(vif, mac, params);
if (ret)
netdev_err(dev, "Host edit station fail\n");
}
return ret;
}
static struct wilc_vif *wilc_get_vif_from_type(struct wilc *wl, int type)
{
struct wilc_vif *vif;
list_for_each_entry_rcu(vif, &wl->vif_list, list) {
if (vif->iftype == type)
return vif;
}
return NULL;
}
static struct wireless_dev *add_virtual_intf(struct wiphy *wiphy,
const char *name,
unsigned char name_assign_type,
enum nl80211_iftype type,
struct vif_params *params)
{
struct wilc *wl = wiphy_priv(wiphy);
struct wilc_vif *vif;
struct wireless_dev *wdev;
int iftype;
if (type == NL80211_IFTYPE_MONITOR) {
struct net_device *ndev;
int srcu_idx;
srcu_idx = srcu_read_lock(&wl->srcu);
vif = wilc_get_vif_from_type(wl, WILC_AP_MODE);
if (!vif) {
vif = wilc_get_vif_from_type(wl, WILC_GO_MODE);
if (!vif) {
srcu_read_unlock(&wl->srcu, srcu_idx);
goto validate_interface;
}
}
if (vif->monitor_flag) {
srcu_read_unlock(&wl->srcu, srcu_idx);
goto validate_interface;
}
ndev = wilc_wfi_init_mon_interface(wl, name, vif->ndev);
if (ndev) {
vif->monitor_flag = 1;
} else {
srcu_read_unlock(&wl->srcu, srcu_idx);
return ERR_PTR(-EINVAL);
}
wdev = &vif->priv.wdev;
srcu_read_unlock(&wl->srcu, srcu_idx);
return wdev;
}
validate_interface:
mutex_lock(&wl->vif_mutex);
if (wl->vif_num == WILC_NUM_CONCURRENT_IFC) {
pr_err("Reached maximum number of interface\n");
mutex_unlock(&wl->vif_mutex);
return ERR_PTR(-EINVAL);
}
mutex_unlock(&wl->vif_mutex);
switch (type) {
case NL80211_IFTYPE_STATION:
iftype = WILC_STATION_MODE;
break;
case NL80211_IFTYPE_AP:
iftype = WILC_AP_MODE;
break;
default:
return ERR_PTR(-EOPNOTSUPP);
}
vif = wilc_netdev_ifc_init(wl, name, iftype, type, true);
if (IS_ERR(vif))
return ERR_CAST(vif);
return &vif->priv.wdev;
}
static int del_virtual_intf(struct wiphy *wiphy, struct wireless_dev *wdev)
{
struct wilc *wl = wiphy_priv(wiphy);
struct wilc_vif *vif;
if (wdev->iftype == NL80211_IFTYPE_AP ||
wdev->iftype == NL80211_IFTYPE_P2P_GO)
wilc_wfi_deinit_mon_interface(wl, true);
vif = netdev_priv(wdev->netdev);
cfg80211_stop_iface(wiphy, wdev, GFP_KERNEL);
cfg80211_unregister_netdevice(vif->ndev);
vif->monitor_flag = 0;
wilc_set_operation_mode(vif, 0, 0, 0);
mutex_lock(&wl->vif_mutex);
list_del_rcu(&vif->list);
wl->vif_num--;
mutex_unlock(&wl->vif_mutex);
synchronize_srcu(&wl->srcu);
return 0;
}
static int wilc_suspend(struct wiphy *wiphy, struct cfg80211_wowlan *wow)
{
struct wilc *wl = wiphy_priv(wiphy);
if (!wow && wilc_wlan_get_num_conn_ifcs(wl))
wl->suspend_event = true;
else
wl->suspend_event = false;
return 0;
}
static int wilc_resume(struct wiphy *wiphy)
{
return 0;
}
static void wilc_set_wakeup(struct wiphy *wiphy, bool enabled)
{
struct wilc *wl = wiphy_priv(wiphy);
struct wilc_vif *vif;
int srcu_idx;
srcu_idx = srcu_read_lock(&wl->srcu);
vif = wilc_get_wl_to_vif(wl);
if (IS_ERR(vif)) {
srcu_read_unlock(&wl->srcu, srcu_idx);
return;
}
netdev_info(vif->ndev, "cfg set wake up = %d\n", enabled);
wilc_set_wowlan_trigger(vif, enabled);
srcu_read_unlock(&wl->srcu, srcu_idx);
}
static int set_tx_power(struct wiphy *wiphy, struct wireless_dev *wdev,
enum nl80211_tx_power_setting type, int mbm)
{
int ret;
int srcu_idx;
s32 tx_power = MBM_TO_DBM(mbm);
struct wilc *wl = wiphy_priv(wiphy);
struct wilc_vif *vif;
if (!wl->initialized)
return -EIO;
srcu_idx = srcu_read_lock(&wl->srcu);
vif = wilc_get_wl_to_vif(wl);
if (IS_ERR(vif)) {
srcu_read_unlock(&wl->srcu, srcu_idx);
return -EINVAL;
}
netdev_info(vif->ndev, "Setting tx power %d\n", tx_power);
if (tx_power < 0)
tx_power = 0;
else if (tx_power > 18)
tx_power = 18;
ret = wilc_set_tx_power(vif, tx_power);
if (ret)
netdev_err(vif->ndev, "Failed to set tx power\n");
srcu_read_unlock(&wl->srcu, srcu_idx);
return ret;
}
static int get_tx_power(struct wiphy *wiphy, struct wireless_dev *wdev,
int *dbm)
{
int ret;
struct wilc_vif *vif = netdev_priv(wdev->netdev);
struct wilc *wl = vif->wilc;
/* If firmware is not started, return. */
if (!wl->initialized)
return -EIO;
ret = wilc_get_tx_power(vif, (u8 *)dbm);
if (ret)
netdev_err(vif->ndev, "Failed to get tx power\n");
return ret;
}
static const struct cfg80211_ops wilc_cfg80211_ops = {
.set_monitor_channel = set_channel,
.scan = scan,
.connect = connect,
.disconnect = disconnect,
.add_key = add_key,
.del_key = del_key,
.get_key = get_key,
.set_default_key = set_default_key,
.set_default_mgmt_key = set_default_mgmt_key,
.add_virtual_intf = add_virtual_intf,
.del_virtual_intf = del_virtual_intf,
.change_virtual_intf = change_virtual_intf,
.start_ap = start_ap,
.change_beacon = change_beacon,
.stop_ap = stop_ap,
.add_station = add_station,
.del_station = del_station,
.change_station = change_station,
.get_station = get_station,
.dump_station = dump_station,
.change_bss = change_bss,
.set_wiphy_params = set_wiphy_params,
.external_auth = external_auth,
.set_pmksa = set_pmksa,
.del_pmksa = del_pmksa,
.flush_pmksa = flush_pmksa,
.remain_on_channel = remain_on_channel,
.cancel_remain_on_channel = cancel_remain_on_channel,
.mgmt_tx_cancel_wait = mgmt_tx_cancel_wait,
.mgmt_tx = mgmt_tx,
.update_mgmt_frame_registrations = wilc_update_mgmt_frame_registrations,
.set_power_mgmt = set_power_mgmt,
.set_cqm_rssi_config = set_cqm_rssi_config,
.suspend = wilc_suspend,
.resume = wilc_resume,
.set_wakeup = wilc_set_wakeup,
.set_tx_power = set_tx_power,
.get_tx_power = get_tx_power,
};
static void wlan_init_locks(struct wilc *wl)
{
mutex_init(&wl->hif_cs);
mutex_init(&wl->rxq_cs);
mutex_init(&wl->cfg_cmd_lock);
mutex_init(&wl->vif_mutex);
mutex_init(&wl->deinit_lock);
spin_lock_init(&wl->txq_spinlock);
mutex_init(&wl->txq_add_to_head_cs);
init_completion(&wl->txq_event);
init_completion(&wl->cfg_event);
init_completion(&wl->sync_event);
init_completion(&wl->txq_thread_started);
init_srcu_struct(&wl->srcu);
}
void wlan_deinit_locks(struct wilc *wilc)
{
mutex_destroy(&wilc->hif_cs);
mutex_destroy(&wilc->rxq_cs);
mutex_destroy(&wilc->cfg_cmd_lock);
mutex_destroy(&wilc->txq_add_to_head_cs);
mutex_destroy(&wilc->vif_mutex);
mutex_destroy(&wilc->deinit_lock);
cleanup_srcu_struct(&wilc->srcu);
}
int wilc_cfg80211_init(struct wilc **wilc, struct device *dev, int io_type,
const struct wilc_hif_func *ops)
{
struct wilc *wl;
struct wilc_vif *vif;
int ret, i;
wl = wilc_create_wiphy(dev);
if (!wl)
return -EINVAL;
wlan_init_locks(wl);
ret = wilc_wlan_cfg_init(wl);
if (ret)
goto free_wl;
*wilc = wl;
wl->io_type = io_type;
wl->hif_func = ops;
for (i = 0; i < NQUEUES; i++)
INIT_LIST_HEAD(&wl->txq[i].txq_head.list);
INIT_LIST_HEAD(&wl->rxq_head.list);
INIT_LIST_HEAD(&wl->vif_list);
vif = wilc_netdev_ifc_init(wl, "wlan%d", WILC_STATION_MODE,
NL80211_IFTYPE_STATION, false);
if (IS_ERR(vif)) {
ret = PTR_ERR(vif);
goto free_cfg;
}
return 0;
free_cfg:
wilc_wlan_cfg_deinit(wl);
free_wl:
wlan_deinit_locks(wl);
wiphy_unregister(wl->wiphy);
wiphy_free(wl->wiphy);
return ret;
}
EXPORT_SYMBOL_GPL(wilc_cfg80211_init);
struct wilc *wilc_create_wiphy(struct device *dev)
{
struct wiphy *wiphy;
struct wilc *wl;
int ret;
wiphy = wiphy_new(&wilc_cfg80211_ops, sizeof(*wl));
if (!wiphy)
return NULL;
wl = wiphy_priv(wiphy);
memcpy(wl->bitrates, wilc_bitrates, sizeof(wilc_bitrates));
memcpy(wl->channels, wilc_2ghz_channels, sizeof(wilc_2ghz_channels));
wl->band.bitrates = wl->bitrates;
wl->band.n_bitrates = ARRAY_SIZE(wl->bitrates);
wl->band.channels = wl->channels;
wl->band.n_channels = ARRAY_SIZE(wilc_2ghz_channels);
wl->band.ht_cap.ht_supported = 1;
wl->band.ht_cap.cap |= (1 << IEEE80211_HT_CAP_RX_STBC_SHIFT);
wl->band.ht_cap.mcs.rx_mask[0] = 0xff;
wl->band.ht_cap.ampdu_factor = IEEE80211_HT_MAX_AMPDU_8K;
wl->band.ht_cap.ampdu_density = IEEE80211_HT_MPDU_DENSITY_NONE;
wiphy->bands[NL80211_BAND_2GHZ] = &wl->band;
wiphy->max_scan_ssids = WILC_MAX_NUM_PROBED_SSID;
#ifdef CONFIG_PM
wiphy->wowlan = &wowlan_support;
#endif
wiphy->max_num_pmkids = WILC_MAX_NUM_PMKIDS;
wiphy->max_scan_ie_len = 1000;
wiphy->signal_type = CFG80211_SIGNAL_TYPE_MBM;
memcpy(wl->cipher_suites, wilc_cipher_suites,
sizeof(wilc_cipher_suites));
wiphy->cipher_suites = wl->cipher_suites;
wiphy->n_cipher_suites = ARRAY_SIZE(wilc_cipher_suites);
wiphy->mgmt_stypes = wilc_wfi_cfg80211_mgmt_types;
wiphy->max_remain_on_channel_duration = 500;
wiphy->interface_modes = BIT(NL80211_IFTYPE_STATION) |
BIT(NL80211_IFTYPE_AP) |
BIT(NL80211_IFTYPE_MONITOR) |
BIT(NL80211_IFTYPE_P2P_GO) |
BIT(NL80211_IFTYPE_P2P_CLIENT);
wiphy->flags |= WIPHY_FLAG_HAS_REMAIN_ON_CHANNEL;
wiphy->features |= NL80211_FEATURE_SAE;
set_wiphy_dev(wiphy, dev);
wl->wiphy = wiphy;
ret = wiphy_register(wiphy);
if (ret) {
wiphy_free(wiphy);
return NULL;
}
return wl;
}
int wilc_init_host_int(struct net_device *net)
{
int ret;
struct wilc_vif *vif = netdev_priv(net);
struct wilc_priv *priv = &vif->priv;
priv->p2p_listen_state = false;
mutex_init(&priv->scan_req_lock);
ret = wilc_init(net, &priv->hif_drv);
if (ret)
netdev_err(net, "Error while initializing hostinterface\n");
return ret;
}
void wilc_deinit_host_int(struct net_device *net)
{
int ret;
struct wilc_vif *vif = netdev_priv(net);
struct wilc_priv *priv = &vif->priv;
priv->p2p_listen_state = false;
flush_workqueue(vif->wilc->hif_workqueue);
mutex_destroy(&priv->scan_req_lock);
ret = wilc_deinit(vif);
if (ret)
netdev_err(net, "Error while deinitializing host interface\n");
}
|
f9b62f9843c7b0afdaecabbcebf1dbba18599408
|
https://github.com/torvalds/linux
|
memo.php
|
php
|
<?php
include_once('./_common.php');
if ($is_guest)
alert_close('회원만 이용하실 수 있습니다.');
set_session('ss_memo_delete_token', $token = uniqid(time()));
$g5['title'] = '내 쪽지함';
include_once(G5_PATH.'/head.sub.php');
$kind = isset($_GET['kind']) ? clean_xss_tags($_GET['kind'], 0, 1) : 'recv';
if ($kind == 'recv')
$unkind = 'send';
else if ($kind == 'send')
$unkind = 'recv';
else
alert(''.$kind .'값을 넘겨주세요.');
if ($page < 1) { $page = 1; } // 페이지가 없으면 첫 페이지 (1 페이지)
run_event('memo_list', $kind, $unkind, $page);
$sql = " select count(*) as cnt from {$g5['memo_table']} where me_{$kind}_mb_id = '{$member['mb_id']}' and me_type = '$kind' ";
$row = sql_fetch($sql);
$total_count = $row['cnt'];
$total_page = ceil($total_count / $config['cf_page_rows']); // 전체 페이지 계산
$from_record = ((int) $page - 1) * $config['cf_page_rows']; // 시작 열을 구함
if ($kind == 'recv')
{
$kind_title = '받은';
$recv_img = 'on';
$send_img = 'off';
}
else
{
$kind_title = '보낸';
$recv_img = 'off';
$send_img = 'on';
}
$list = array();
$sql = " select a.*, b.mb_id, b.mb_nick, b.mb_email, b.mb_homepage
from {$g5['memo_table']} a
left join {$g5['member_table']} b on (a.me_{$unkind}_mb_id = b.mb_id)
where a.me_{$kind}_mb_id = '{$member['mb_id']}' and a.me_type = '$kind'
order by a.me_id desc limit $from_record, {$config['cf_page_rows']} ";
$result = sql_query($sql);
for ($i=0; $row=sql_fetch_array($result); $i++)
{
$list[$i] = $row;
$mb_id = $row["me_{$unkind}_mb_id"];
if ($row['mb_nick'])
$mb_nick = $row['mb_nick'];
else
$mb_nick = '정보없음';
$name = get_sideview($row['mb_id'], $row['mb_nick'], $row['mb_email'], $row['mb_homepage']);
if (substr($row['me_read_datetime'],0,1) == 0)
$read_datetime = '아직 읽지 않음';
else
$read_datetime = substr($row['me_read_datetime'],2,14);
$send_datetime = substr($row['me_send_datetime'],2,14);
$list[$i]['mb_id'] = $mb_id;
$list[$i]['name'] = $name;
$list[$i]['send_datetime'] = $send_datetime;
$list[$i]['read_datetime'] = $read_datetime;
$list[$i]['view_href'] = './memo_view.php?me_id='.$row['me_id'].'&kind='.$kind.'&page='.$page;
$list[$i]['del_href'] = './memo_delete.php?me_id='.$row['me_id'].'&token='.$token.'&kind='.$kind;
}
$write_pages = get_paging(G5_IS_MOBILE ? $config['cf_mobile_pages'] : $config['cf_write_pages'], $page, $total_page, "./memo.php?kind=$kind".$qstr."&page=");
include_once($member_skin_path.'/memo.skin.php');
include_once(G5_PATH.'/tail.sub.php');
|
<?php
include_once('./_common.php');
if ($is_guest)
alert_close('회원만 이용하실 수 있습니다.');
set_session('ss_memo_delete_token', $token = uniqid(time()));
$g5['title'] = '내 쪽지함';
include_once(G5_PATH.'/head.sub.php');
$kind = isset($_GET['kind']) ? clean_xss_tags($_GET['kind'], 0, 1) : 'recv';
if ($kind == 'recv')
$unkind = 'send';
else if ($kind == 'send')
$unkind = 'recv';
else {
$kind = clean_xss_tags(trim($kind));
alert(''.$kind .'값을 넘겨주세요.');
}
if ($page < 1) { $page = 1; } // 페이지가 없으면 첫 페이지 (1 페이지)
run_event('memo_list', $kind, $unkind, $page);
$sql = " select count(*) as cnt from {$g5['memo_table']} where me_{$kind}_mb_id = '{$member['mb_id']}' and me_type = '$kind' ";
$row = sql_fetch($sql);
$total_count = $row['cnt'];
$total_page = ceil($total_count / $config['cf_page_rows']); // 전체 페이지 계산
$from_record = ((int) $page - 1) * $config['cf_page_rows']; // 시작 열을 구함
if ($kind == 'recv')
{
$kind_title = '받은';
$recv_img = 'on';
$send_img = 'off';
}
else
{
$kind_title = '보낸';
$recv_img = 'off';
$send_img = 'on';
}
$list = array();
$sql = " select a.*, b.mb_id, b.mb_nick, b.mb_email, b.mb_homepage
from {$g5['memo_table']} a
left join {$g5['member_table']} b on (a.me_{$unkind}_mb_id = b.mb_id)
where a.me_{$kind}_mb_id = '{$member['mb_id']}' and a.me_type = '$kind'
order by a.me_id desc limit $from_record, {$config['cf_page_rows']} ";
$result = sql_query($sql);
for ($i=0; $row=sql_fetch_array($result); $i++)
{
$list[$i] = $row;
$mb_id = $row["me_{$unkind}_mb_id"];
if ($row['mb_nick'])
$mb_nick = $row['mb_nick'];
else
$mb_nick = '정보없음';
$name = get_sideview($row['mb_id'], $row['mb_nick'], $row['mb_email'], $row['mb_homepage']);
if (substr($row['me_read_datetime'],0,1) == 0)
$read_datetime = '아직 읽지 않음';
else
$read_datetime = substr($row['me_read_datetime'],2,14);
$send_datetime = substr($row['me_send_datetime'],2,14);
$list[$i]['mb_id'] = $mb_id;
$list[$i]['name'] = $name;
$list[$i]['send_datetime'] = $send_datetime;
$list[$i]['read_datetime'] = $read_datetime;
$list[$i]['view_href'] = './memo_view.php?me_id='.$row['me_id'].'&kind='.$kind.'&page='.$page;
$list[$i]['del_href'] = './memo_delete.php?me_id='.$row['me_id'].'&token='.$token.'&kind='.$kind;
}
$write_pages = get_paging(G5_IS_MOBILE ? $config['cf_mobile_pages'] : $config['cf_write_pages'], $page, $total_page, "./memo.php?kind=$kind".$qstr."&page=");
include_once($member_skin_path.'/memo.skin.php');
include_once(G5_PATH.'/tail.sub.php');
|
2e81619ea87bc9c0b4a073d8df3c7693a6fdbf0d
|
https://github.com/gnuboard/gnuboard5
|
admin.php
|
php
|
<b>Service Status</b>
<table>
<tr>
<th><a class=tooltip href="#">DStarRepeater<span><b>DStarRepeater</b></span></th>
<th><a class=tooltip href="#">MMDVMHost<span><b>DStarRepeater</b></span></th>
<th><a class=tooltip href="#">ircDDBgateway<span><b>ircDDBgateway</b></span></th>
<th><a class=tooltip href="#">timeserver<span><b>timeserver</b></span></th>
<th><a class=tooltip href="#">pistar-watchdog<span><b>pistar-watchdog</b></span></th>
<th><a class=tooltip href="#">pistar-keeper<span><b>pistar-keeper</b></span></th>
</tr>
<tr>
<td><?php exec ("pgrep dstarrepeaterd", $dstarrepeaterpid); if (!empty($dstarrepeaterpid)) { echo "<img src=\"images/20green.png\">"; } else { echo "<img src=\"images/20red.png\">"; } ?></td>
<td><?php exec ("pgrep MMDVMHost", $mmdvmhostpid); if (!empty($mmdvmhostpid)) { echo "<img src=\"images/20green.png\">"; } else { echo "<img src=\"images/20red.png\">"; } ?></td>
<td><?php exec ("pgrep ircddbgatewayd", $ircddbgatewaypid); if (!empty($ircddbgatewaypid)) { echo "<img src=\"images/20green.png\">"; } else { echo "<img src=\"images/20red.png\">"; } ?></td>
<td><?php exec ("pgrep timeserverd", $timeserverpid); if (!empty($timeserverpid)) { echo "<img src=\"images/20green.png\">"; } else { echo "<img src=\"images/20red.png\">"; } ?></td>
<td><?php exec ("pgrep -f -a /usr/local/sbin/pistar-watchdog | sed '/pgrep/d'", $watchdogpid); if (!empty($watchdogpid)) { echo "<img src=\"images/20green.png\">"; } else { echo "<img src=\"images/20red.png\">"; } ?></td>
<td><?php exec ("pgrep -f -a /usr/local/sbin/pistar-keeper | sed '/pgrep/d'", $keeperpid); if (!empty($keeperpid)) { echo "<img src=\"images/20green.png\">"; } else { echo "<img src=\"images/20red.png\">"; } ?></td>
</tr>
</table>
<br />
<?php if (!empty($_POST)):
if (preg_match('/[^A-Z]/',$_POST["Link"])) { unset ($_POST["Link"]);}
if ($_POST["Link"] == "LINK") {
if (preg_match('/[^A-Z0-9]/',$_POST["RefName"])) { unset ($_POST["RefName"]);}
if (preg_match('/[^A-Z]/',$_POST["Letter"])) { unset ($_POST["Letter"]);}
if (preg_match('/[^A-Z0-9 ]/',$_POST["Module"])) { unset ($_POST["Module"]);}
}
if (empty($_POST["RefName"]) || empty($_POST["Letter"]) || empty($_POST["Module"])) { echo "Somthing wrong with your input, try again";}
else {
$targetRef = $_POST["RefName"]." ".$_POST["Letter"];
$module = $_POST["Module"];
if (strlen($module) != 8) { //Fix the length of the module information
$moduleFixedCs= strlen($module) - 1; //Length of the string, -1
$moduleFixedBand = substr($module, -1); //Single Band Letter in the 8th position
$moduleFixedCallPad = str_pad(substr($module, 0, $moduleFixedCs), 7); //Pad the callsign area to 7 chars
$module = $moduleFixedCallPad.$moduleFixedBand; //Re add the band information
};
$unlinkCommand = "sudo remotecontrold \"".$module."\" unlink";
$linkCommand = "sudo remotecontrold \"".$module."\" link never \"".$targetRef."\"";
if ($_POST["Link"] == "LINK") {
echo "<b>Reflector Connector</b>\n";
echo "<table>\n<tr><th><a class=tooltip href=\"#\">Command Output<span><b>Command Output</b></span></th></tr>\n<tr><td>";
echo exec($linkCommand);
echo "</tr></td>\n</table>\n";
}
if ($_POST["Link"] == "UNLINK") {
echo "<b>Reflector Connector</b>\n";
echo "<table>\n<tr><th><a class=tooltip href=\"#\">Command Output<span><b>Command Output</b></span></th></tr>\n<tr><td>";
echo exec($unlinkCommand);
echo "</tr></td>\n</table>\n";
}
}
unset($_POST);
echo '<script type="text/javascript">setTimeout(function() { window.location=window.location;},2000);</script>';
else: ?>
<b>Reflector Connector</b>
<form action="//<?php echo htmlentities($_SERVER['HTTP_HOST']).htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<table>
<tr>
<th width="150"><a class=tooltip href="#">Radio Module<span><b>Radio Module</b></span></th>
<th width="180"><a class=tooltip href="#">Reflector<span><b>Reflector</b></span></th>
<th width="150"><a class=tooltip href="#">Link / Un-Link<span><b>Link / Un-Link</b></span></th>
<th><a class=tooltip href="#">Action<span><b>Action</b></span></th>
</tr>
<tr>
<td>
<select name="Module">
<?php for($i = 1;$i < 5; $i++){
$param="repeaterBand" . $i;
if((isset($configs[$param])) && strlen($configs[$param]) == 1) {
$ci++;
if($ci > 1) { $ci = 0; }
$module = $configs[$param];
$rcall = sprintf("%-7.7s%-1.1s",$MYCALL,$module);
$param="repeaterCall" . $i;
if(isset($configs[$param])) { $rptrcall=sprintf("%-7.7s%-1.1s",$configs[$param],$module); } else { $rptrcall = $rcall;}
print "<option>$rptrcall</option>\n";
}
} ?>
</select>
</td>
<td>
<select name="RefName">
<?php
$dcsFile = fopen("/usr/local/etc/DCS_Hosts.txt", "r");
$dplusFile = fopen("/usr/local/etc/DPlus_Hosts.txt", "r");
$dextraFile = fopen("/usr/local/etc/DExtra_Hosts.txt", "r");
while (!feof($dcsFile)) {
$dcsLine = fgets($dcsFile);
if (strpos($dcsLine, 'DCS') !== FALSE && strpos($dcsLine, '#') === FALSE)
echo " <option>".substr($dcsLine, 0, 6)."</option>\n";
}
fclose($dcsFile);
echo " <option selected>REF001</option>\n";
while (!feof($dplusFile)) {
$dplusLine = fgets($dplusFile);
if (strpos($dplusLine, 'REF') !== FALSE && strpos($dplusLine, '#') === FALSE && strpos($dplusLine, 'REF001') === FALSE)
echo " <option>".substr($dplusLine, 0, 6)."</option>\n";
}
fclose($dplusFile);
while (!feof($dextraFile)) {
$dextraLine = fgets($dextraFile);
if (strpos($dextraLine, 'XRF') !== FALSE && strpos($dextraLine, '#') === FALSE)
echo " <option>".substr($dextraLine, 0, 6)."</option>\n";
}
fclose($dextraFile);
?>
</select>
<select name="Letter">
<option>A</option>
<option>B</option>
<option selected>C</option>
<option>D</option>
<option>E</option>
<option>F</option>
<option>G</option>
<option>H</option>
<option>I</option>
<option>J</option>
<option>K</option>
<option>L</option>
<option>M</option>
<option>N</option>
<option>O</option>
<option>P</option>
<option>Q</option>
<option>R</option>
<option>S</option>
<option>T</option>
<option>U</option>
<option>V</option>
<option>W</option>
<option>X</option>
<option>Y</option>
<option>Z</option>
</select>
</td>
<td>
<input type="radio" name="Link" value="LINK" checked>Link
<input type="radio" name="Link" value="UNLINK">UnLink
</td>
<td>
<input type="submit" value="Request Change">
</td>
</tr>
</table>
</form>
<?php endif; ?>
<?php
exec ("pgrep pistar-keeper", $pids);
if (!empty($pids))
{
echo "<br />\n";
echo "<b>PiStar-Keeper Logbook</b><input type=button onClick=\"location.href='/admin/pistar-keeper-download.php'\" value=\"Download Logbook\">\n";
echo "<table>\n";
echo " <tr>\n";
echo " <th><a class=tooltip href=\"#\">PiStar-Keeper Log Entries (UTC)<span><b>PiStar-Keeper Log Entries (UTC)</b></span></th>\n";
echo " </tr>\n";
exec ("tail -n 5 /var/pistar-keeper/pistar-keeper.log", $lines);
$counter = 0;
foreach ($lines as $line) {
echo "<tr><td align=\"left\">".$lines[$counter]."</td></tr>\n";
$counter++;
}
echo "</table>\n";
}
?>
|
<b>Service Status</b>
<table>
<tr>
<th><a class=tooltip href="#">DStarRepeater<span><b>DStarRepeater</b></span></th>
<th><a class=tooltip href="#">MMDVMHost<span><b>DStarRepeater</b></span></th>
<th><a class=tooltip href="#">ircDDBgateway<span><b>ircDDBgateway</b></span></th>
<th><a class=tooltip href="#">timeserver<span><b>timeserver</b></span></th>
<th><a class=tooltip href="#">pistar-watchdog<span><b>pistar-watchdog</b></span></th>
<th><a class=tooltip href="#">pistar-keeper<span><b>pistar-keeper</b></span></th>
</tr>
<tr>
<td><?php exec ("pgrep dstarrepeaterd", $dstarrepeaterpid); if (!empty($dstarrepeaterpid)) { echo "<img src=\"images/20green.png\">"; } else { echo "<img src=\"images/20red.png\">"; } ?></td>
<td><?php exec ("pgrep MMDVMHost", $mmdvmhostpid); if (!empty($mmdvmhostpid)) { echo "<img src=\"images/20green.png\">"; } else { echo "<img src=\"images/20red.png\">"; } ?></td>
<td><?php exec ("pgrep ircddbgatewayd", $ircddbgatewaypid); if (!empty($ircddbgatewaypid)) { echo "<img src=\"images/20green.png\">"; } else { echo "<img src=\"images/20red.png\">"; } ?></td>
<td><?php exec ("pgrep timeserverd", $timeserverpid); if (!empty($timeserverpid)) { echo "<img src=\"images/20green.png\">"; } else { echo "<img src=\"images/20red.png\">"; } ?></td>
<td><?php exec ("pgrep -f -a /usr/local/sbin/pistar-watchdog | sed '/pgrep/d'", $watchdogpid); if (!empty($watchdogpid)) { echo "<img src=\"images/20green.png\">"; } else { echo "<img src=\"images/20red.png\">"; } ?></td>
<td><?php exec ("pgrep -f -a /usr/local/sbin/pistar-keeper | sed '/pgrep/d'", $keeperpid); if (!empty($keeperpid)) { echo "<img src=\"images/20green.png\">"; } else { echo "<img src=\"images/20red.png\">"; } ?></td>
</tr>
</table>
<br />
<?php if (!empty($_POST)):
if (preg_match('/[^A-Z]/',$_POST["Link"])) { unset ($_POST["Link"]);}
if ($_POST["Link"] == "LINK") {
if (preg_match('/[^A-Z0-9]/',$_POST["RefName"])) { unset ($_POST["RefName"]);}
if (preg_match('/[^A-Z]/',$_POST["Letter"])) { unset ($_POST["Letter"]);}
if (preg_match('/[^A-Z0-9 ]/',$_POST["Module"])) { unset ($_POST["Module"]);}
}
if ($_POST["Link"] == "UNLINK") {
if (preg_match('/[^A-Z0-9 ]/',$_POST["Module"])) { unset ($_POST["Module"]);}
}
if (empty($_POST["RefName"]) || empty($_POST["Letter"]) || empty($_POST["Module"])) { echo "Somthing wrong with your input, try again";}
else {
$targetRef = $_POST["RefName"]." ".$_POST["Letter"];
$module = $_POST["Module"];
if (strlen($module) != 8) { //Fix the length of the module information
$moduleFixedCs= strlen($module) - 1; //Length of the string, -1
$moduleFixedBand = substr($module, -1); //Single Band Letter in the 8th position
$moduleFixedCallPad = str_pad(substr($module, 0, $moduleFixedCs), 7); //Pad the callsign area to 7 chars
$module = $moduleFixedCallPad.$moduleFixedBand; //Re add the band information
};
$unlinkCommand = "sudo remotecontrold \"".$module."\" unlink";
$linkCommand = "sudo remotecontrold \"".$module."\" link never \"".$targetRef."\"";
if ($_POST["Link"] == "LINK") {
echo "<b>Reflector Connector</b>\n";
echo "<table>\n<tr><th><a class=tooltip href=\"#\">Command Output<span><b>Command Output</b></span></th></tr>\n<tr><td>";
echo exec($linkCommand);
echo "</tr></td>\n</table>\n";
}
if ($_POST["Link"] == "UNLINK") {
echo "<b>Reflector Connector</b>\n";
echo "<table>\n<tr><th><a class=tooltip href=\"#\">Command Output<span><b>Command Output</b></span></th></tr>\n<tr><td>";
echo exec($unlinkCommand);
echo "</tr></td>\n</table>\n";
}
}
unset($_POST);
echo '<script type="text/javascript">setTimeout(function() { window.location=window.location;},2000);</script>';
else: ?>
<b>Reflector Connector</b>
<form action="//<?php echo htmlentities($_SERVER['HTTP_HOST']).htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<table>
<tr>
<th width="150"><a class=tooltip href="#">Radio Module<span><b>Radio Module</b></span></th>
<th width="180"><a class=tooltip href="#">Reflector<span><b>Reflector</b></span></th>
<th width="150"><a class=tooltip href="#">Link / Un-Link<span><b>Link / Un-Link</b></span></th>
<th><a class=tooltip href="#">Action<span><b>Action</b></span></th>
</tr>
<tr>
<td>
<select name="Module">
<?php for($i = 1;$i < 5; $i++){
$param="repeaterBand" . $i;
if((isset($configs[$param])) && strlen($configs[$param]) == 1) {
$ci++;
if($ci > 1) { $ci = 0; }
$module = $configs[$param];
$rcall = sprintf("%-7.7s%-1.1s",$MYCALL,$module);
$param="repeaterCall" . $i;
if(isset($configs[$param])) { $rptrcall=sprintf("%-7.7s%-1.1s",$configs[$param],$module); } else { $rptrcall = $rcall;}
print "<option>$rptrcall</option>\n";
}
} ?>
</select>
</td>
<td>
<select name="RefName">
<?php
$dcsFile = fopen("/usr/local/etc/DCS_Hosts.txt", "r");
$dplusFile = fopen("/usr/local/etc/DPlus_Hosts.txt", "r");
$dextraFile = fopen("/usr/local/etc/DExtra_Hosts.txt", "r");
while (!feof($dcsFile)) {
$dcsLine = fgets($dcsFile);
if (strpos($dcsLine, 'DCS') !== FALSE && strpos($dcsLine, '#') === FALSE)
echo " <option>".substr($dcsLine, 0, 6)."</option>\n";
}
fclose($dcsFile);
echo " <option selected>REF001</option>\n";
while (!feof($dplusFile)) {
$dplusLine = fgets($dplusFile);
if (strpos($dplusLine, 'REF') !== FALSE && strpos($dplusLine, '#') === FALSE && strpos($dplusLine, 'REF001') === FALSE)
echo " <option>".substr($dplusLine, 0, 6)."</option>\n";
}
fclose($dplusFile);
while (!feof($dextraFile)) {
$dextraLine = fgets($dextraFile);
if (strpos($dextraLine, 'XRF') !== FALSE && strpos($dextraLine, '#') === FALSE)
echo " <option>".substr($dextraLine, 0, 6)."</option>\n";
}
fclose($dextraFile);
?>
</select>
<select name="Letter">
<option>A</option>
<option>B</option>
<option selected>C</option>
<option>D</option>
<option>E</option>
<option>F</option>
<option>G</option>
<option>H</option>
<option>I</option>
<option>J</option>
<option>K</option>
<option>L</option>
<option>M</option>
<option>N</option>
<option>O</option>
<option>P</option>
<option>Q</option>
<option>R</option>
<option>S</option>
<option>T</option>
<option>U</option>
<option>V</option>
<option>W</option>
<option>X</option>
<option>Y</option>
<option>Z</option>
</select>
</td>
<td>
<input type="radio" name="Link" value="LINK" checked>Link
<input type="radio" name="Link" value="UNLINK">UnLink
</td>
<td>
<input type="submit" value="Request Change">
</td>
</tr>
</table>
</form>
<?php endif; ?>
<?php
exec ("pgrep pistar-keeper", $pids);
if (!empty($pids))
{
echo "<br />\n";
echo "<b>PiStar-Keeper Logbook</b><input type=button onClick=\"location.href='/admin/pistar-keeper-download.php'\" value=\"Download Logbook\">\n";
echo "<table>\n";
echo " <tr>\n";
echo " <th><a class=tooltip href=\"#\">PiStar-Keeper Log Entries (UTC)<span><b>PiStar-Keeper Log Entries (UTC)</b></span></th>\n";
echo " </tr>\n";
exec ("tail -n 5 /var/pistar-keeper/pistar-keeper.log", $lines);
$counter = 0;
foreach ($lines as $line) {
echo "<tr><td align=\"left\">".$lines[$counter]."</td></tr>\n";
$counter++;
}
echo "</table>\n";
}
?>
|
5aa194df3dfc92cc21f6604bbda32268f4a624ce
|
https://github.com/andytaylortweet/pi-star_dv_dash
|
bug_actiongroup_page.php
|
php
|
<?php
# MantisBT - A PHP based bugtracking system
# MantisBT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# MantisBT 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 MantisBT. If not, see <http://www.gnu.org/licenses/>.
/**
* This page allows actions to be performed on an array of bugs
*
* @package MantisBT
* @copyright Copyright 2000 - 2002 Kenzaburo Ito - kenito@300baud.org
* @copyright Copyright 2002 MantisBT Team - mantisbt-dev@lists.sourceforge.net
* @link http://www.mantisbt.org
*
* @uses core.php
* @uses access_api.php
* @uses authentication_api.php
* @uses bug_api.php
* @uses bug_group_action_api.php
* @uses config_api.php
* @uses constant_inc.php
* @uses custom_field_api.php
* @uses event_api.php
* @uses form_api.php
* @uses gpc_api.php
* @uses helper_api.php
* @uses lang_api.php
* @uses print_api.php
* @uses string_api.php
* @uses utility_api.php
* @uses version_api.php
*/
require_once( 'core.php' );
require_api( 'access_api.php' );
require_api( 'authentication_api.php' );
require_api( 'bug_api.php' );
require_api( 'bug_group_action_api.php' );
require_api( 'config_api.php' );
require_api( 'constant_inc.php' );
require_api( 'custom_field_api.php' );
require_api( 'event_api.php' );
require_api( 'form_api.php' );
require_api( 'gpc_api.php' );
require_api( 'helper_api.php' );
require_api( 'lang_api.php' );
require_api( 'print_api.php' );
require_api( 'string_api.php' );
require_api( 'utility_api.php' );
require_api( 'version_api.php' );
auth_ensure_user_authenticated();
$f_action = gpc_get_string( 'action', '' );
$f_bug_arr = gpc_get_int_array( 'bug_arr', array() );
# redirects to all_bug_page if nothing is selected
if( is_blank( $f_action ) || ( 0 == count( $f_bug_arr ) ) ) {
print_header_redirect( 'view_all_bug_page.php' );
}
# run through the issues to see if they are all from one project
$t_project_id = ALL_PROJECTS;
$t_multiple_projects = false;
$t_projects = array();
# Array of parameters to be used with plugin event
$t_event_params = array();
$t_event_params['bug_ids'] = $f_bug_arr;
$t_event_params['action'] = $f_action;
$t_event_params['has_bugnote'] = false;
bug_cache_array_rows( $f_bug_arr );
foreach( $f_bug_arr as $t_bug_id ) {
$t_bug = bug_get( $t_bug_id );
if( $t_project_id != $t_bug->project_id ) {
if( ( $t_project_id != ALL_PROJECTS ) && !$t_multiple_projects ) {
$t_multiple_projects = true;
} else {
$t_project_id = $t_bug->project_id;
$t_projects[$t_project_id] = $t_project_id;
}
}
}
$t_event_params['multiple_projects'] = $t_multiple_projects;
if( $t_multiple_projects ) {
$t_project_id = ALL_PROJECTS;
$t_projects[ALL_PROJECTS] = ALL_PROJECTS;
}
# override the project if necessary
if( $t_project_id != helper_get_current_project() ) {
# in case the current project is not the same project of the bug we are viewing...
# ... override the current project. This to avoid problems with categories and handlers lists etc.
$g_project_override = $t_project_id;
}
define( 'BUG_ACTIONGROUP_INC_ALLOW', true );
$t_finished = false;
$t_bugnote = false;
$t_external_action_prefix = 'EXT_';
if( strpos( $f_action, $t_external_action_prefix ) === 0 ) {
$t_form_page = 'bug_actiongroup_ext_page.php';
require_once( $t_form_page );
exit;
}
$t_custom_group_actions = config_get( 'custom_group_actions' );
foreach( $t_custom_group_actions as $t_custom_group_action ) {
if( $f_action == $t_custom_group_action['action'] ) {
require_once( $t_custom_group_action['form_page'] );
exit;
}
}
# Check if user selected to update a custom field.
$t_custom_fields_prefix = 'custom_field_';
if( strpos( $f_action, $t_custom_fields_prefix ) === 0 ) {
$t_custom_field_id = (int)substr( $f_action, mb_strlen( $t_custom_fields_prefix ) );
$f_action = 'CUSTOM';
$t_event_params['action'] = $f_action;
}
# Form name
$t_form_name = 'bug_actiongroup_' . $f_action;
switch( $f_action ) {
# Use a simple confirmation page, if close or delete...
case 'CLOSE' :
$t_finished = true;
$t_question_title = lang_get( 'close_bugs_conf_msg' );
$t_button_title = lang_get( 'close_group_bugs_button' );
$t_bugnote = true;
break;
case 'DELETE' :
$t_finished = true;
$t_question_title = lang_get( 'delete_bugs_conf_msg' );
$t_button_title = lang_get( 'delete_group_bugs_button' );
break;
case 'SET_STICKY' :
$t_finished = true;
$t_question_title = lang_get( 'set_sticky_bugs_conf_msg' );
$t_button_title = lang_get( 'set_sticky_group_bugs_button' );
break;
# ...else we define the variables used in the form
case 'MOVE' :
$t_question_title = lang_get( 'move_bugs_conf_msg' );
$t_button_title = lang_get( 'move_group_bugs_button' );
$t_form = 'project_id';
break;
case 'COPY' :
$t_question_title = lang_get( 'copy_bugs_conf_msg' );
$t_button_title = lang_get( 'copy_group_bugs_button' );
$t_form = 'project_id';
break;
case 'ASSIGN' :
$t_question_title = lang_get( 'assign_bugs_conf_msg' );
$t_button_title = lang_get( 'assign_group_bugs_button' );
$t_form = 'assign';
break;
case 'RESOLVE' :
$t_question_title = lang_get( 'resolve_bugs_conf_msg' );
$t_button_title = lang_get( 'resolve_group_bugs_button' );
$t_form = 'resolution';
if( ALL_PROJECTS != $t_project_id ) {
$t_question_title2 = lang_get( 'fixed_in_version' );
$t_form2 = 'fixed_in_version';
}
$t_bugnote = true;
break;
case 'UP_PRIOR' :
$t_question_title = lang_get( 'priority_bugs_conf_msg' );
$t_button_title = lang_get( 'priority_group_bugs_button' );
$t_form = 'priority';
break;
case 'UP_STATUS' :
$t_question_title = lang_get( 'status_bugs_conf_msg' );
$t_button_title = lang_get( 'status_group_bugs_button' );
$t_form = 'status';
$t_bugnote = true;
break;
case 'UP_CATEGORY' :
$t_question_title = lang_get( 'category_bugs_conf_msg' );
$t_button_title = lang_get( 'category_group_bugs_button' );
$t_form = 'category';
break;
case 'VIEW_STATUS' :
$t_question_title = lang_get( 'view_status_bugs_conf_msg' );
$t_button_title = lang_get( 'view_status_group_bugs_button' );
$t_form = 'view_status';
break;
case 'UP_PRODUCT_VERSION':
$t_question_title = lang_get( 'product_version_bugs_conf_msg' );
$t_button_title = lang_get( 'product_version_group_bugs_button' );
$t_form = 'product_version';
break;
case 'UP_FIXED_IN_VERSION':
$t_question_title = lang_get( 'fixed_in_version_bugs_conf_msg' );
$t_button_title = lang_get( 'fixed_in_version_group_bugs_button' );
$t_form = 'fixed_in_version';
break;
case 'UP_TARGET_VERSION':
$t_question_title = lang_get( 'target_version_bugs_conf_msg' );
$t_button_title = lang_get( 'target_version_group_bugs_button' );
$t_form = 'target_version';
break;
case 'UP_DUE_DATE':
$t_question_title = lang_get( 'due_date_bugs_conf_msg' );
$t_button_title = lang_get( 'due_date_group_bugs_button' );
$t_form = 'due_date';
break;
case 'CUSTOM' :
$t_custom_field_def = custom_field_get_definition( $t_custom_field_id );
$t_question_title = sprintf( lang_get( 'actiongroup_menu_update_field' ), lang_get_defaulted( $t_custom_field_def['name'] ) );
$t_button_title = $t_question_title;
$t_form = 'custom_field_' . $t_custom_field_id;
$t_event_params['custom_field_id'] = $t_custom_field_id;
break;
default:
trigger_error( ERROR_GENERIC, ERROR );
}
$t_event_params['has_bugnote'] = $t_bugnote;
bug_group_action_print_top();
?>
<div class="col-md-12 col-xs-12">
<?php
if( $t_multiple_projects ) {
echo '<div class="alert alert-warning"> <p class="bold">' . lang_get( 'multiple_projects' ) . '</p> </div>';
}
?>
<div id="action-group-div" class="form-container">
<form method="post" action="bug_actiongroup.php">
<?php echo form_security_field( $t_form_name ); ?>
<input type="hidden" name="action" value="<?php echo string_attribute( $f_action ) ?>" />
<?php
bug_group_action_print_hidden_fields( $f_bug_arr );
if( $f_action === 'CUSTOM' ) {
echo "<input type=\"hidden\" name=\"custom_field_id\" value=\"$t_custom_field_id\" />";
}
?>
<div class="widget-box widget-color-blue2">
<div class="widget-header widget-header-small">
<h4 class="widget-title lighter">
<?php echo $t_question_title ?>
</h4>
</div>
<div class="widget-body">
<div class="widget-main no-padding">
<div class="table-responsive">
<table class="table table-bordered table-condensed table-striped">
<tbody>
<?php
if( !$t_finished ) {
?>
<tr>
<th class="category">
<?php echo $t_question_title ?>
</th>
<td>
<?php
if( $f_action === 'CUSTOM' ) {
$t_custom_field_def = custom_field_get_definition( $t_custom_field_id );
$t_bug_id = null;
# if there is only one issue, use its current value as default, otherwise,
# use the default value specified in custom field definition.
if( count( $f_bug_arr ) == 1 ) {
$t_bug_id = $f_bug_arr[0];
}
print_custom_field_input( $t_custom_field_def, $t_bug_id );
} else if ( $f_action === 'UP_DUE_DATE' ) {
$t_date_to_display = '';
# if there is only one issue, use its current value as default
if( count( $f_bug_arr ) == 1 ) {
$t_bug_id = $f_bug_arr[0];
$t_bug = bug_get( $t_bug_id );
if( !date_is_null( $t_bug->due_date ) ) {
$t_date_to_display = date( config_get( 'normal_date_format' ), $t_bug->due_date );
}
}
echo '<input type="text" id="due_date" name="due_date" class="datetimepicker input-sm" size="16" maxlength="16" ' .
'data-picker-locale="' . lang_get_current_datetime_locale() .
'" data-picker-format="' . config_get( 'datetime_picker_format' ) . '"' .
'" value="' . $t_date_to_display . '" />';
echo '<i class="fa fa-calendar fa-xlg datetimepicker"></i>';
} else {
echo '<select name="' . $t_form . '" class="input-sm" required>';
switch( $f_action ) {
case 'COPY':
case 'MOVE':
print_project_option_list( null /* $p_project_id */, false /* $p_include_all_projects */,
null /* $p_filter_project_id */, false /* $p_trace */, true /* $p_can_report_only */ );
break;
case 'ASSIGN':
print_assign_to_option_list( 0, $t_project_id );
break;
case 'RESOLVE':
print_enum_string_option_list( 'resolution', config_get( 'bug_resolution_fixed_threshold' ) );
break;
case 'UP_PRIOR':
print_enum_string_option_list( 'priority', config_get( 'default_bug_priority' ) );
break;
case 'UP_STATUS':
print_enum_string_option_list( 'status', config_get( 'bug_submit_status' ) );
break;
case 'UP_CATEGORY':
print_category_option_list();
break;
case 'VIEW_STATUS':
print_enum_string_option_list( 'view_state', config_get( 'default_bug_view_status' ) );
break;
case 'UP_TARGET_VERSION':
print_version_option_list( '', $t_projects, VERSION_FUTURE, true );
break;
case 'UP_PRODUCT_VERSION':
case 'UP_FIXED_IN_VERSION':
print_version_option_list( '', $t_projects, VERSION_ALL, true );
break;
}
echo '</select>';
}
?>
</td>
</tr>
<?php
if( isset( $t_question_title2 ) ) {
switch( $f_action ) {
case 'RESOLVE':
$t_show_product_version = ( ON == config_get( 'show_product_version' ) )
|| ( ( AUTO == config_get( 'show_product_version' ) )
&& ( count( version_get_all_rows( $t_project_id ) ) > 0 ) );
if( $t_show_product_version ) {
?>
<tr>
<th class="category">
<?php echo $t_question_title2 ?>
</th>
<td>
<select name="<?php echo $t_form2 ?>" class="input-sm">
<?php print_version_option_list( '', null, VERSION_ALL );?>
</select>
</td>
</tr>
<?php
}
break;
}
}
} else {
?>
<tr>
<th class="category" colspan="2">
<?php echo $t_question_title; ?>
</th>
</tr>
<?php
}
# signal plugin event for additional fields
event_signal( 'EVENT_BUG_ACTIONGROUP_FORM', array( $t_event_params ) );
if( $t_bugnote ) {
$t_default_bugnote_view_status = config_get( 'default_bugnote_view_status' );
$t_bugnote_private = $t_default_bugnote_view_status == VS_PRIVATE;
$t_bugnote_class = $t_bugnote_private ? 'form-control bugnote-private' : 'form-control';
?>
<tr>
<th class="category">
<?php echo lang_get( 'add_bugnote_title' ); ?>
</th>
<td>
<textarea name="bugnote_text" id="bugnote_text" class="<?php echo $t_bugnote_class ?>" cols="80" rows="7"></textarea>
</td>
</tr>
<?php
if( access_has_project_level( config_get( 'private_bugnote_threshold' ), $t_project_id ) ) {
?>
<tr>
<th class="category">
<?php echo lang_get( 'view_status' ) ?>
</th>
<td>
<?php
if( access_has_project_level( config_get( 'set_view_status_threshold' ), $t_project_id ) ) {
?>
<input type="checkbox" class="ace" name="private" <?php check_checked( $t_default_bugnote_view_status, VS_PRIVATE ); ?> />
<label class="lbl padding-6"><?php echo lang_get( 'private' ); ?></label>
<?php
} else {
echo get_enum_element( 'view_state', $t_default_bugnote_view_status );
}
?>
</td>
</tr>
<?php
}
}
?>
<tr class="spacer"></tr>
<?php bug_group_action_print_bug_list( $f_bug_arr ); ?>
<tr class="spacer"></tr>
</tbody>
</table>
</div>
</div>
<div class="widget-toolbox padding-8 clearfix">
<input type="submit" class="btn btn-primary btn-white btn-round" value="<?php echo $t_button_title ?>" />
</div>
</div>
</div>
</form>
</div>
</div>
<?php
bug_group_action_print_bottom();
|
<?php
# MantisBT - A PHP based bugtracking system
# MantisBT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# MantisBT 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 MantisBT. If not, see <http://www.gnu.org/licenses/>.
/**
* This page allows actions to be performed on an array of bugs
*
* @package MantisBT
* @copyright Copyright 2000 - 2002 Kenzaburo Ito - kenito@300baud.org
* @copyright Copyright 2002 MantisBT Team - mantisbt-dev@lists.sourceforge.net
* @link http://www.mantisbt.org
*
* @uses core.php
* @uses access_api.php
* @uses authentication_api.php
* @uses bug_api.php
* @uses bug_group_action_api.php
* @uses config_api.php
* @uses constant_inc.php
* @uses custom_field_api.php
* @uses event_api.php
* @uses form_api.php
* @uses gpc_api.php
* @uses helper_api.php
* @uses lang_api.php
* @uses print_api.php
* @uses string_api.php
* @uses utility_api.php
* @uses version_api.php
*/
require_once( 'core.php' );
require_api( 'access_api.php' );
require_api( 'authentication_api.php' );
require_api( 'bug_api.php' );
require_api( 'bug_group_action_api.php' );
require_api( 'config_api.php' );
require_api( 'constant_inc.php' );
require_api( 'custom_field_api.php' );
require_api( 'event_api.php' );
require_api( 'form_api.php' );
require_api( 'gpc_api.php' );
require_api( 'helper_api.php' );
require_api( 'lang_api.php' );
require_api( 'print_api.php' );
require_api( 'string_api.php' );
require_api( 'utility_api.php' );
require_api( 'version_api.php' );
auth_ensure_user_authenticated();
$f_action = gpc_get_string( 'action', '' );
$f_bug_arr = gpc_get_int_array( 'bug_arr', array() );
# redirects to all_bug_page if nothing is selected
if( is_blank( $f_action ) || ( 0 == count( $f_bug_arr ) ) ) {
print_header_redirect( 'view_all_bug_page.php' );
}
# run through the issues to see if they are all from one project
$t_project_id = ALL_PROJECTS;
$t_multiple_projects = false;
$t_projects = array();
# Array of parameters to be used with plugin event
$t_event_params = array();
$t_event_params['bug_ids'] = $f_bug_arr;
$t_event_params['action'] = $f_action;
$t_event_params['has_bugnote'] = false;
bug_cache_array_rows( $f_bug_arr );
foreach( $f_bug_arr as $t_bug_id ) {
$t_bug = bug_get( $t_bug_id );
if( $t_project_id != $t_bug->project_id ) {
if( ( $t_project_id != ALL_PROJECTS ) && !$t_multiple_projects ) {
$t_multiple_projects = true;
} else {
$t_project_id = $t_bug->project_id;
$t_projects[$t_project_id] = $t_project_id;
}
}
}
$t_event_params['multiple_projects'] = $t_multiple_projects;
if( $t_multiple_projects ) {
$t_project_id = ALL_PROJECTS;
$t_projects[ALL_PROJECTS] = ALL_PROJECTS;
}
# override the project if necessary
if( $t_project_id != helper_get_current_project() ) {
# in case the current project is not the same project of the bug we are viewing...
# ... override the current project. This to avoid problems with categories and handlers lists etc.
$g_project_override = $t_project_id;
}
define( 'BUG_ACTIONGROUP_INC_ALLOW', true );
$t_finished = false;
$t_bugnote = false;
$t_external_action_prefix = 'EXT_';
if( strpos( $f_action, $t_external_action_prefix ) === 0 ) {
$t_form_page = 'bug_actiongroup_ext_page.php';
require_once( $t_form_page );
exit;
}
$t_custom_group_actions = config_get( 'custom_group_actions' );
foreach( $t_custom_group_actions as $t_custom_group_action ) {
if( $f_action == $t_custom_group_action['action'] ) {
require_once( $t_custom_group_action['form_page'] );
exit;
}
}
# Check if user selected to update a custom field.
$t_custom_fields_prefix = 'custom_field_';
if( strpos( $f_action, $t_custom_fields_prefix ) === 0 ) {
$t_custom_field_id = (int)substr( $f_action, mb_strlen( $t_custom_fields_prefix ) );
$f_action = 'CUSTOM';
$t_event_params['action'] = $f_action;
}
# Form name
$t_form_name = 'bug_actiongroup_' . $f_action;
switch( $f_action ) {
# Use a simple confirmation page, if close or delete...
case 'CLOSE' :
$t_finished = true;
$t_question_title = lang_get( 'close_bugs_conf_msg' );
$t_button_title = lang_get( 'close_group_bugs_button' );
$t_bugnote = true;
break;
case 'DELETE' :
$t_finished = true;
$t_question_title = lang_get( 'delete_bugs_conf_msg' );
$t_button_title = lang_get( 'delete_group_bugs_button' );
break;
case 'SET_STICKY' :
$t_finished = true;
$t_question_title = lang_get( 'set_sticky_bugs_conf_msg' );
$t_button_title = lang_get( 'set_sticky_group_bugs_button' );
break;
# ...else we define the variables used in the form
case 'MOVE' :
$t_question_title = lang_get( 'move_bugs_conf_msg' );
$t_button_title = lang_get( 'move_group_bugs_button' );
$t_form = 'project_id';
break;
case 'COPY' :
$t_question_title = lang_get( 'copy_bugs_conf_msg' );
$t_button_title = lang_get( 'copy_group_bugs_button' );
$t_form = 'project_id';
break;
case 'ASSIGN' :
$t_question_title = lang_get( 'assign_bugs_conf_msg' );
$t_button_title = lang_get( 'assign_group_bugs_button' );
$t_form = 'assign';
break;
case 'RESOLVE' :
$t_question_title = lang_get( 'resolve_bugs_conf_msg' );
$t_button_title = lang_get( 'resolve_group_bugs_button' );
$t_form = 'resolution';
if( ALL_PROJECTS != $t_project_id ) {
$t_question_title2 = lang_get( 'fixed_in_version' );
$t_form2 = 'fixed_in_version';
}
$t_bugnote = true;
break;
case 'UP_PRIOR' :
$t_question_title = lang_get( 'priority_bugs_conf_msg' );
$t_button_title = lang_get( 'priority_group_bugs_button' );
$t_form = 'priority';
break;
case 'UP_STATUS' :
$t_question_title = lang_get( 'status_bugs_conf_msg' );
$t_button_title = lang_get( 'status_group_bugs_button' );
$t_form = 'status';
$t_bugnote = true;
break;
case 'UP_CATEGORY' :
$t_question_title = lang_get( 'category_bugs_conf_msg' );
$t_button_title = lang_get( 'category_group_bugs_button' );
$t_form = 'category';
break;
case 'VIEW_STATUS' :
$t_question_title = lang_get( 'view_status_bugs_conf_msg' );
$t_button_title = lang_get( 'view_status_group_bugs_button' );
$t_form = 'view_status';
break;
case 'UP_PRODUCT_VERSION':
$t_question_title = lang_get( 'product_version_bugs_conf_msg' );
$t_button_title = lang_get( 'product_version_group_bugs_button' );
$t_form = 'product_version';
break;
case 'UP_FIXED_IN_VERSION':
$t_question_title = lang_get( 'fixed_in_version_bugs_conf_msg' );
$t_button_title = lang_get( 'fixed_in_version_group_bugs_button' );
$t_form = 'fixed_in_version';
break;
case 'UP_TARGET_VERSION':
$t_question_title = lang_get( 'target_version_bugs_conf_msg' );
$t_button_title = lang_get( 'target_version_group_bugs_button' );
$t_form = 'target_version';
break;
case 'UP_DUE_DATE':
$t_question_title = lang_get( 'due_date_bugs_conf_msg' );
$t_button_title = lang_get( 'due_date_group_bugs_button' );
$t_form = 'due_date';
break;
case 'CUSTOM' :
$t_custom_field_def = custom_field_get_definition( $t_custom_field_id );
$t_question_title = sprintf( lang_get( 'actiongroup_menu_update_field' ),
string_attribute( lang_get_defaulted( $t_custom_field_def['name'] ) )
);
$t_button_title = $t_question_title;
$t_form = 'custom_field_' . $t_custom_field_id;
$t_event_params['custom_field_id'] = $t_custom_field_id;
break;
default:
trigger_error( ERROR_GENERIC, ERROR );
}
$t_event_params['has_bugnote'] = $t_bugnote;
bug_group_action_print_top();
?>
<div class="col-md-12 col-xs-12">
<?php
if( $t_multiple_projects ) {
echo '<div class="alert alert-warning"> <p class="bold">' . lang_get( 'multiple_projects' ) . '</p> </div>';
}
?>
<div id="action-group-div" class="form-container">
<form method="post" action="bug_actiongroup.php">
<?php echo form_security_field( $t_form_name ); ?>
<input type="hidden" name="action" value="<?php echo string_attribute( $f_action ) ?>" />
<?php
bug_group_action_print_hidden_fields( $f_bug_arr );
if( $f_action === 'CUSTOM' ) {
echo "<input type=\"hidden\" name=\"custom_field_id\" value=\"$t_custom_field_id\" />";
}
?>
<div class="widget-box widget-color-blue2">
<div class="widget-header widget-header-small">
<h4 class="widget-title lighter">
<?php echo $t_question_title ?>
</h4>
</div>
<div class="widget-body">
<div class="widget-main no-padding">
<div class="table-responsive">
<table class="table table-bordered table-condensed table-striped">
<tbody>
<?php
if( !$t_finished ) {
?>
<tr>
<th class="category">
<?php echo $t_question_title ?>
</th>
<td>
<?php
if( $f_action === 'CUSTOM' ) {
$t_custom_field_def = custom_field_get_definition( $t_custom_field_id );
$t_bug_id = null;
# if there is only one issue, use its current value as default, otherwise,
# use the default value specified in custom field definition.
if( count( $f_bug_arr ) == 1 ) {
$t_bug_id = $f_bug_arr[0];
}
print_custom_field_input( $t_custom_field_def, $t_bug_id );
} else if ( $f_action === 'UP_DUE_DATE' ) {
$t_date_to_display = '';
# if there is only one issue, use its current value as default
if( count( $f_bug_arr ) == 1 ) {
$t_bug_id = $f_bug_arr[0];
$t_bug = bug_get( $t_bug_id );
if( !date_is_null( $t_bug->due_date ) ) {
$t_date_to_display = date( config_get( 'normal_date_format' ), $t_bug->due_date );
}
}
echo '<input type="text" id="due_date" name="due_date" class="datetimepicker input-sm" size="16" maxlength="16" ' .
'data-picker-locale="' . lang_get_current_datetime_locale() .
'" data-picker-format="' . config_get( 'datetime_picker_format' ) . '"' .
'" value="' . $t_date_to_display . '" />';
echo '<i class="fa fa-calendar fa-xlg datetimepicker"></i>';
} else {
echo '<select name="' . $t_form . '" class="input-sm" required>';
switch( $f_action ) {
case 'COPY':
case 'MOVE':
print_project_option_list( null /* $p_project_id */, false /* $p_include_all_projects */,
null /* $p_filter_project_id */, false /* $p_trace */, true /* $p_can_report_only */ );
break;
case 'ASSIGN':
print_assign_to_option_list( 0, $t_project_id );
break;
case 'RESOLVE':
print_enum_string_option_list( 'resolution', config_get( 'bug_resolution_fixed_threshold' ) );
break;
case 'UP_PRIOR':
print_enum_string_option_list( 'priority', config_get( 'default_bug_priority' ) );
break;
case 'UP_STATUS':
print_enum_string_option_list( 'status', config_get( 'bug_submit_status' ) );
break;
case 'UP_CATEGORY':
print_category_option_list();
break;
case 'VIEW_STATUS':
print_enum_string_option_list( 'view_state', config_get( 'default_bug_view_status' ) );
break;
case 'UP_TARGET_VERSION':
print_version_option_list( '', $t_projects, VERSION_FUTURE, true );
break;
case 'UP_PRODUCT_VERSION':
case 'UP_FIXED_IN_VERSION':
print_version_option_list( '', $t_projects, VERSION_ALL, true );
break;
}
echo '</select>';
}
?>
</td>
</tr>
<?php
if( isset( $t_question_title2 ) ) {
switch( $f_action ) {
case 'RESOLVE':
$t_show_product_version = ( ON == config_get( 'show_product_version' ) )
|| ( ( AUTO == config_get( 'show_product_version' ) )
&& ( count( version_get_all_rows( $t_project_id ) ) > 0 ) );
if( $t_show_product_version ) {
?>
<tr>
<th class="category">
<?php echo $t_question_title2 ?>
</th>
<td>
<select name="<?php echo $t_form2 ?>" class="input-sm">
<?php print_version_option_list( '', null, VERSION_ALL );?>
</select>
</td>
</tr>
<?php
}
break;
}
}
} else {
?>
<tr>
<th class="category" colspan="2">
<?php echo $t_question_title; ?>
</th>
</tr>
<?php
}
# signal plugin event for additional fields
event_signal( 'EVENT_BUG_ACTIONGROUP_FORM', array( $t_event_params ) );
if( $t_bugnote ) {
$t_default_bugnote_view_status = config_get( 'default_bugnote_view_status' );
$t_bugnote_private = $t_default_bugnote_view_status == VS_PRIVATE;
$t_bugnote_class = $t_bugnote_private ? 'form-control bugnote-private' : 'form-control';
?>
<tr>
<th class="category">
<?php echo lang_get( 'add_bugnote_title' ); ?>
</th>
<td>
<textarea name="bugnote_text" id="bugnote_text" class="<?php echo $t_bugnote_class ?>" cols="80" rows="7"></textarea>
</td>
</tr>
<?php
if( access_has_project_level( config_get( 'private_bugnote_threshold' ), $t_project_id ) ) {
?>
<tr>
<th class="category">
<?php echo lang_get( 'view_status' ) ?>
</th>
<td>
<?php
if( access_has_project_level( config_get( 'set_view_status_threshold' ), $t_project_id ) ) {
?>
<input type="checkbox" class="ace" name="private" <?php check_checked( $t_default_bugnote_view_status, VS_PRIVATE ); ?> />
<label class="lbl padding-6"><?php echo lang_get( 'private' ); ?></label>
<?php
} else {
echo get_enum_element( 'view_state', $t_default_bugnote_view_status );
}
?>
</td>
</tr>
<?php
}
}
?>
<tr class="spacer"></tr>
<?php bug_group_action_print_bug_list( $f_bug_arr ); ?>
<tr class="spacer"></tr>
</tbody>
</table>
</div>
</div>
<div class="widget-toolbox padding-8 clearfix">
<input type="submit" class="btn btn-primary btn-white btn-round" value="<?php echo $t_button_title ?>" />
</div>
</div>
</div>
</form>
</div>
</div>
<?php
bug_group_action_print_bottom();
|
8c6f4d8859785b67fb80ac65100ac5259ed9237d
|
https://github.com/mantisbt/mantisbt
|
LiveDataMacroComponentList.java
|
java
|
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* 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.xwiki.livedata.internal.macro;
import java.lang.annotation.Documented;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import org.xwiki.livedata.internal.DefaultLiveDataConfigurationResolver;
import org.xwiki.livedata.internal.StringLiveDataConfigurationResolver;
import org.xwiki.skinx.internal.JsFileSkinExtension;
import org.xwiki.test.annotation.ComponentList;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Pack of default Component implementations that are needed for running the Live Data macro.
*
* @version $Id$
* @since 13.7RC1
* @since 13.6.1
* @since 13.4.3
*/
@Documented
@Retention(RUNTIME)
@Target({ TYPE, METHOD, ANNOTATION_TYPE })
@ComponentList({
LiveDataMacro.class,
DefaultLiveDataConfigurationResolver.class,
StringLiveDataConfigurationResolver.class,
JsFileSkinExtension.class
})
@Inherited
public @interface LiveDataMacroComponentList
{
}
|
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* 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.xwiki.livedata.internal.macro;
import java.lang.annotation.Documented;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import org.xwiki.livedata.internal.DefaultLiveDataConfigurationResolver;
import org.xwiki.livedata.internal.StringLiveDataConfigurationResolver;
import org.xwiki.skinx.internal.JsFileSkinExtension;
import org.xwiki.test.annotation.ComponentList;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Pack of default Component implementations that are needed for running the Live Data macro.
*
* @version $Id$
* @since 13.7RC1
* @since 13.6.1
* @since 13.4.3
*/
@Documented
@Retention(RUNTIME)
@Target({ TYPE, METHOD, ANNOTATION_TYPE })
@ComponentList({
LiveDataMacro.class,
DefaultLiveDataConfigurationResolver.class,
StringLiveDataConfigurationResolver.class,
JsFileSkinExtension.class,
LiveDataMacroConfiguration.class,
LiveDataMacroRights.class
})
@Inherited
public @interface LiveDataMacroComponentList
{
}
|
23d5ea9b23e84b5f3d1f1b2d5673fe8c774d0d79
|
https://github.com/xwiki/xwiki-platform
|
error.php
|
php
|
<?php
/* Copyright (c) 1998-2009 ILIAS open source, Extended GPL, see docs/LICENSE */
try
{
require_once("Services/Init/classes/class.ilInitialisation.php");
ilInitialisation::initILIAS();
$tpl->addBlockFile("CONTENT", "content", "tpl.error.html");
$lng->loadLanguageModule("error");
// #13515 - link back to "system" [see ilWebAccessChecker::sendError()]
$nd = $tree->getNodeData(ROOT_FOLDER_ID);
$txt = $lng->txt('error_back_to_repository');
$tpl->SetCurrentBlock("ErrorLink");
$tpl->SetVariable("TXT_LINK", $txt);
$tpl->SetVariable("LINK", ilUtil::secureUrl(ILIAS_HTTP_PATH . '/ilias.php?baseClass=ilRepositoryGUI&client_id=' . CLIENT_ID));
$tpl->ParseCurrentBlock();
$tpl->setCurrentBlock("content");
$tpl->setVariable("ERROR_MESSAGE", ($_SESSION["failure"]));
$tpl->setVariable("MESSAGE_HEADING", $lng->txt('error_sry_error'));
//$tpl->parseCurrentBlock();
ilSession::clear("referer");
ilSession::clear("message");
$tpl->show();
}
catch(Exception $e)
{
if(defined('DEVMODE') && DEVMODE)
{
throw $e;
}
die($e->getMessage());
}
|
<?php
/* Copyright (c) 1998-2009 ILIAS open source, Extended GPL, see docs/LICENSE */
try
{
require_once("Services/Init/classes/class.ilInitialisation.php");
ilInitialisation::initILIAS();
$tpl->addBlockFile("CONTENT", "content", "tpl.error.html");
$lng->loadLanguageModule("error");
// #13515 - link back to "system" [see ilWebAccessChecker::sendError()]
$nd = $tree->getNodeData(ROOT_FOLDER_ID);
$txt = $lng->txt('error_back_to_repository');
$tpl->SetCurrentBlock("ErrorLink");
$tpl->SetVariable("TXT_LINK", $txt);
$tpl->SetVariable("LINK", ilUtil::secureUrl(ILIAS_HTTP_PATH . '/ilias.php?baseClass=ilRepositoryGUI&client_id=' . CLIENT_ID));
$tpl->ParseCurrentBlock();
$tpl->setCurrentBlock("content");
$tpl->setVariable("ERROR_MESSAGE", ($_SESSION["failure"]));
$tpl->setVariable("MESSAGE_HEADING", $lng->txt('error_sry_error'));
//$tpl->parseCurrentBlock();
ilSession::clear("referer");
ilSession::clear("message");
$tpl->show();
}
catch(Exception $e)
{
if(defined('DEVMODE') && DEVMODE)
{
throw $e;
}
if (!($e instanceof \PDOException)) {
die($e->getMessage());
}
}
|
ca982e59d0b76c0374c9a7fd1acf2685ca57cf41
|
https://github.com/ilias-elearning/ilias
|
recover.php
|
php
|
<?php
include_once('internal/Smarty.class.php');
$main_smarty = new Smarty;
include('config.php');
include(mnminclude.'html1.php');
include(mnminclude.'link.php');
include(mnminclude.'smartyvariables.php');
// breadcrumbs and page title
$navwhere['text1'] = $main_smarty->get_config_vars('PLIGG_Visual_Breadcrumb_Recover_Password');
$navwhere['link1'] = getmyurl('loginNoVar', '');
$main_smarty->assign('navbar_where', $navwhere);
$main_smarty->assign('posttitle', $main_smarty->get_config_vars('PLIGG_Visual_Breadcrumb_Recover_Password'));
// sidebar
$main_smarty = do_sidebar($main_smarty);
// initialize error message variable
$errorMsg="";
// if user requests to logout
if($my_pligg_base){
if (strpos($_GET['return'],$my_pligg_base)!==0) $_GET['return']=$my_pligg_base . '/';
if (strpos($_POST['return'],$my_pligg_base)!==0) $_POST['return']=$my_pligg_base . '/';
}
$id=sanitize($_REQUEST['id'], 3);
$n=sanitize($_REQUEST['n'], 3);
$username=base64_decode($id);
$sql="SELECT * FROM `" . table_users . "` where `user_login` = '".$username."' AND `last_reset_request` = FROM_UNIXTIME('".$n."') AND user_level!='Spammer'";
$user = $db->get_row($sql);
if($user){
if( (isset($_POST["processrecover"]) && is_numeric($_POST["processrecover"]))){
if($_POST["processrecover"]==1){
$error=false;
$password = sanitize($_POST["reg_password"], 3);
$password2 = sanitize($_POST["reg_password2"], 3);
if(strlen($password) < 5 ) { // if password is less than 5 characters
$form_password_error[] = $main_smarty->get_config_vars('PLIGG_Visual_Register_Error_FiveCharPass');
$error = true;
}
if($password !== $password2) { // if both passwords do not match
$form_password_error[] = $main_smarty->get_config_vars('PLIGG_Visual_Register_Error_NoPassMatch');
$error = true;
}
if($error==false){
$saltedlogin = generateHash($username);
$to = $user->user_email;
$subject = $main_smarty->get_config_vars("PLIGG_Visual_Name").' '.$main_smarty->get_config_vars("PLIGG_PassEmail_Subject");
$body = sprintf(
$main_smarty->get_config_vars("PLIGG_PassEmail_PassBody"),
$main_smarty->get_config_vars("PLIGG_Visual_Name"),
$my_base_url . $my_pligg_base . '/login.php',
$user->user_login,
$password
);
$headers = 'From: ' . $main_smarty->get_config_vars("PLIGG_PassEmail_From") . "\r\n";
$headers .= "Content-type: text/html; charset=utf-8\r\n";
if (mail($to, $subject, $body, $headers))
{
$saltedPass = generateHash($password);
$db->query('UPDATE `' . table_users . "` SET `user_pass` = '$saltedPass' WHERE `user_login` = '".$user->user_login."'");
$db->query('UPDATE `' . table_users . '` SET `last_reset_request` = FROM_UNIXTIME('.time().') WHERE `user_login` = "'.$user->user_login.'"');
$current_user->Authenticate($user->user_login, $password);
$return = my_pligg_base.'/';
if(strpos($_SERVER['SERVER_SOFTWARE'], "IIS") && strpos(php_sapi_name(), "cgi") >= 0){
echo '<SCRIPT LANGUAGE="JavaScript">window.location="' . $return . '";</script>';
echo $main_smarty->get_config_vars('PLIGG_Visual_IIS_Logged_In') . '<a href = "'.$return.'">' . $main_smarty->get_config_vars('PLIGG_Visual_IIS_Continue') . '</a>';
} else {
header('Location: '.$return);
}
} else {
$errorMsg = $main_smarty->get_config_vars('PLIGG_Visual_Login_Delivery_Failed');
}
}
$main_smarty->assign('form_password_error', $form_password_error);
}
}
} else {
$errorMsg = $main_smarty->get_config_vars('PLIGG_Password_Invalid_URL');
}
// pagename
define('pagename', 'recover');
$main_smarty->assign('pagename', pagename);
// misc smarty
$main_smarty->assign('errorMsg',$errorMsg);
$main_smarty->assign('id',$id);
$main_smarty->assign('n',$n);
// show the template
$main_smarty->assign('tpl_center', $the_template . '/recover_password_center');
$main_smarty->display($the_template . '/pligg.tpl');
?>
|
<?php
include_once('internal/Smarty.class.php');
$main_smarty = new Smarty;
include('config.php');
include(mnminclude.'html1.php');
include(mnminclude.'link.php');
include(mnminclude.'smartyvariables.php');
// breadcrumbs and page title
$navwhere['text1'] = $main_smarty->get_config_vars('PLIGG_Visual_Breadcrumb_Recover_Password');
$navwhere['link1'] = getmyurl('loginNoVar', '');
$main_smarty->assign('navbar_where', $navwhere);
$main_smarty->assign('posttitle', $main_smarty->get_config_vars('PLIGG_Visual_Breadcrumb_Recover_Password'));
// sidebar
$main_smarty = do_sidebar($main_smarty);
// initialize error message variable
$errorMsg="";
// if user requests to logout
if($my_pligg_base){
if (strpos($_GET['return'],$my_pligg_base)!==0) $_GET['return']=$my_pligg_base . '/';
if (strpos($_POST['return'],$my_pligg_base)!==0) $_POST['return']=$my_pligg_base . '/';
}
$id=sanitize($_REQUEST['id'], 3);
$n=sanitize($_REQUEST['n'], 3);
$idTemp=base64_decode($id);
$username=sanitize($idTemp ,3);
$sql="SELECT * FROM `" . table_users . "` where `user_login` = '".$username."' AND `last_reset_request` = FROM_UNIXTIME('".$n."') AND user_level!='Spammer'";
$user = $db->get_row($sql);
if($user){
if( (isset($_POST["processrecover"]) && is_numeric($_POST["processrecover"]))){
if($_POST["processrecover"]==1){
$error=false;
$password = sanitize($_POST["reg_password"], 3);
$password2 = sanitize($_POST["reg_password2"], 3);
if(strlen($password) < 5 ) { // if password is less than 5 characters
$form_password_error[] = $main_smarty->get_config_vars('PLIGG_Visual_Register_Error_FiveCharPass');
$error = true;
}
if($password !== $password2) { // if both passwords do not match
$form_password_error[] = $main_smarty->get_config_vars('PLIGG_Visual_Register_Error_NoPassMatch');
$error = true;
}
if($error==false){
$saltedlogin = generateHash($username);
$to = $user->user_email;
$subject = $main_smarty->get_config_vars("PLIGG_Visual_Name").' '.$main_smarty->get_config_vars("PLIGG_PassEmail_Subject");
$body = sprintf(
$main_smarty->get_config_vars("PLIGG_PassEmail_PassBody"),
$main_smarty->get_config_vars("PLIGG_Visual_Name"),
$my_base_url . $my_pligg_base . '/login.php',
$user->user_login,
$password
);
$headers = 'From: ' . $main_smarty->get_config_vars("PLIGG_PassEmail_From") . "\r\n";
$headers .= "Content-type: text/html; charset=utf-8\r\n";
if (mail($to, $subject, $body, $headers))
{
$saltedPass = generateHash($password);
$db->query('UPDATE `' . table_users . "` SET `user_pass` = '$saltedPass' WHERE `user_login` = '".$user->user_login."'");
$db->query('UPDATE `' . table_users . '` SET `last_reset_request` = FROM_UNIXTIME('.time().') WHERE `user_login` = "'.$user->user_login.'"');
$current_user->Authenticate($user->user_login, $password);
$return = my_pligg_base.'/';
if(strpos($_SERVER['SERVER_SOFTWARE'], "IIS") && strpos(php_sapi_name(), "cgi") >= 0){
echo '<SCRIPT LANGUAGE="JavaScript">window.location="' . $return . '";</script>';
echo $main_smarty->get_config_vars('PLIGG_Visual_IIS_Logged_In') . '<a href = "'.$return.'">' . $main_smarty->get_config_vars('PLIGG_Visual_IIS_Continue') . '</a>';
} else {
header('Location: '.$return);
}
} else {
$errorMsg = $main_smarty->get_config_vars('PLIGG_Visual_Login_Delivery_Failed');
}
}
$main_smarty->assign('form_password_error', $form_password_error);
}
}
} else {
$errorMsg = $main_smarty->get_config_vars('PLIGG_Password_Invalid_URL');
}
// pagename
define('pagename', 'recover');
$main_smarty->assign('pagename', pagename);
// misc smarty
$main_smarty->assign('errorMsg',$errorMsg);
$main_smarty->assign('id',$id);
$main_smarty->assign('n',$n);
// show the template
$main_smarty->assign('tpl_center', $the_template . '/recover_password_center');
$main_smarty->display($the_template . '/pligg.tpl');
?>
|
4891c4d8742b9dabd67e7250840e3434865aebed
|
https://github.com/pligg/pligg-cms
|
example-form.php
|
php
|
<?php session_start(); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta name="Author" content="Jose Rodriguez" />
<title>Captcha test</title>
<style type="text/css">
body { font-family: sans-serif; font-size: 0.8em; padding: 20px; }
#result { border: 1px solid green; width: 300px; margin: 0 0 35px 0; padding: 10px 20px; font-weight: bold; }
#change-image { font-size: 0.8em; }
</style>
</head>
<body onload="document.getElementById('captcha-form').focus()">
<?php
/** Validate captcha */
if (!empty($_REQUEST['captcha'])) {
if (empty($_SESSION['captcha']) || trim(strtolower($_REQUEST['captcha'])) != $_SESSION['captcha']) {
$captcha_message = "Invalid captcha";
$style = "background-color: #FF606C";
} else {
$captcha_message = "Valid captcha";
$style = "background-color: #CCFF99";
}
echo <<<HTML
<div id="result" style="$style">
<h2>$captcha_message</h2>
<table>
<tr>
<td>Session CAPTCHA:</td>
<td>{$_SESSION['captcha']}</td>
</tr>
<tr>
<td>Form CAPTCHA:</td>
<td>{$_REQUEST['captcha']}</td>
</tr>
</table>
</div>
HTML;
unset($_SESSION['captcha']);
}
?>
<p><strong>Write the following word:</strong></p>
<form method="GET">
<img src="captcha.php" id="captcha" /><br/>
<!-- CHANGE TEXT LINK -->
<a href="#" onclick="
document.getElementById('captcha').src='captcha.php?'+Math.random();
document.getElementById('captcha-form').focus();"
id="change-image">Not readable? Change text.</a><br/><br/>
<input type="text" name="captcha" id="captcha-form" /><br/>
<input type="submit" />
</form>
</body>
</html>
|
<?php session_start(); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta name="Author" content="Jose Rodriguez" />
<title>Captcha test</title>
<style type="text/css">
body { font-family: sans-serif; font-size: 0.8em; padding: 20px; }
#result { border: 1px solid green; width: 300px; margin: 0 0 35px 0; padding: 10px 20px; font-weight: bold; }
#change-image { font-size: 0.8em; }
</style>
</head>
<body onload="document.getElementById('captcha-form').focus()">
<?php
/** Validate captcha */
if (!empty($_REQUEST['captcha'])) {
if (empty($_SESSION['captcha']) || trim(strtolower($_REQUEST['captcha'])) != $_SESSION['captcha']) {
$captcha_message = "Invalid captcha";
$style = "background-color: #FF606C";
} else {
$captcha_message = "Valid captcha";
$style = "background-color: #CCFF99";
}
$request_captcha = htmlspecialchars($_REQUEST['captcha']);
echo <<<HTML
<div id="result" style="$style">
<h2>$captcha_message</h2>
<table>
<tr>
<td>Session CAPTCHA:</td>
<td>{$_SESSION['captcha']}</td>
</tr>
<tr>
<td>Form CAPTCHA:</td>
<td>$request_captcha</td>
</tr>
</table>
</div>
HTML;
unset($_SESSION['captcha']);
}
?>
<p><strong>Write the following word:</strong></p>
<form method="GET">
<img src="captcha.php" id="captcha" /><br/>
<!-- CHANGE TEXT LINK -->
<a href="#" onclick="
document.getElementById('captcha').src='captcha.php?'+Math.random();
document.getElementById('captcha-form').focus();"
id="change-image">Not readable? Change text.</a><br/><br/>
<input type="text" name="captcha" id="captcha-form" /><br/>
<input type="submit" />
</form>
</body>
</html>
|
c84fb6b153bebaf228feee0cbf50728d27ae3f80
|
https://github.com/jianlinwei/cool-php-captcha
|
validate.php
|
php
|
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Validation callback.
*
* @package PhpMyAdmin-Setup
*/
/**
* Core libraries.
*/
require './lib/common.inc.php';
$validators = array();
require './libraries/config/Validator.php';
PMA_headerJSON();
$ids = PMA_isValid($_POST['id'], 'scalar') ? $_POST['id'] : null;
$vids = explode(',', $ids);
$vals = PMA_isValid($_POST['values'], 'scalar') ? $_POST['values'] : null;
$values = json_decode($vals);
if (!($values instanceof stdClass)) {
PMA_fatalError(__('Wrong data'));
}
$values = (array)$values;
$result = PMA\libraries\config\Validator::validate($GLOBALS['ConfigFile'], $vids, $values, true);
if ($result === false) {
$result = 'Wrong data or no validation for ' . $vids;
}
echo $result !== true ? json_encode($result) : '';
|
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Validation callback.
*
* @package PhpMyAdmin-Setup
*/
/**
* Core libraries.
*/
require './lib/common.inc.php';
$validators = array();
require './libraries/config/Validator.php';
PMA_headerJSON();
$ids = PMA_isValid($_POST['id'], 'scalar') ? $_POST['id'] : null;
$vids = explode(',', $ids);
$vals = PMA_isValid($_POST['values'], 'scalar') ? $_POST['values'] : null;
$values = json_decode($vals);
if (!($values instanceof stdClass)) {
PMA_fatalError(__('Wrong data'));
}
$values = (array)$values;
$result = PMA\libraries\config\Validator::validate($GLOBALS['ConfigFile'], $vids, $values, true);
if ($result === false) {
$result = sprintf(
__('Wrong data or no validation for %s'),
implode(',', $vids)
);
}
echo $result !== true ? json_encode($result) : '';
|
96e0aa35653ec0c66084a7e9343465e16c1f769b
|
https://github.com/phpmyadmin/phpmyadmin
|
attachment.php
|
php
|
<?php
/**
* Select an attachment and save it.
*
* PHP Version 5.5
*
* 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/.
*
* @category phpMyFAQ
* @author Thorsten Rinne <thorsten@phpmyfaq.de>
* @author Anatoliy Belsky <ab@php.net>
* @copyright 2002-2017 phpMyFAQ
* @license http://www.mozilla.org/MPL/2.0/ Mozilla Public License Version 2.0
* @link http://www.phpmyfaq.de
* @since 2002-09-17
*/
define('PMF_ROOT_DIR', dirname(__DIR__));
//
// Define the named constant used as a check by any included PHP file
//
define('IS_VALID_PHPMYFAQ', null);
//
// Bootstrapping
//
require PMF_ROOT_DIR.'/inc/Bootstrap.php';
/*
* Initialize attachment factory
*/
PMF_Attachment_Factory::init(
$faqConfig->get('records.attachmentsStorageType'),
$faqConfig->get('records.defaultAttachmentEncKey'),
$faqConfig->get('records.enableAttachmentEncryption')
);
$currentSave = PMF_Filter::filterInput(INPUT_POST, 'save', FILTER_SANITIZE_STRING);
$currentAction = PMF_Filter::filterInput(INPUT_GET, 'action', FILTER_SANITIZE_STRING);
$currentToken = PMF_Filter::filterInput(INPUT_POST, 'csrf', FILTER_SANITIZE_STRING);
$Language = new PMF_Language($faqConfig);
$LANGCODE = $Language->setLanguage($faqConfig->get('main.languageDetection'), $faqConfig->get('main.language'));
require_once PMF_ROOT_DIR.'/lang/language_en.php';
if (isset($LANGCODE) && PMF_Language::isASupportedLanguage($LANGCODE)) {
require_once PMF_ROOT_DIR.'/lang/language_'.$LANGCODE.'.php';
} else {
$LANGCODE = 'en';
}
$auth = false;
$user = PMF_User_CurrentUser::getFromCookie($faqConfig);
if (!$user instanceof PMF_User_CurrentUser) {
$user = PMF_User_CurrentUser::getFromSession($faqConfig);
}
if ($user) {
$auth = true;
} else {
$error = $PMF_LANG['ad_auth_sess'];
$user = null;
unset($user);
}
if (is_null($currentAction) || !is_null($currentSave)) {
?>
<!DOCTYPE html>
<!--[if IE 9 ]> <html lang="<?php echo $PMF_LANG['metaLanguage']; ?>" class="no-js ie9"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--> <html lang="<?php echo $PMF_LANG['metaLanguage']; ?>" class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<title><?php echo $faqConfig->get('main.titleFAQ') ?> - powered by phpMyFAQ</title>
<base href="<?php echo $faqConfig->getDefaultUrl() ?>admin/" />
<meta name="description" content="Only Chuck Norris can divide by zero.">
<meta name="author" content="phpMyFAQ Team">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="application-name" content="phpMyFAQ <?php echo $faqConfig->get('main.currentVersion') ?>">
<meta name="publisher" content="phpMyFAQ Team">
<link rel="stylesheet" href="assets/css/style.css?v=1">
<script src="../assets/js/modernizr.min.js"></script>
<script src="../assets/js/phpmyfaq.min.js"></script>
<link rel="shortcut icon" href="../assets/template/<?php echo PMF_Template::getTplSetName() ?>/favicon.ico">
</head>
<body class="attachments">
<?php
}
if (is_null($currentAction) && $auth && $user->perm->checkRight($user->getUserId(), 'addattachment')) {
$recordId = filter_input(INPUT_GET, 'record_id', FILTER_VALIDATE_INT);
$recordLang = filter_input(INPUT_GET, 'record_lang', FILTER_SANITIZE_STRING);
?>
<form action="attachment.php?action=save" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<fieldset>
<legend>
<?php echo $PMF_LANG['ad_att_addto'].' '.$PMF_LANG['ad_att_addto_2'] ?>
(max <?php echo round($faqConfig->get('records.maxAttachmentSize') / pow(1024, 2), 2) ?> MB)
</legend>
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $faqConfig->get('records.maxAttachmentSize') ?>">
<input type="hidden" name="record_id" value="<?php echo $recordId ?>">
<input type="hidden" name="record_lang" value="<?php echo $recordLang ?>">
<input type="hidden" name="save" value="TRUE">
<input type="hidden" name="csrf" value="<?php echo $user->getCsrfTokenFromSession() ?>">
<?php echo $PMF_LANG['ad_att_att'] ?>
<input name="userfile" type="file" id="fileUpload">
<button class="btn btn-primary" type="submit">
<?php echo $PMF_LANG['ad_att_butt'] ?>
</button>
<?php echo $PMF_LANG['msgAttachmentsFilesize'] ?>: <output id="filesize"></output>
</fieldset>
</form>
<?php
}
if (!isset($_SESSION['phpmyfaq_csrf_token']) || $_SESSION['phpmyfaq_csrf_token'] !== $currentToken) {
$auth = false;
}
if (!is_null($currentAction) && $auth && !$user->perm->checkRight($user->getUserId(), 'addattachment')) {
echo $PMF_LANG['err_NotAuth'];
}
if (!is_null($currentSave) && $currentSave == true && $auth &&
$user->perm->checkRight($user->getUserId(), 'addattachment')) {
$recordId = filter_input(INPUT_POST, 'record_id', FILTER_VALIDATE_INT);
$recordLang = filter_input(INPUT_POST, 'record_lang', FILTER_SANITIZE_STRING);
?>
<p>
<strong><?php echo $PMF_LANG['ad_att_addto'].' '.$PMF_LANG['ad_att_addto_2'] ?></strong>
</p>
<?php
if (is_uploaded_file($_FILES['userfile']['tmp_name']) && !($_FILES['userfile']['size'] > $faqConfig->get('records.maxAttachmentSize'))) {
$att = PMF_Attachment_Factory::create();
$att->setRecordId($recordId);
$att->setRecordLang($recordLang);
/*
* To add user defined key
* $att->setKey($somekey, false);
*/
try {
$uploaded = $att->save($_FILES['userfile']['tmp_name'], $_FILES['userfile']['name']);
if ($uploaded) {
echo '<p>'.$PMF_LANG['ad_att_suc'].'</p>';
} else {
throw new Exception();
}
} catch (Exception $e) {
$att->delete();
echo '<p>'.$PMF_LANG['ad_att_fail'].'</p>';
}
printf(
'<p class="text-center"><a href="#" onclick="addAttachmentLink(%d, \'%s\', %d, \'%s\');">%s</a></p>',
$att->getId(),
$att->getFilename(),
$recordId,
$recordLang,
$PMF_LANG['ad_att_close']
);
} else {
printf(
'<p>%s</p>',
sprintf(
$PMF_LANG['ad_attach_4'],
round($faqConfig->get('records.maxAttachmentSize') / pow(1024, 2), 2)
)
);
printf(
'<p class="text-center"><a href="javascript:;" onclick="closeWindow();">%s</a></p>',
$PMF_LANG['ad_att_close']
);
}
}
if (!is_null($currentSave) && $currentSave == true && $auth &&
!$user->perm->checkRight($user->getUserId(), 'addattachment')) {
echo $PMF_LANG['err_NotAuth'];
}
$faqConfig->getDb()->close();
?>
<script src="assets/js/uploadcheck.js"></script>
</body>
</html>
|
<?php
/**
* Select an attachment and save it.
*
* PHP Version 5.5
*
* 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/.
*
* @category phpMyFAQ
* @author Thorsten Rinne <thorsten@phpmyfaq.de>
* @author Anatoliy Belsky <ab@php.net>
* @copyright 2002-2017 phpMyFAQ
* @license http://www.mozilla.org/MPL/2.0/ Mozilla Public License Version 2.0
* @link http://www.phpmyfaq.de
* @since 2002-09-17
*/
define('PMF_ROOT_DIR', dirname(__DIR__));
//
// Define the named constant used as a check by any included PHP file
//
define('IS_VALID_PHPMYFAQ', null);
//
// Bootstrapping
//
require PMF_ROOT_DIR.'/inc/Bootstrap.php';
/*
* Initialize attachment factory
*/
PMF_Attachment_Factory::init(
$faqConfig->get('records.attachmentsStorageType'),
$faqConfig->get('records.defaultAttachmentEncKey'),
$faqConfig->get('records.enableAttachmentEncryption')
);
$currentSave = PMF_Filter::filterInput(INPUT_POST, 'save', FILTER_SANITIZE_STRING);
$currentAction = PMF_Filter::filterInput(INPUT_GET, 'action', FILTER_SANITIZE_STRING);
$currentToken = PMF_Filter::filterInput(INPUT_POST, 'csrf', FILTER_SANITIZE_STRING);
$Language = new PMF_Language($faqConfig);
$LANGCODE = $Language->setLanguage($faqConfig->get('main.languageDetection'), $faqConfig->get('main.language'));
require_once PMF_ROOT_DIR.'/lang/language_en.php';
if (isset($LANGCODE) && PMF_Language::isASupportedLanguage($LANGCODE)) {
require_once PMF_ROOT_DIR.'/lang/language_'.$LANGCODE.'.php';
} else {
$LANGCODE = 'en';
}
$auth = false;
$user = PMF_User_CurrentUser::getFromCookie($faqConfig);
if (!$user instanceof PMF_User_CurrentUser) {
$user = PMF_User_CurrentUser::getFromSession($faqConfig);
}
if ($user) {
$auth = true;
} else {
$error = $PMF_LANG['ad_auth_sess'];
$user = null;
unset($user);
}
if (is_null($currentAction) || !is_null($currentSave)) {
?>
<!DOCTYPE html>
<!--[if IE 9 ]> <html lang="<?php echo $PMF_LANG['metaLanguage']; ?>" class="no-js ie9"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--> <html lang="<?php echo $PMF_LANG['metaLanguage']; ?>" class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<title><?php echo $faqConfig->get('main.titleFAQ') ?> - powered by phpMyFAQ</title>
<base href="<?php echo $faqConfig->getDefaultUrl() ?>admin/" />
<meta name="description" content="Only Chuck Norris can divide by zero.">
<meta name="author" content="phpMyFAQ Team">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="application-name" content="phpMyFAQ <?php echo $faqConfig->get('main.currentVersion') ?>">
<meta name="publisher" content="phpMyFAQ Team">
<link rel="stylesheet" href="assets/css/style.css?v=1">
<script src="../assets/js/modernizr.min.js"></script>
<script src="../assets/js/phpmyfaq.min.js"></script>
<link rel="shortcut icon" href="../assets/template/<?php echo PMF_Template::getTplSetName() ?>/favicon.ico">
</head>
<body class="attachments">
<?php
}
if (is_null($currentAction) && $auth && $user->perm->checkRight($user->getUserId(), 'addattachment')) {
$recordId = filter_input(INPUT_GET, 'record_id', FILTER_VALIDATE_INT);
$recordLang = filter_input(INPUT_GET, 'record_lang', FILTER_SANITIZE_STRING);
?>
<form action="attachment.php?action=save" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<fieldset>
<legend>
<?php echo $PMF_LANG['ad_att_addto'].' '.$PMF_LANG['ad_att_addto_2'] ?>
(max <?php echo round($faqConfig->get('records.maxAttachmentSize') / pow(1024, 2), 2) ?> MB)
</legend>
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $faqConfig->get('records.maxAttachmentSize') ?>">
<input type="hidden" name="record_id" value="<?php echo $recordId ?>">
<input type="hidden" name="record_lang" value="<?php echo $recordLang ?>">
<input type="hidden" name="save" value="TRUE">
<input type="hidden" name="csrf" value="<?php echo $user->getCsrfTokenFromSession() ?>">
<?php echo $PMF_LANG['ad_att_att'] ?>
<input name="userfile" type="file" id="fileUpload">
<button class="btn btn-primary" type="submit">
<?php echo $PMF_LANG['ad_att_butt'] ?>
</button>
<?php echo $PMF_LANG['msgAttachmentsFilesize'] ?>: <output id="filesize"></output>
</fieldset>
</form>
<?php
}
if (!isset($_SESSION['phpmyfaq_csrf_token']) || $_SESSION['phpmyfaq_csrf_token'] !== $currentToken) {
$auth = false;
}
if (!is_null($currentAction) && $auth && !$user->perm->checkRight($user->getUserId(), 'addattachment')) {
echo $PMF_LANG['err_NotAuth'];
}
if (!is_null($currentSave) && $currentSave == true && $auth &&
$user->perm->checkRight($user->getUserId(), 'addattachment')) {
$recordId = filter_input(INPUT_POST, 'record_id', FILTER_VALIDATE_INT);
$recordLang = filter_input(INPUT_POST, 'record_lang', FILTER_SANITIZE_STRING);
?>
<p>
<strong><?php echo $PMF_LANG['ad_att_addto'].' '.$PMF_LANG['ad_att_addto_2'] ?></strong>
</p>
<?php
if (
is_uploaded_file($_FILES['userfile']['tmp_name']) &&
!($_FILES['userfile']['size'] > $faqConfig->get('records.maxAttachmentSize')) &&
$_FILES['userfile']['type'] !== "text/html"
) {
$att = PMF_Attachment_Factory::create();
$att->setRecordId($recordId);
$att->setRecordLang($recordLang);
/*
* To add user defined key
* $att->setKey($somekey, false);
*/
try {
$uploaded = $att->save($_FILES['userfile']['tmp_name'], $_FILES['userfile']['name']);
if ($uploaded) {
echo '<p>'.$PMF_LANG['ad_att_suc'].'</p>';
} else {
throw new Exception();
}
} catch (Exception $e) {
$att->delete();
echo '<p>'.$PMF_LANG['ad_att_fail'].'</p>';
}
printf(
'<p class="text-center"><a href="#" onclick="addAttachmentLink(%d, \'%s\', %d, \'%s\');">%s</a></p>',
$att->getId(),
$att->getFilename(),
$recordId,
$recordLang,
$PMF_LANG['ad_att_close']
);
} else {
printf(
'<p>%s</p>',
sprintf(
$PMF_LANG['ad_attach_4'],
round($faqConfig->get('records.maxAttachmentSize') / pow(1024, 2), 2)
)
);
printf(
'<p class="text-center"><a href="javascript:;" onclick="closeWindow();">%s</a></p>',
$PMF_LANG['ad_att_close']
);
}
}
if (!is_null($currentSave) && $currentSave == true && $auth &&
!$user->perm->checkRight($user->getUserId(), 'addattachment')) {
echo $PMF_LANG['err_NotAuth'];
}
$faqConfig->getDb()->close();
?>
<script src="assets/js/uploadcheck.js"></script>
</body>
</html>
|
5c3e4f96ff0ef6b91a3f0aa64eb28197c5cf5435
|
https://github.com/thorsten/phpmyfaq
|
images.php
|
php
|
<?php
/*
* This file is part of pluck, the easy content management system
* Copyright (c) pluck team
* http://www.pluck-cms.org
* Pluck is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* See docs/COPYING for the complete license.
*/
//Make sure the file isn't accessed directly.
defined('IN_PLUCK') or exit('Access denied!');
//Introduction text.
?>
<p>
<strong><?php echo $lang['images']['message']; ?></strong>
</p>
<?php run_hook('admin_images_before'); ?>
<div class="menudiv" style="display: inline-block; margin-top: 0;">
<span>
<img src="data/image/image.png" alt="" />
</span>
<form name="form1" method="post" action="" enctype="multipart/form-data" style="display: inline-block;">
<input type="file" name="imagefile" />
<input type="submit" name="submit" value="<?php echo $lang['general']['upload']; ?>" />
</form>
</div>
<?php
if (isset($_POST['submit'])) {
//Check if the file is JPG, PNG or GIF.
if (in_array($_FILES['imagefile']['type'], array('image/pjpeg', 'image/jpeg','image/png', 'image/gif'))) {
if (!copy($_FILES['imagefile']['tmp_name'], 'images/'.$_FILES['imagefile']['name']))
show_error($lang['general']['upload_failed'], 1);
else {
chmod('images/'.$_FILES['imagefile']['name'], 0666);
?>
<div class="menudiv">
<strong><?php echo $lang['images']['name']; ?></strong> <?php echo $_FILES['imagefile']['name']; ?>
<br />
<strong><?php echo $lang['images']['size']; ?></strong> <?php echo $_FILES['imagefile']['size'].' '.$lang['images']['bytes']; ?>
<br />
<strong><?php echo $lang['images']['type']; ?></strong> <?php echo $_FILES['imagefile']['type']; ?>
<br />
<strong><?php echo $lang['images']['success']; //TODO: Need to show this message another place, and with show_error(). ?></strong>
</div>
<?php
}
}
}
//Display list of uploaded pictures.
?>
<span class="kop2"><?php echo $lang['images']['uploaded']; ?></span>
<?php
//Show the uploaded images
$images = read_dir_contents('images', 'files');
if ($images) {
natcasesort($images);
foreach ($images as $image) {
?>
<div class="menudiv">
<span>
<img src="data/image/image.png" alt="" />
</span>
<span class="title-page"><?php echo $image; ?></span>
<span>
<a href="images/<?php echo $image; ?>" target="_blank">
<img src="data/image/view.png" alt="" />
</a>
</span>
<span>
<a href="?action=deleteimage&var1=<?php echo $image; ?>">
<img src="data/image/delete.png" title="<?php echo $lang['trashcan']['move_to_trash']; ?>" alt="<?php echo $lang['trashcan']['move_to_trash']; ?>" />
</a>
</span>
</div>
<?php
}
unset($images);
}
else
echo '<span class="kop4">'.$lang['general']['nothing_yet'].'</span>';
?>
<p style="margin-top: 10px;">
<a href="?action=page"><<< <?php echo $lang['general']['back']; ?></a>
</p>
|
<?php
/*
* This file is part of pluck, the easy content management system
* Copyright (c) pluck team
* http://www.pluck-cms.org
* Pluck is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* See docs/COPYING for the complete license.
*/
//Make sure the file isn't accessed directly.
defined('IN_PLUCK') or exit('Access denied!');
//Introduction text.
?>
<p>
<strong><?php echo $lang['images']['message']; ?></strong>
</p>
<?php run_hook('admin_images_before'); ?>
<div class="menudiv" style="display: inline-block; margin-top: 0;">
<span>
<img src="data/image/image.png" alt="" />
</span>
<form name="form1" method="post" action="" enctype="multipart/form-data" style="display: inline-block;">
<input type="file" name="imagefile" />
<input type="submit" name="submit" value="<?php echo $lang['general']['upload']; ?>" />
</form>
</div>
<?php
if (isset($_POST['submit'])) {
//Check if the file is JPG, PNG or GIF.
if (in_array($_FILES['imagefile']['type'], array('image/pjpeg', 'image/jpeg','image/png', 'image/gif'))) {
/* fix issue 44. Thanks to Klaus. */
$imagewhitelist = array('jfif', '.png', '.jpg', '.gif', 'jpeg');
if (!in_array(strtolower(substr($_FILES['imagefile']['name'], -4)), $imagewhitelist))
show_error($lang['general']['upload_failed'], 1);
/* end of fix issue 44. Thanks to Klaus. */
if (!copy($_FILES['imagefile']['tmp_name'], 'images/'.$_FILES['imagefile']['name']))
show_error($lang['general']['upload_failed'], 1);
else {
chmod('images/'.$_FILES['imagefile']['name'], 0666);
?>
<div class="menudiv">
<strong><?php echo $lang['images']['name']; ?></strong> <?php echo $_FILES['imagefile']['name']; ?>
<br />
<strong><?php echo $lang['images']['size']; ?></strong> <?php echo $_FILES['imagefile']['size'].' '.$lang['images']['bytes']; ?>
<br />
<strong><?php echo $lang['images']['type']; ?></strong> <?php echo $_FILES['imagefile']['type']; ?>
<br />
<strong><?php echo $lang['images']['success']; //TODO: Need to show this message another place, and with show_error(). ?></strong>
</div>
<?php
}
}
}
//Display list of uploaded pictures.
?>
<span class="kop2"><?php echo $lang['images']['uploaded']; ?></span>
<?php
//Show the uploaded images
$images = read_dir_contents('images', 'files');
if ($images) {
natcasesort($images);
foreach ($images as $image) {
?>
<div class="menudiv">
<span>
<img src="data/image/image.png" alt="" />
</span>
<span class="title-page"><?php echo $image; ?></span>
<span>
<a href="images/<?php echo $image; ?>" target="_blank">
<img src="data/image/view.png" alt="" />
</a>
</span>
<span>
<a href="?action=deleteimage&var1=<?php echo $image; ?>">
<img src="data/image/delete.png" title="<?php echo $lang['trashcan']['move_to_trash']; ?>" alt="<?php echo $lang['trashcan']['move_to_trash']; ?>" />
</a>
</span>
</div>
<?php
}
unset($images);
}
else
echo '<span class="kop4">'.$lang['general']['nothing_yet'].'</span>';
?>
<p style="margin-top: 10px;">
<a href="?action=page"><<< <?php echo $lang['general']['back']; ?></a>
</p>
|
09f0ab871bf633973cfd9fc4fe59d4a912397cf8
|
https://github.com/pluck-cms/pluck
|
menu_list_update.php
|
php
|
<?php
$sub_menu = "100290";
include_once('./_common.php');
check_demo();
if ($is_admin != 'super')
alert('최고관리자만 접근 가능합니다.');
check_admin_token();
// 이전 메뉴정보 삭제
$sql = " delete from {$g5['menu_table']} ";
sql_query($sql);
$group_code = null;
$primary_code = null;
$count = count($_POST['code']);
for ($i=0; $i<$count; $i++)
{
$_POST = array_map_deep('trim', $_POST);
$_POST['me_link'][$i] = is_array($_POST['me_link']) ? clean_xss_tags(clean_xss_attributes($_POST['me_link'][$i], 1)) : '';
$code = is_array($_POST['code']) ? strip_tags($_POST['code'][$i]) : '';
$me_name = is_array($_POST['me_name']) ? strip_tags($_POST['me_name'][$i]) : '';
$me_link = (preg_match('/^javascript/i', $_POST['me_link'][$i]) || preg_match('/script:/i', $_POST['me_link'][$i])) ? G5_URL : strip_tags(clean_xss_attributes($_POST['me_link'][$i]));
if(!$code || !$me_name || !$me_link)
continue;
$sub_code = '';
if($group_code == $code) {
$sql = " select MAX(SUBSTRING(me_code,3,2)) as max_me_code
from {$g5['menu_table']}
where SUBSTRING(me_code,1,2) = '$primary_code' ";
$row = sql_fetch($sql);
$sub_code = base_convert($row['max_me_code'], 36, 10);
$sub_code += 36;
$sub_code = base_convert($sub_code, 10, 36);
$me_code = $primary_code.$sub_code;
} else {
$sql = " select MAX(SUBSTRING(me_code,1,2)) as max_me_code
from {$g5['menu_table']}
where LENGTH(me_code) = '2' ";
$row = sql_fetch($sql);
$me_code = base_convert($row['max_me_code'], 36, 10);
$me_code += 36;
$me_code = base_convert($me_code, 10, 36);
$group_code = $code;
$primary_code = $me_code;
}
// 메뉴 등록
$sql = " insert into {$g5['menu_table']}
set me_code = '".$me_code."',
me_name = '".$me_name."',
me_link = '".$me_link."',
me_target = '".sql_real_escape_string(strip_tags($_POST['me_target'][$i]))."',
me_order = '".sql_real_escape_string(strip_tags($_POST['me_order'][$i]))."',
me_use = '".sql_real_escape_string(strip_tags($_POST['me_use'][$i]))."',
me_mobile_use = '".sql_real_escape_string(strip_tags($_POST['me_mobile_use'][$i]))."' ";
sql_query($sql);
}
run_event('admin_menu_list_update');
goto_url('./menu_list.php');
|
<?php
$sub_menu = "100290";
include_once('./_common.php');
check_demo();
if ($is_admin != 'super')
alert('최고관리자만 접근 가능합니다.');
check_admin_token();
// 이전 메뉴정보 삭제
$sql = " delete from {$g5['menu_table']} ";
sql_query($sql);
$group_code = null;
$primary_code = null;
$count = count($_POST['code']);
for ($i=0; $i<$count; $i++)
{
$_POST = array_map_deep('trim', $_POST);
if(preg_match('/^javascript/i', preg_replace('/[ ]{1,}|[\t]/', '', $_POST['me_link'][$i]))){
$_POST['me_link'][$i] = G5_URL;
}
$_POST['me_link'][$i] = is_array($_POST['me_link']) ? clean_xss_tags(clean_xss_attributes(preg_replace('/[ ]{2,}|[\t]/', '', $_POST['me_link'][$i]), 1)) : '';
$code = is_array($_POST['code']) ? strip_tags($_POST['code'][$i]) : '';
$me_name = is_array($_POST['me_name']) ? strip_tags($_POST['me_name'][$i]) : '';
$me_link = (preg_match('/^javascript/i', $_POST['me_link'][$i]) || preg_match('/script:/i', $_POST['me_link'][$i])) ? G5_URL : strip_tags(clean_xss_attributes($_POST['me_link'][$i]));
if(!$code || !$me_name || !$me_link)
continue;
$sub_code = '';
if($group_code == $code) {
$sql = " select MAX(SUBSTRING(me_code,3,2)) as max_me_code
from {$g5['menu_table']}
where SUBSTRING(me_code,1,2) = '$primary_code' ";
$row = sql_fetch($sql);
$sub_code = base_convert($row['max_me_code'], 36, 10);
$sub_code += 36;
$sub_code = base_convert($sub_code, 10, 36);
$me_code = $primary_code.$sub_code;
} else {
$sql = " select MAX(SUBSTRING(me_code,1,2)) as max_me_code
from {$g5['menu_table']}
where LENGTH(me_code) = '2' ";
$row = sql_fetch($sql);
$me_code = base_convert($row['max_me_code'], 36, 10);
$me_code += 36;
$me_code = base_convert($me_code, 10, 36);
$group_code = $code;
$primary_code = $me_code;
}
// 메뉴 등록
$sql = " insert into {$g5['menu_table']}
set me_code = '".$me_code."',
me_name = '".$me_name."',
me_link = '".$me_link."',
me_target = '".sql_real_escape_string(strip_tags($_POST['me_target'][$i]))."',
me_order = '".sql_real_escape_string(strip_tags($_POST['me_order'][$i]))."',
me_use = '".sql_real_escape_string(strip_tags($_POST['me_use'][$i]))."',
me_mobile_use = '".sql_real_escape_string(strip_tags($_POST['me_mobile_use'][$i]))."' ";
sql_query($sql);
}
run_event('admin_menu_list_update');
goto_url('./menu_list.php');
|
70daa537adfa47b87af12d85f1e698fff01785ff
|
https://github.com/gnuboard/youngcart5
|
plugin.php
|
php
|
<?php
// +-----------------------------------------------------------------------+
// | Piwigo - a PHP based photo gallery |
// +-----------------------------------------------------------------------+
// | Copyright(C) 2008-2016 Piwigo Team http://piwigo.org |
// | Copyright(C) 2003-2008 PhpWebGallery Team http://phpwebgallery.net |
// | Copyright(C) 2002-2003 Pierrick LE GALL http://le-gall.net/pierrick |
// +-----------------------------------------------------------------------+
// | This program is free software; you can redistribute it and/or modify |
// | it under the terms of the GNU General Public License as published by |
// | the Free Software Foundation |
// | |
// | This program is distributed in the hope that it will be useful, but |
// | WITHOUT ANY WARRANTY; without even the implied warranty of |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
// | General Public License for more details. |
// | |
// | You should have received a copy of the GNU General Public License |
// | along with this program; if not, write to the Free Software |
// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
// | USA. |
// +-----------------------------------------------------------------------+
if( !defined("PHPWG_ROOT_PATH") )
{
die ("Hacking attempt!");
}
include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
check_status(ACCESS_ADMINISTRATOR);
$sections = explode('/', $_GET['section'] );
for ($i=0; $i<count($sections); $i++)
{
if (empty($sections[$i]) or $sections[$i]=='..')
{
unset($sections[$i]);
$i--;
}
}
if (count($sections)<2)
{
die('Invalid plugin URL');
}
$plugin_id = $sections[0];
if (!preg_match('/^[\w-]+$/', $plugin_id))
{
die('Invalid plugin identifier');
}
if ( !isset($pwg_loaded_plugins[$plugin_id]) )
{
die('Invalid URL - plugin '.$plugin_id.' not active');
}
$filename = PHPWG_PLUGINS_PATH.implode('/', $sections);
if (is_file($filename))
{
include_once($filename);
}
else
{
die('Missing file '.htmlentities($filename));
}
?>
|
<?php
// +-----------------------------------------------------------------------+
// | Piwigo - a PHP based photo gallery |
// +-----------------------------------------------------------------------+
// | Copyright(C) 2008-2016 Piwigo Team http://piwigo.org |
// | Copyright(C) 2003-2008 PhpWebGallery Team http://phpwebgallery.net |
// | Copyright(C) 2002-2003 Pierrick LE GALL http://le-gall.net/pierrick |
// +-----------------------------------------------------------------------+
// | This program is free software; you can redistribute it and/or modify |
// | it under the terms of the GNU General Public License as published by |
// | the Free Software Foundation |
// | |
// | This program is distributed in the hope that it will be useful, but |
// | WITHOUT ANY WARRANTY; without even the implied warranty of |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
// | General Public License for more details. |
// | |
// | You should have received a copy of the GNU General Public License |
// | along with this program; if not, write to the Free Software |
// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
// | USA. |
// +-----------------------------------------------------------------------+
if( !defined("PHPWG_ROOT_PATH") )
{
die ("Hacking attempt!");
}
include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
check_status(ACCESS_ADMINISTRATOR);
$sections = explode('/', $_GET['section'] );
for ($i=0; $i<count($sections); $i++)
{
if (empty($sections[$i]))
{
unset($sections[$i]);
$i--;
continue;
}
if ($sections[$i] == '..' or !preg_match('/^[a-zA-Z_\.-]+$/', $sections[$i]))
{
die('invalid section token ['.htmlentities($sections[$i]).']');
}
}
if (count($sections)<2)
{
die('Invalid plugin URL');
}
$plugin_id = $sections[0];
if (!preg_match('/^[\w-]+$/', $plugin_id))
{
die('Invalid plugin identifier');
}
if ( !isset($pwg_loaded_plugins[$plugin_id]) )
{
die('Invalid URL - plugin '.$plugin_id.' not active');
}
$filename = PHPWG_PLUGINS_PATH.implode('/', $sections);
if (is_file($filename))
{
include_once($filename);
}
else
{
die('Missing file '.htmlentities($filename));
}
?>
|
8796e43aa344681d92a92e1f9b985409d4f36e31
|
https://github.com/piwigo/piwigo
|
plugin.php
|
php
|
<?php
// +-----------------------------------------------------------------------+
// | Piwigo - a PHP based photo gallery |
// +-----------------------------------------------------------------------+
// | Copyright(C) 2008-2016 Piwigo Team http://piwigo.org |
// | Copyright(C) 2003-2008 PhpWebGallery Team http://phpwebgallery.net |
// | Copyright(C) 2002-2003 Pierrick LE GALL http://le-gall.net/pierrick |
// +-----------------------------------------------------------------------+
// | This program is free software; you can redistribute it and/or modify |
// | it under the terms of the GNU General Public License as published by |
// | the Free Software Foundation |
// | |
// | This program is distributed in the hope that it will be useful, but |
// | WITHOUT ANY WARRANTY; without even the implied warranty of |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
// | General Public License for more details. |
// | |
// | You should have received a copy of the GNU General Public License |
// | along with this program; if not, write to the Free Software |
// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
// | USA. |
// +-----------------------------------------------------------------------+
if( !defined("PHPWG_ROOT_PATH") )
{
die ("Hacking attempt!");
}
include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
check_status(ACCESS_ADMINISTRATOR);
$sections = explode('/', $_GET['section'] );
for ($i=0; $i<count($sections); $i++)
{
if (empty($sections[$i]) or $sections[$i]=='..')
{
unset($sections[$i]);
$i--;
}
}
if (count($sections)<2)
{
die('Invalid plugin URL');
}
$plugin_id = $sections[0];
if (!preg_match('/^[\w-]+$/', $plugin_id))
{
die('Invalid plugin identifier');
}
if ( !isset($pwg_loaded_plugins[$plugin_id]) )
{
die('Invalid URL - plugin '.$plugin_id.' not active');
}
$filename = PHPWG_PLUGINS_PATH.implode('/', $sections);
if (is_file($filename))
{
include_once($filename);
}
else
{
die('Missing file '.htmlentities($filename));
}
?>
|
<?php
// +-----------------------------------------------------------------------+
// | Piwigo - a PHP based photo gallery |
// +-----------------------------------------------------------------------+
// | Copyright(C) 2008-2016 Piwigo Team http://piwigo.org |
// | Copyright(C) 2003-2008 PhpWebGallery Team http://phpwebgallery.net |
// | Copyright(C) 2002-2003 Pierrick LE GALL http://le-gall.net/pierrick |
// +-----------------------------------------------------------------------+
// | This program is free software; you can redistribute it and/or modify |
// | it under the terms of the GNU General Public License as published by |
// | the Free Software Foundation |
// | |
// | This program is distributed in the hope that it will be useful, but |
// | WITHOUT ANY WARRANTY; without even the implied warranty of |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
// | General Public License for more details. |
// | |
// | You should have received a copy of the GNU General Public License |
// | along with this program; if not, write to the Free Software |
// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
// | USA. |
// +-----------------------------------------------------------------------+
if( !defined("PHPWG_ROOT_PATH") )
{
die ("Hacking attempt!");
}
include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
check_status(ACCESS_ADMINISTRATOR);
$sections = explode('/', $_GET['section'] );
for ($i=0; $i<count($sections); $i++)
{
if (empty($sections[$i]))
{
unset($sections[$i]);
$i--;
continue;
}
if ($sections[$i] == '..' or !preg_match('/^[a-zA-Z_\.-]+$/', $sections[$i]))
{
die('invalid section token ['.htmlentities($sections[$i]).']');
}
}
if (count($sections)<2)
{
die('Invalid plugin URL');
}
$plugin_id = $sections[0];
if (!preg_match('/^[\w-]+$/', $plugin_id))
{
die('Invalid plugin identifier');
}
if ( !isset($pwg_loaded_plugins[$plugin_id]) )
{
die('Invalid URL - plugin '.$plugin_id.' not active');
}
$filename = PHPWG_PLUGINS_PATH.implode('/', $sections);
if (is_file($filename))
{
include_once($filename);
}
else
{
die('Missing file '.htmlentities($filename));
}
?>
|
9004fdfc0b4a11cb32e9e15a5f67e4ec827e82dc
|
https://github.com/piwigo/piwigo
|
save_taxes.php
|
php
|
<?php
/*
This file is part of Webfinance.
Webfinance is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Webfinance 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 Webfinance; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
?>
<?php
//
// This file is part of « Webfinance »
//
// Copyright (c) 2004-2006 NBI SARL
// Author : Nicolas Bouthors <nbouthors@nbi.fr>
//
// You can use and redistribute this file under the term of the GNU GPL v2.0
//
// $Id: save_taxes.php 531 2007-06-13 12:32:31Z thierry $
require("../inc/main.php");
must_login();
if ($_GET['action'] == "delete") {
mysql_query("DELETE FROM webfinance_pref WHERE id_pref=".$_GET['id']);
$_SESSION['message'] = _('Tax deleted');
header("Location: preferences.php?tab=Taxes");
exit;
}
foreach ($_POST['taxes'] as $id=>$data) {
if ($id == "new") {
if (!empty($data['taxe']) ) {
$q = sprintf("INSERT INTO webfinance_pref SET type_pref='taxe_%s', value='%s'" , $data['taxe'], $data['value']);
$_SESSION['message'] = _('Tax added');
}
} else {
$q = sprintf("UPDATE webfinance_pref SET type_pref='taxe_%s', value='%s' WHERE id_pref=%d " , $data['taxe'], $data['value'] , $id );
$_SESSION['message'] = _('Tax updated');
}
if(isset($q) AND !empty($q))
mysql_query($q) or wf_mysqldie();
}
header("Location: preferences.php?tab=Taxes");
exit;
?>
|
<?php
/*
This file is part of Webfinance.
Webfinance is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Webfinance 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 Webfinance; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
?>
<?php
//
// This file is part of « Webfinance »
//
// Copyright (c) 2004-2006 NBI SARL
// Author : Nicolas Bouthors <nbouthors@nbi.fr>
//
// You can use and redistribute this file under the term of the GNU GPL v2.0
//
// $Id: save_taxes.php 531 2007-06-13 12:32:31Z thierry $
require("../inc/main.php");
must_login();
if ($_GET['action'] == "delete") {
$_GET['id'] = mysql_real_escape_string($_GET['id']);
mysql_query("DELETE FROM webfinance_pref WHERE id_pref=".$_GET['id']);
$_SESSION['message'] = _('Tax deleted');
header("Location: preferences.php?tab=Taxes");
exit;
}
foreach ($_POST['taxes'] as $id=>$data) {
if ($id == "new") {
if (!empty($data['taxe']) ) {
$q = sprintf("INSERT INTO webfinance_pref SET type_pref='taxe_%s', value='%s'" , $data['taxe'], $data['value']);
$_SESSION['message'] = _('Tax added');
}
} else {
$q = sprintf("UPDATE webfinance_pref SET type_pref='taxe_%s', value='%s' WHERE id_pref=%d " , $data['taxe'], $data['value'] , $id );
$_SESSION['message'] = _('Tax updated');
}
if(isset($q) AND !empty($q))
mysql_query($q) or wf_mysqldie();
}
header("Location: preferences.php?tab=Taxes");
exit;
?>
|
306f170ca2a8203ae3d8f51fb219ba9e05b945e1
|
https://github.com/fanzila/webfinance
|
inventory.php
|
php
|
<?php
/**
* ---------------------------------------------------------------------
*
* GLPI - Gestionnaire Libre de Parc Informatique
*
* http://glpi-project.org
*
* @copyright 2015-2022 Teclib' and contributors.
* @copyright 2003-2014 by the INDEPNET Development Team.
* @licence https://www.gnu.org/licenses/gpl-3.0.html
*
* ---------------------------------------------------------------------
*
* LICENSE
*
* This file is part of GLPI.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* ---------------------------------------------------------------------
*/
use Glpi\Inventory\Request;
if (!defined('GLPI_ROOT')) {
include(__DIR__ . '/../inc/includes.php');
}
$inventory_request = new Request();
$inventory_request->handleHeaders();
$handle = true;
if (isset($_GET['refused'])) {
$refused = new RefusedEquipment();
if ($refused->getFromDB($_GET['refused']) && ($inventory_file = $refused->getInventoryFileName()) !== null) {
$contents = file_get_contents($inventory_file);
} else {
trigger_error(
sprintf('Invalid RefusedEquipment "%s" or inventory file missing', $_GET['refused']),
E_USER_WARNING
);
$contents = '';
}
} else if (!isCommandLine() && $_SERVER['REQUEST_METHOD'] != 'POST') {
if (isset($_GET['action']) && $_GET['action'] == 'getConfig') {
/**
* Even if Fusion protocol is not supported for getConfig requests, they
* should be handled and answered with a json content type
*/
$inventory_request->handleContentType('application/json');
$inventory_request->addError('Protocol not supported', 400);
} else {
// Method not allowed answer without content
$inventory_request->addError(null, 405);
}
$handle = false;
} else {
if (isCommandLine()) {
$f = fopen('php://stdin', 'r');
$contents = '';
while ($line = fgets($f)) {
$contents .= $line;
}
fclose($f);
} else {
$contents = file_get_contents("php://input");
}
}
if ($handle === true) {
try {
$inventory_request->handleRequest($contents);
} catch (\Exception $e) {
$inventory_request->addError($e->getMessage());
}
}
if (isset($_GET['refused'])) {
$redirect_url = $refused->handleInventoryRequest($inventory_request);
Html::redirect($redirect_url);
} else {
if (isCommandLine()) {
exit(0);
}
$headers = $inventory_request->getHeaders(true);
http_response_code($inventory_request->getHttpResponseCode());
foreach ($headers as $key => $value) {
header(sprintf('%1$s: %2$s', $key, $value));
}
echo $inventory_request->getResponse();
}
|
<?php
/**
* ---------------------------------------------------------------------
*
* GLPI - Gestionnaire Libre de Parc Informatique
*
* http://glpi-project.org
*
* @copyright 2015-2022 Teclib' and contributors.
* @copyright 2003-2014 by the INDEPNET Development Team.
* @licence https://www.gnu.org/licenses/gpl-3.0.html
*
* ---------------------------------------------------------------------
*
* LICENSE
*
* This file is part of GLPI.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* ---------------------------------------------------------------------
*/
use Glpi\Inventory\Request;
if (!defined('GLPI_ROOT')) {
include(__DIR__ . '/../inc/includes.php');
}
$inventory_request = new Request();
$inventory_request->handleHeaders();
$handle = true;
if (isset($_GET['refused'])) {
Session::checkRight("config", READ);
$refused = new RefusedEquipment();
if ($refused->getFromDB($_GET['refused']) && ($inventory_file = $refused->getInventoryFileName()) !== null) {
$contents = file_get_contents($inventory_file);
} else {
trigger_error(
sprintf('Invalid RefusedEquipment "%s" or inventory file missing', $_GET['refused']),
E_USER_WARNING
);
$contents = '';
}
} else if (!isCommandLine() && $_SERVER['REQUEST_METHOD'] != 'POST') {
if (isset($_GET['action']) && $_GET['action'] == 'getConfig') {
/**
* Even if Fusion protocol is not supported for getConfig requests, they
* should be handled and answered with a json content type
*/
$inventory_request->handleContentType('application/json');
$inventory_request->addError('Protocol not supported', 400);
} else {
// Method not allowed answer without content
$inventory_request->addError(null, 405);
}
$handle = false;
} else {
if (isCommandLine()) {
$f = fopen('php://stdin', 'r');
$contents = '';
while ($line = fgets($f)) {
$contents .= $line;
}
fclose($f);
} else {
$contents = file_get_contents("php://input");
}
}
if ($handle === true) {
try {
$inventory_request->handleRequest($contents);
} catch (\Exception $e) {
$inventory_request->addError($e->getMessage());
}
}
if (isset($_GET['refused'])) {
$redirect_url = $refused->handleInventoryRequest($inventory_request);
Html::redirect($redirect_url);
} else {
if (isCommandLine()) {
exit(0);
}
$headers = $inventory_request->getHeaders(true);
http_response_code($inventory_request->getHttpResponseCode());
foreach ($headers as $key => $value) {
header(sprintf('%1$s: %2$s', $key, $value));
}
echo $inventory_request->getResponse();
}
|
9953a644777e4167b06db9e14fc93b945a557be5
|
https://github.com/glpi-project/glpi
|
normalization.php
|
php
|
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Normalization process (temporarily specific to 1NF)
*
* @package PhpMyAdmin
*/
/**
*
*/
require_once 'libraries/common.inc.php';
require_once 'libraries/transformations.lib.php';
require_once 'libraries/normalization.lib.php';
require_once 'libraries/Index.class.php';
if (isset($_REQUEST['getColumns'])) {
$html = '<option selected disabled>' . __('Select one…') . '</option>'
. '<option value="no_such_col">' . __('No such column') . '</option>';
//get column whose datatype falls under string category
$html .= PMA_getHtmlForColumnsList(
$db,
$table,
_pgettext('string types', 'String')
);
echo $html;
exit;
}
if (isset($_REQUEST['splitColumn'])) {
$num_fields = $_REQUEST['numFields'];
$html = PMA_getHtmlForCreateNewColumn($num_fields, $db, $table);
$html .= PMA_URL_getHiddenInputs($db, $table);
echo $html;
exit;
}
if (isset($_REQUEST['addNewPrimary'])) {
$num_fields = 1;
$columnMeta = array('Field'=>$table . "_id", 'Extra'=>'auto_increment');
$html = PMA_getHtmlForCreateNewColumn(
$num_fields, $db, $table, $columnMeta
);
$html .= PMA_URL_getHiddenInputs($db, $table);
echo $html;
exit;
}
if (isset($_REQUEST['findPdl'])) {
$html = PMA_findPartialDependencies($table, $db);
echo $html;
exit;
}
if (isset($_REQUEST['getNewTables2NF'])) {
$partialDependencies = json_decode($_REQUEST['pd']);
$html = PMA_getHtmlForNewTables2NF($partialDependencies, $table);
echo $html;
exit;
}
if (isset($_REQUEST['getNewTables3NF'])) {
$dependencies = json_decode($_REQUEST['pd']);
$tables = json_decode($_REQUEST['tables']);
$newTables = PMA_getHtmlForNewTables3NF($dependencies, $tables, $db);
PMA_Response::getInstance()->disable();
PMA_headerJSON();
echo json_encode($newTables);
exit;
}
$response = PMA_Response::getInstance();
$header = $response->getHeader();
$scripts = $header->getScripts();
$scripts->addFile('normalization.js');
$scripts->addFile('jquery/jquery.uitablefilter.js');
$normalForm = '1nf';
if (isset($_REQUEST['normalizeTo'])) {
$normalForm = $_REQUEST['normalizeTo'];
}
if (isset($_REQUEST['createNewTables2NF'])) {
$partialDependencies = json_decode($_REQUEST['pd']);
$tablesName = json_decode($_REQUEST['newTablesName']);
$res = PMA_createNewTablesFor2NF($partialDependencies, $tablesName, $table, $db);
$response->addJSON($res);
exit;
}
if (isset($_REQUEST['createNewTables3NF'])) {
$newtables = json_decode($_REQUEST['newTables']);
$res = PMA_createNewTablesFor3NF($newtables, $db);
$response->addJSON($res);
exit;
}
if (isset($_POST['repeatingColumns'])) {
$repeatingColumns = $_POST['repeatingColumns'];
$newTable = $_POST['newTable'];
$newColumn = $_POST['newColumn'];
$primary_columns = $_POST['primary_columns'];
$res = PMA_moveRepeatingGroup(
$repeatingColumns, $primary_columns, $newTable, $newColumn, $table, $db
);
$response->addJSON($res);
exit;
}
if (isset($_REQUEST['step1'])) {
$html = PMA_getHtmlFor1NFStep1($db, $table, $normalForm);
$response->addHTML($html);
} else if (isset($_REQUEST['step2'])) {
$res = PMA_getHtmlContentsFor1NFStep2($db, $table);
$response->addJSON($res);
} else if (isset($_REQUEST['step3'])) {
$res = PMA_getHtmlContentsFor1NFStep3($db, $table);
$response->addJSON($res);
} else if (isset ($_REQUEST['step4'])) {
$res = PMA_getHtmlContentsFor1NFStep4($db, $table);
$response->addJSON($res);
} else if (isset($_REQUEST['step']) && $_REQUEST['step'] == 2.1) {
$res = PMA_getHtmlFor2NFstep1($db, $table);
$response->addJSON($res);
} else if (isset($_REQUEST['step']) && $_REQUEST['step'] == 3.1) {
$tables = $_REQUEST['tables'];
$res = PMA_getHtmlFor3NFstep1($db, $tables);
$response->addJSON($res);
} else {
$response->addHTML(PMA_getHtmlForNormalizetable());
}
|
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Normalization process (temporarily specific to 1NF)
*
* @package PhpMyAdmin
*/
/**
*
*/
require_once 'libraries/common.inc.php';
require_once 'libraries/transformations.lib.php';
require_once 'libraries/normalization.lib.php';
require_once 'libraries/Index.class.php';
if (isset($_REQUEST['getColumns'])) {
$html = '<option selected disabled>' . __('Select one…') . '</option>'
. '<option value="no_such_col">' . __('No such column') . '</option>';
//get column whose datatype falls under string category
$html .= PMA_getHtmlForColumnsList(
$db,
$table,
_pgettext('string types', 'String')
);
echo $html;
exit;
}
if (isset($_REQUEST['splitColumn'])) {
$num_fields = $_REQUEST['numFields'];
$html = PMA_getHtmlForCreateNewColumn($num_fields, $db, $table);
$html .= PMA_URL_getHiddenInputs($db, $table);
echo $html;
exit;
}
if (isset($_REQUEST['addNewPrimary'])) {
$num_fields = 1;
$columnMeta = array('Field'=>$table . "_id", 'Extra'=>'auto_increment');
$html = PMA_getHtmlForCreateNewColumn(
$num_fields, $db, $table, $columnMeta
);
$html .= PMA_URL_getHiddenInputs($db, $table);
echo $html;
exit;
}
if (isset($_REQUEST['findPdl'])) {
$html = PMA_findPartialDependencies($table, $db);
echo $html;
exit;
}
if (isset($_REQUEST['getNewTables2NF'])) {
$partialDependencies = json_decode($_REQUEST['pd']);
$html = PMA_getHtmlForNewTables2NF($partialDependencies, $table);
echo $html;
exit;
}
if (isset($_REQUEST['getNewTables3NF'])) {
$dependencies = json_decode($_REQUEST['pd']);
$tables = json_decode($_REQUEST['tables']);
$newTables = PMA_getHtmlForNewTables3NF($dependencies, $tables, $db);
PMA_Response::getInstance()->disable();
PMA_headerJSON();
echo json_encode($newTables);
exit;
}
$response = PMA_Response::getInstance();
$header = $response->getHeader();
$scripts = $header->getScripts();
$scripts->addFile('normalization.js');
$scripts->addFile('jquery/jquery.uitablefilter.js');
$normalForm = '1nf';
if (PMA_isValid($_REQUEST['normalizeTo'], array('1nf', '2nf', '3nf'))) {
$normalForm = $_REQUEST['normalizeTo'];
}
if (isset($_REQUEST['createNewTables2NF'])) {
$partialDependencies = json_decode($_REQUEST['pd']);
$tablesName = json_decode($_REQUEST['newTablesName']);
$res = PMA_createNewTablesFor2NF($partialDependencies, $tablesName, $table, $db);
$response->addJSON($res);
exit;
}
if (isset($_REQUEST['createNewTables3NF'])) {
$newtables = json_decode($_REQUEST['newTables']);
$res = PMA_createNewTablesFor3NF($newtables, $db);
$response->addJSON($res);
exit;
}
if (isset($_POST['repeatingColumns'])) {
$repeatingColumns = $_POST['repeatingColumns'];
$newTable = $_POST['newTable'];
$newColumn = $_POST['newColumn'];
$primary_columns = $_POST['primary_columns'];
$res = PMA_moveRepeatingGroup(
$repeatingColumns, $primary_columns, $newTable, $newColumn, $table, $db
);
$response->addJSON($res);
exit;
}
if (isset($_REQUEST['step1'])) {
$html = PMA_getHtmlFor1NFStep1($db, $table, $normalForm);
$response->addHTML($html);
} else if (isset($_REQUEST['step2'])) {
$res = PMA_getHtmlContentsFor1NFStep2($db, $table);
$response->addJSON($res);
} else if (isset($_REQUEST['step3'])) {
$res = PMA_getHtmlContentsFor1NFStep3($db, $table);
$response->addJSON($res);
} else if (isset ($_REQUEST['step4'])) {
$res = PMA_getHtmlContentsFor1NFStep4($db, $table);
$response->addJSON($res);
} else if (isset($_REQUEST['step']) && $_REQUEST['step'] == 2.1) {
$res = PMA_getHtmlFor2NFstep1($db, $table);
$response->addJSON($res);
} else if (isset($_REQUEST['step']) && $_REQUEST['step'] == 3.1) {
$tables = $_REQUEST['tables'];
$res = PMA_getHtmlFor3NFstep1($db, $tables);
$response->addJSON($res);
} else {
$response->addHTML(PMA_getHtmlForNormalizetable());
}
|
746240bd13b62b5956fc34389cfbdc09e1e67775
|
https://github.com/phpmyadmin/phpmyadmin
|
appconfig.php
|
php
|
<?php
/**
* Copyright (c) 2011, Robin Appelman <icewind1991@gmail.com>
* This file is licensed under the Affero General Public License version 3 or later.
* See the COPYING-README file.
*/
require_once ("../../lib/base.php");
OC_Util::checkAdminUser();
$action=isset($_POST['action'])?$_POST['action']:$_GET['action'];
$result=false;
switch($action){
case 'getValue':
$result=OC_Appconfig::getValue($_GET['app'],$_GET['key'],$_GET['defaultValue']);
break;
case 'setValue':
$result=OC_Appconfig::setValue($_POST['app'],$_POST['key'],$_POST['value']);
break;
case 'getApps':
$result=OC_Appconfig::getApps();
break;
case 'getKeys':
$result=OC_Appconfig::getKeys($_GET['app']);
break;
case 'hasKey':
$result=OC_Appconfig::hasKey($_GET['app'],$_GET['key']);
break;
case 'deleteKey':
$result=OC_Appconfig::deleteKey($_POST['app'],$_POST['key']);
break;
case 'deleteApp':
$result=OC_Appconfig::deleteApp($_POST['app']);
break;
}
OC_JSON::success(array('data'=>$result));
|
<?php
/**
* Copyright (c) 2011, Robin Appelman <icewind1991@gmail.com>
* This file is licensed under the Affero General Public License version 3 or later.
* See the COPYING-README file.
*/
require_once ("../../lib/base.php");
OC_Util::checkAdminUser();
OCP\JSON::callCheck();
$action=isset($_POST['action'])?$_POST['action']:$_GET['action'];
$result=false;
switch($action){
case 'getValue':
$result=OC_Appconfig::getValue($_GET['app'],$_GET['key'],$_GET['defaultValue']);
break;
case 'setValue':
$result=OC_Appconfig::setValue($_POST['app'],$_POST['key'],$_POST['value']);
break;
case 'getApps':
$result=OC_Appconfig::getApps();
break;
case 'getKeys':
$result=OC_Appconfig::getKeys($_GET['app']);
break;
case 'hasKey':
$result=OC_Appconfig::hasKey($_GET['app'],$_GET['key']);
break;
case 'deleteKey':
$result=OC_Appconfig::deleteKey($_POST['app'],$_POST['key']);
break;
case 'deleteApp':
$result=OC_Appconfig::deleteApp($_POST['app']);
break;
}
OC_JSON::success(array('data'=>$result));
|
5192eecce239a0b7ade1e60a6cf03075e5cfc188
|
https://github.com/owncloud/core
|
ItemController.php
|
php
|
<?php
/**
* Copyright (C) 2015 Deciso B.V.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
namespace OPNsense\Cron;
/**
* Class ItemController
* @package OPNsense\Cron
*/
class ItemController extends \OPNsense\Base\IndexController
{
/**
* open cron form with selected item
* @param null $uuid cron item to open
* @throws \Exception
*/
public function openAction($uuid = null)
{
$this->view->selected_uuid = $uuid;
// include dialog form definitions
$this->view->formDialogEdit = $this->getForm("dialogEdit");
$this->view->pick('OPNsense/Cron/index');
}
}
|
<?php
/**
* Copyright (C) 2015 Deciso B.V.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
namespace OPNsense\Cron;
/**
* Class ItemController
* @package OPNsense\Cron
*/
class ItemController extends \OPNsense\Base\IndexController
{
/**
* open cron form with selected item
* @param null $uuid cron item to open
* @throws \Exception
*/
public function openAction($uuid = null)
{
$this->view->selected_uuid = htmlspecialchars($uuid, ENT_QUOTES | ENT_HTML401);
// include dialog form definitions
$this->view->formDialogEdit = $this->getForm("dialogEdit");
$this->view->pick('OPNsense/Cron/index');
}
}
|
5edff49db1cd8b5078611e2f542d91c02af2b25c
|
https://github.com/opnsense/core
|
alert_rule_list.inc.php
|
php
|
<?php
/**
* alert_rule_list.inc.php
*
* LibreNMS alert_rule_list modal
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* @link https://www.librenms.org
*
* @copyright 2020 Thomas Berberich
* @author Thomas Berberich <sourcehhdoctor@gmail.com>
*/
use LibreNMS\Alerting\QueryBuilderParser;
if (! Auth::user()->hasGlobalAdmin()) {
exit('ERROR: You need to be admin');
}
?>
<div class="modal fade" id="search_alert_rule_modal" tabindex="-1" role="dialog" aria-labelledby="search_alert_rule_list" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h5 class="modal-title" id="search_alert_rule_list">Running Alert rules</h5>
</div>
<div class="modal-body">
<div class="table-responsive">
<table id="alert_rule_list" class="table table-condensed table-hover">
<thead>
<tr>
<th data-column-id="alert_name" data-width="200px">Name</th>
<th data-column-id="alert_rule">Rule</th>
<th data-column-id="alert_severity">Severity</th>
<td data-column-id="alert_action" data-formatter="alert_action"></td>
</tr>
</thead>
<?php
$alert_rules = dbFetchRows('SELECT * FROM alert_rules order by name');
foreach ($alert_rules as $rule) {
if (empty($rule['builder'])) {
$rule_display = $rule['rule'];
} elseif ($rule_extra['options']['override_query'] === 'on') {
$rule_display = 'Custom SQL Query';
} else {
$rule_display = QueryBuilderParser::fromJson($rule['builder'])->toSql(false);
}
echo "
<tr>
<td>{$rule['name']}</td>
<td><i>" . htmlentities($rule_display) . "</i></td>
<td>{$rule['severity']}</td>
<td>{$rule['id']}</td>
</tr>
";
}
?>
</table>
<script>
var alert_grid = $("#alert_rule_list").bootgrid({
caseSensitive: false,
formatters: {
"alert_action": function (column, row) {
return "<button type=\"button\" id=\"alert_rule_from_list\" name=\"alert_rule_from_list\" data-rule_id=\"" + row.alert_action + "\" class=\"btn btn-sm btn-primary alert_rule_from_list\">Select</button";
}
},
templates: {
footer: "<div id=\"{{ctx.id}}\" class=\"{{css.footer}}\"><div class=\"row\"><div class=\"col-sm-12\"><p class=\"{{css.pagination}}\"></p></div></div></div>"
}
}).on("loaded.rs.jquery.bootgrid", function()
{
alert_grid.find(".alert_rule_from_list").on("click", function(e) {
var alert_rule_id = $(this).data("rule_id");
$.ajax({
type: "POST",
url: "ajax_form.php",
data: {type: 'sql-from-alert-rules', rule_id: alert_rule_id},
dataType: "json",
success: function (data) {
if (data.status == 'ok') {
$("#search_alert_rule_modal").one('hidden.bs.modal', function(event) {
$('#create-alert').modal('show');
loadRule(data);
});
$("#search_alert_rule_modal").modal('hide');
} else {
toastr.error(data.message);
}
},
error: function () {
toastr.error('Failed to process template');
}
});
}).end();
});
</script>
</div>
</div>
</div>
</div>
</div>
<script>
$("#search_alert_rule_modal").on('hidden.bs.modal', function(e) {
$("#alert_rule_id").val('');
$("#rule_suggest").val('');
$("#rule_display").html('');
});
</script>
|
<?php
/**
* alert_rule_list.inc.php
*
* LibreNMS alert_rule_list modal
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* @link https://www.librenms.org
*
* @copyright 2020 Thomas Berberich
* @author Thomas Berberich <sourcehhdoctor@gmail.com>
*/
use LibreNMS\Alerting\QueryBuilderParser;
if (! Auth::user()->hasGlobalAdmin()) {
exit('ERROR: You need to be admin');
}
?>
<div class="modal fade" id="search_alert_rule_modal" tabindex="-1" role="dialog" aria-labelledby="search_alert_rule_list" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h5 class="modal-title" id="search_alert_rule_list">Running Alert rules</h5>
</div>
<div class="modal-body">
<div class="table-responsive">
<table id="alert_rule_list" class="table table-condensed table-hover">
<thead>
<tr>
<th data-column-id="alert_name" data-width="200px">Name</th>
<th data-column-id="alert_rule">Rule</th>
<th data-column-id="alert_severity">Severity</th>
<td data-column-id="alert_action" data-formatter="alert_action"></td>
</tr>
</thead>
<?php
$alert_rules = dbFetchRows('SELECT * FROM alert_rules order by name');
foreach ($alert_rules as $rule) {
if (empty($rule['builder'])) {
$rule_display = $rule['rule'];
} elseif ($rule_extra['options']['override_query'] === 'on') {
$rule_display = 'Custom SQL Query';
} else {
$rule_display = QueryBuilderParser::fromJson($rule['builder'])->toSql(false);
}
echo "
<tr>
<td>{$rule['name']}</td>
<td><i>" . htmlentities(strip_tags($rule_display)) . "</i></td>
<td>{$rule['severity']}</td>
<td>{$rule['id']}</td>
</tr>
";
}
?>
</table>
<script>
var alert_grid = $("#alert_rule_list").bootgrid({
caseSensitive: false,
formatters: {
"alert_action": function (column, row) {
return "<button type=\"button\" id=\"alert_rule_from_list\" name=\"alert_rule_from_list\" data-rule_id=\"" + row.alert_action + "\" class=\"btn btn-sm btn-primary alert_rule_from_list\">Select</button";
}
},
templates: {
footer: "<div id=\"{{ctx.id}}\" class=\"{{css.footer}}\"><div class=\"row\"><div class=\"col-sm-12\"><p class=\"{{css.pagination}}\"></p></div></div></div>"
}
}).on("loaded.rs.jquery.bootgrid", function()
{
alert_grid.find(".alert_rule_from_list").on("click", function(e) {
var alert_rule_id = $(this).data("rule_id");
$.ajax({
type: "POST",
url: "ajax_form.php",
data: {type: 'sql-from-alert-rules', rule_id: alert_rule_id},
dataType: "json",
success: function (data) {
if (data.status == 'ok') {
$("#search_alert_rule_modal").one('hidden.bs.modal', function(event) {
$('#create-alert').modal('show');
loadRule(data);
});
$("#search_alert_rule_modal").modal('hide');
} else {
toastr.error(data.message);
}
},
error: function () {
toastr.error('Failed to process template');
}
});
}).end();
});
</script>
</div>
</div>
</div>
</div>
</div>
<script>
$("#search_alert_rule_modal").on('hidden.bs.modal', function(e) {
$("#alert_rule_id").val('');
$("#rule_suggest").val('');
$("#rule_display").html('');
});
</script>
|
703745d0ed3948623153117d761ce48514e2f281
|
https://github.com/librenms/librenms
|
user_box.tpl.php
|
php
|
<?php
$currentUser = erLhcoreClassUser::instance();
if ($currentUser->isLogged()) :
$UserData = $currentUser->getUserData(true);
// Just logout if force to logout
if ($UserData->force_logout == 1) {
$UserData->force_logout = 0;
$UserData->updateThis(['update' => ['force_logout']]);
$currentUser->logout();
}
?>
<li class="nav-item dropleft">
<a href="#" class="nav-link dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><?php echo htmlspecialchars($UserData->name),' ',htmlspecialchars($UserData->surname)?></a>
<div class="dropdown-menu" style="min-width: 25rem;" role="menu">
<div class="row">
<div class="col-6">
<div class="pl-2 pt-1 font-weight-bold" ng-non-bindable>
<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('pagelayout/pagelayout','Hello')?> <?php echo erLhcoreClassDesign::shrt($UserData->name,10,'...',30,ENT_QUOTES)?>!
</div>
</div>
<?php if ($currentUser->hasAccessTo('lhuser','selfedit')) : ?>
<div class="col-6">
<a class="dropdown-item pl-2" href="<?php echo erLhcoreClassDesign::baseurl('user/account')?>" title="<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('pagelayout/pagelayout','Account')?>"><i class="material-icons">account_box</i><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('pagelayout/pagelayout','Account')?></a>
</div>
<?php endif; ?>
<div class="col-6">
<a title="<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/user_settings','Toggle between dark and white themes');?>" href="<?php echo erLhcoreClassDesign::baseurl('front/switchdashboard')?>/(action)/mode" class="csfr-required dropdown-item pl-2"><span class="material-icons">settings_brightness</span><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('pagelayout/pagelayout','Dark/bright');?></a>
</div>
<div class="col-6">
<a class="dropdown-item pl-2 csfr-required" href="<?php echo erLhcoreClassDesign::baseurl('user/logout')?>" title="<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('pagelayout/pagelayout','Logout');?>"><i class="material-icons">exit_to_app</i><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('pagelayout/pagelayout','Logout');?></a>
</div>
</div>
<hr class="m-0">
<?php include(erLhcoreClassDesign::designtpl('pagelayouts/parts/top_menu_chat_actions_pre.tpl.php'));?>
<?php
$soundData = erLhcoreClassModelChatConfig::fetch('sync_sound_settings')->data;
$soundMessageEnabled = erLhcoreClassModelUserSetting::getSetting('chat_message',(int)($soundData['new_message_sound_admin_enabled']));
$soundNewChatEnabled = erLhcoreClassModelUserSetting::getSetting('new_chat_sound',(int)($soundData['new_chat_sound_enabled']));
$canChangeOnlineStatus = false;
$currentUser = erLhcoreClassUser::instance();
if ( $currentUser->hasAccessTo('lhuser','changeonlinestatus') ) {
$canChangeOnlineStatus = true;
if ( !isset($UserData) ) {
$UserData = $currentUser->getUserData(true);
}
}
$canChangeVisibilityMode = false;
if ( $currentUser->hasAccessTo('lhuser','changevisibility') ) {
$canChangeVisibilityMode = true;
if ( !isset($UserData) ) {
$UserData = $currentUser->getUserData(true);
}
}
$canChangeAlwaysOnline = false;
if ( $currentUser->hasAccessTo('lhuser','changealwaysonline') ) {
$canChangeAlwaysOnline = true;
if ( !isset($UserData) ) {
$UserData = $currentUser->getUserData(true);
}
}
?>
<?php if ($currentUser->hasAccessTo('lhchat','use') ) : ?>
<div class="row">
<div class="col-12">
<a href="<?php echo erLhcoreClassDesign::baseurl('user/setsetting')?>/auto_uppercase/<?php echo erLhcoreClassModelUserSetting::getSetting('auto_uppercase',1) == 0 ? 1 : 0?>" class="csfr-required dropdown-item pl-2"><span class="material-icons"><?php erLhcoreClassModelUserSetting::getSetting('auto_uppercase',1) ? print 'check' : print 'remove_done'?></span><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('user/account','Auto uppercase sentences');?></a>
</div>
<div class="col-12">
<a href="<?php echo erLhcoreClassDesign::baseurl('user/setsetting')?>/no_scroll_bottom/<?php echo erLhcoreClassModelUserSetting::getSetting('no_scroll_bottom',0) == 0 ? 1 : 0?>" class="csfr-required dropdown-item pl-2"><span class="material-icons"><?php erLhcoreClassModelUserSetting::getSetting('no_scroll_bottom',0) ? print 'check' : print 'remove_done'?></span><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('user/account','Do not scroll to the bottom on chat open');?></a>
</div>
<div class="col-12">
<a href="<?php echo erLhcoreClassDesign::baseurl('user/setsetting')?>/auto_preload/<?php echo erLhcoreClassModelUserSetting::getSetting('auto_preload',0) == 0 ? 1 : 0?>" class="csfr-required dropdown-item pl-2"><span class="material-icons"><?php erLhcoreClassModelUserSetting::getSetting('auto_preload',0) ? print 'check' : print 'remove_done'?></span><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('user/account','Auto preload previous visitor chat messages');?></a>
</div>
<div class="col-12">
<a href="<?php echo erLhcoreClassDesign::baseurl('user/setsetting')?>/scroll_load/<?php echo erLhcoreClassModelUserSetting::getSetting('scroll_load',1) == 0 ? 1 : 0?>" class="csfr-required dropdown-item pl-2"><span class="material-icons"><?php erLhcoreClassModelUserSetting::getSetting('scroll_load',1) ? print 'check' : print 'remove_done'?></span><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('user/account','Load previous message on scroll');?></a>
</div>
<div class="col-6">
<a href="#" class="dropdown-item pl-2" onclick="lhinst.disableChatSoundAdmin($(this));event.stopPropagation()" title="<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/user_settings','Enable/Disable sound about new messages from users');?>"><i class="material-icons" ><?php $soundMessageEnabled == 0 ? print 'volume_off' : print 'volume_up'?></i><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('pagelayout/pagelayout','New messages');?></a>
</div>
<div class="col-6">
<a href="#" class="dropdown-item pl-2" onclick="lhinst.disableNewChatSoundAdmin($(this));event.stopPropagation()" title="<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/user_settings','Enable/Disable sound about new pending chats');?>"><i class="material-icons" ><?php $soundNewChatEnabled == 0 ? print 'volume_off' : print 'volume_up'?></i><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('pagelayout/pagelayout','New chats');?></a>
</div>
</div>
<hr class="m-0">
<?php if ($canChangeVisibilityMode || $canChangeOnlineStatus || $canChangeAlwaysOnline) : ?>
<div class="row">
<?php if ($canChangeOnlineStatus == true) : ?>
<div class="col-6">
<a href="#" class="dropdown-item pl-2" ng-click="lhc.changeOnline($event)" title="<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/user_settings','Change my status to online/offline');?>"><i id="online-offline-user" class="material-icons ng-cloak" >{{lhc.hideOnline == true ? 'flash_off' : 'flash_on'}}</i>{{lhc.hideOnline == true ? <?php echo json_encode(htmlspecialchars_decode(erTranslationClassLhTranslation::getInstance()->getTranslation('pagelayout/pagelayout','Offline'),ENT_QUOTES))?> : <?php echo json_encode(htmlspecialchars_decode(erTranslationClassLhTranslation::getInstance()->getTranslation('pagelayout/pagelayout','Online'),ENT_QUOTES))?>}}</a>
</div>
<?php endif;?>
<?php if ($canChangeAlwaysOnline == true) : ?>
<div class="col-6">
<a href="#" class="dropdown-item pl-2" title="<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/user_settings','Change my persistent status to online');?>" ng-click="lhc.changeAlwaysOnline($event)"><i class="material-icons ng-cloak" >{{lhc.hideOnline == true ? 'flash_off' : (lhc.alwaysOnline == true ? 'toggle_on' : 'toggle_off')}}</i>{{lhc.alwaysOnline == true ? <?php echo json_encode(htmlspecialchars_decode(erTranslationClassLhTranslation::getInstance()->getTranslation('pagelayout/pagelayout','Always online'),ENT_QUOTES))?> : <?php echo json_encode(htmlspecialchars_decode(erTranslationClassLhTranslation::getInstance()->getTranslation('pagelayout/pagelayout','Based on activity'),ENT_QUOTES))?>}}</a>
</div>
<?php endif; ?>
<?php if ($canChangeVisibilityMode == true) : ?>
<div class="col-12">
<a href="#" class="dropdown-item pl-2" ng-click="lhc.changeVisibility($event)"><i id="vi-in-user" class="material-icons ng-cloak" title="<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/user_settings','Change my visibility to visible/invisible');?>" >{{lhc.hideInvisible == true ? 'visibility_off' : 'visibility'}}</i>{{lhc.hideInvisible == true ? <?php echo json_encode(htmlspecialchars_decode(erTranslationClassLhTranslation::getInstance()->getTranslation('pagelayout/pagelayout','Invisible'),ENT_QUOTES))?> : <?php echo json_encode(htmlspecialchars_decode(erTranslationClassLhTranslation::getInstance()->getTranslation('pagelayout/pagelayout','Visible'),ENT_QUOTES))?>}}</a>
</div>
<?php endif;?>
</div>
<hr class="m-0">
<?php endif; ?>
<?php endif;?>
<?php include(erLhcoreClassDesign::designtpl('pagelayouts/parts/top_menu_chat_actions_post_multiinclude.tpl.php'));?>
</div>
</li>
<?php unset($currentUser);unset($UserData);endif; ?>
|
<?php
$currentUser = erLhcoreClassUser::instance();
if ($currentUser->isLogged()) :
$UserData = $currentUser->getUserData(true);
// Just logout if force to logout
if ($UserData->force_logout == 1) {
$UserData->force_logout = 0;
$UserData->updateThis(['update' => ['force_logout']]);
$currentUser->logout();
}
?>
<li class="nav-item dropleft">
<a href="#" class="nav-link dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false" ng-non-bindable><?php echo htmlspecialchars($UserData->name),' ',htmlspecialchars($UserData->surname)?></a>
<div class="dropdown-menu" style="min-width: 25rem;" role="menu">
<div class="row">
<div class="col-6">
<div class="pl-2 pt-1 font-weight-bold" ng-non-bindable>
<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('pagelayout/pagelayout','Hello')?> <?php echo erLhcoreClassDesign::shrt($UserData->name,10,'...',30,ENT_QUOTES)?>!
</div>
</div>
<?php if ($currentUser->hasAccessTo('lhuser','selfedit')) : ?>
<div class="col-6">
<a class="dropdown-item pl-2" href="<?php echo erLhcoreClassDesign::baseurl('user/account')?>" title="<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('pagelayout/pagelayout','Account')?>"><i class="material-icons">account_box</i><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('pagelayout/pagelayout','Account')?></a>
</div>
<?php endif; ?>
<div class="col-6">
<a title="<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/user_settings','Toggle between dark and white themes');?>" href="<?php echo erLhcoreClassDesign::baseurl('front/switchdashboard')?>/(action)/mode" class="csfr-required dropdown-item pl-2"><span class="material-icons">settings_brightness</span><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('pagelayout/pagelayout','Dark/bright');?></a>
</div>
<div class="col-6">
<a class="dropdown-item pl-2 csfr-required" href="<?php echo erLhcoreClassDesign::baseurl('user/logout')?>" title="<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('pagelayout/pagelayout','Logout');?>"><i class="material-icons">exit_to_app</i><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('pagelayout/pagelayout','Logout');?></a>
</div>
</div>
<hr class="m-0">
<?php include(erLhcoreClassDesign::designtpl('pagelayouts/parts/top_menu_chat_actions_pre.tpl.php'));?>
<?php
$soundData = erLhcoreClassModelChatConfig::fetch('sync_sound_settings')->data;
$soundMessageEnabled = erLhcoreClassModelUserSetting::getSetting('chat_message',(int)($soundData['new_message_sound_admin_enabled']));
$soundNewChatEnabled = erLhcoreClassModelUserSetting::getSetting('new_chat_sound',(int)($soundData['new_chat_sound_enabled']));
$canChangeOnlineStatus = false;
$currentUser = erLhcoreClassUser::instance();
if ( $currentUser->hasAccessTo('lhuser','changeonlinestatus') ) {
$canChangeOnlineStatus = true;
if ( !isset($UserData) ) {
$UserData = $currentUser->getUserData(true);
}
}
$canChangeVisibilityMode = false;
if ( $currentUser->hasAccessTo('lhuser','changevisibility') ) {
$canChangeVisibilityMode = true;
if ( !isset($UserData) ) {
$UserData = $currentUser->getUserData(true);
}
}
$canChangeAlwaysOnline = false;
if ( $currentUser->hasAccessTo('lhuser','changealwaysonline') ) {
$canChangeAlwaysOnline = true;
if ( !isset($UserData) ) {
$UserData = $currentUser->getUserData(true);
}
}
?>
<?php if ($currentUser->hasAccessTo('lhchat','use') ) : ?>
<div class="row">
<div class="col-12">
<a href="<?php echo erLhcoreClassDesign::baseurl('user/setsetting')?>/auto_uppercase/<?php echo erLhcoreClassModelUserSetting::getSetting('auto_uppercase',1) == 0 ? 1 : 0?>" class="csfr-required dropdown-item pl-2"><span class="material-icons"><?php erLhcoreClassModelUserSetting::getSetting('auto_uppercase',1) ? print 'check' : print 'remove_done'?></span><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('user/account','Auto uppercase sentences');?></a>
</div>
<div class="col-12">
<a href="<?php echo erLhcoreClassDesign::baseurl('user/setsetting')?>/no_scroll_bottom/<?php echo erLhcoreClassModelUserSetting::getSetting('no_scroll_bottom',0) == 0 ? 1 : 0?>" class="csfr-required dropdown-item pl-2"><span class="material-icons"><?php erLhcoreClassModelUserSetting::getSetting('no_scroll_bottom',0) ? print 'check' : print 'remove_done'?></span><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('user/account','Do not scroll to the bottom on chat open');?></a>
</div>
<div class="col-12">
<a href="<?php echo erLhcoreClassDesign::baseurl('user/setsetting')?>/auto_preload/<?php echo erLhcoreClassModelUserSetting::getSetting('auto_preload',0) == 0 ? 1 : 0?>" class="csfr-required dropdown-item pl-2"><span class="material-icons"><?php erLhcoreClassModelUserSetting::getSetting('auto_preload',0) ? print 'check' : print 'remove_done'?></span><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('user/account','Auto preload previous visitor chat messages');?></a>
</div>
<div class="col-12">
<a href="<?php echo erLhcoreClassDesign::baseurl('user/setsetting')?>/scroll_load/<?php echo erLhcoreClassModelUserSetting::getSetting('scroll_load',1) == 0 ? 1 : 0?>" class="csfr-required dropdown-item pl-2"><span class="material-icons"><?php erLhcoreClassModelUserSetting::getSetting('scroll_load',1) ? print 'check' : print 'remove_done'?></span><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('user/account','Load previous message on scroll');?></a>
</div>
<div class="col-6">
<a href="#" class="dropdown-item pl-2" onclick="lhinst.disableChatSoundAdmin($(this));event.stopPropagation()" title="<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/user_settings','Enable/Disable sound about new messages from users');?>"><i class="material-icons" ><?php $soundMessageEnabled == 0 ? print 'volume_off' : print 'volume_up'?></i><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('pagelayout/pagelayout','New messages');?></a>
</div>
<div class="col-6">
<a href="#" class="dropdown-item pl-2" onclick="lhinst.disableNewChatSoundAdmin($(this));event.stopPropagation()" title="<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/user_settings','Enable/Disable sound about new pending chats');?>"><i class="material-icons" ><?php $soundNewChatEnabled == 0 ? print 'volume_off' : print 'volume_up'?></i><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('pagelayout/pagelayout','New chats');?></a>
</div>
</div>
<hr class="m-0">
<?php if ($canChangeVisibilityMode || $canChangeOnlineStatus || $canChangeAlwaysOnline) : ?>
<div class="row">
<?php if ($canChangeOnlineStatus == true) : ?>
<div class="col-6">
<a href="#" class="dropdown-item pl-2" ng-click="lhc.changeOnline($event)" title="<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/user_settings','Change my status to online/offline');?>"><i id="online-offline-user" class="material-icons ng-cloak" >{{lhc.hideOnline == true ? 'flash_off' : 'flash_on'}}</i>{{lhc.hideOnline == true ? <?php echo json_encode(htmlspecialchars_decode(erTranslationClassLhTranslation::getInstance()->getTranslation('pagelayout/pagelayout','Offline'),ENT_QUOTES))?> : <?php echo json_encode(htmlspecialchars_decode(erTranslationClassLhTranslation::getInstance()->getTranslation('pagelayout/pagelayout','Online'),ENT_QUOTES))?>}}</a>
</div>
<?php endif;?>
<?php if ($canChangeAlwaysOnline == true) : ?>
<div class="col-6">
<a href="#" class="dropdown-item pl-2" title="<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/user_settings','Change my persistent status to online');?>" ng-click="lhc.changeAlwaysOnline($event)"><i class="material-icons ng-cloak" >{{lhc.hideOnline == true ? 'flash_off' : (lhc.alwaysOnline == true ? 'toggle_on' : 'toggle_off')}}</i>{{lhc.alwaysOnline == true ? <?php echo json_encode(htmlspecialchars_decode(erTranslationClassLhTranslation::getInstance()->getTranslation('pagelayout/pagelayout','Always online'),ENT_QUOTES))?> : <?php echo json_encode(htmlspecialchars_decode(erTranslationClassLhTranslation::getInstance()->getTranslation('pagelayout/pagelayout','Based on activity'),ENT_QUOTES))?>}}</a>
</div>
<?php endif; ?>
<?php if ($canChangeVisibilityMode == true) : ?>
<div class="col-12">
<a href="#" class="dropdown-item pl-2" ng-click="lhc.changeVisibility($event)"><i id="vi-in-user" class="material-icons ng-cloak" title="<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/user_settings','Change my visibility to visible/invisible');?>" >{{lhc.hideInvisible == true ? 'visibility_off' : 'visibility'}}</i>{{lhc.hideInvisible == true ? <?php echo json_encode(htmlspecialchars_decode(erTranslationClassLhTranslation::getInstance()->getTranslation('pagelayout/pagelayout','Invisible'),ENT_QUOTES))?> : <?php echo json_encode(htmlspecialchars_decode(erTranslationClassLhTranslation::getInstance()->getTranslation('pagelayout/pagelayout','Visible'),ENT_QUOTES))?>}}</a>
</div>
<?php endif;?>
</div>
<hr class="m-0">
<?php endif; ?>
<?php endif;?>
<?php include(erLhcoreClassDesign::designtpl('pagelayouts/parts/top_menu_chat_actions_post_multiinclude.tpl.php'));?>
</div>
</li>
<?php unset($currentUser);unset($UserData);endif; ?>
|
8fdb4f67ac1a095331aa0fb4630ef9dfe8e75dcb
|
https://github.com/livehelperchat/livehelperchat
|
index.php
|
php
|
<?php
/**
* ownCloud
*
* @author Frank Karlitschek
* @copyright 2010 Frank Karlitschek karlitschek@kde.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
$RUNTIME_NOAPPS = TRUE; //no apps, yet
require_once('lib/base.php');
// Setup required :
$not_installed = !OC_Config::getValue('installed', false);
if($not_installed) {
// Check for autosetup:
$autosetup_file = OC::$SERVERROOT."/config/autoconfig.php";
if( file_exists( $autosetup_file )){
OC_Log::write('core','Autoconfig file found, setting up owncloud...',OC_Log::INFO);
include( $autosetup_file );
$_POST['install'] = 'true';
$_POST = array_merge ($_POST, $AUTOCONFIG);
unlink($autosetup_file);
}
OC_Util::addScript('setup');
require_once('setup.php');
exit();
}
// Handle WebDAV
if($_SERVER['REQUEST_METHOD']=='PROPFIND'){
header('location: '.OC_Helper::linkToRemote('webdav'));
exit();
}
elseif(!OC_User::isLoggedIn() && substr(OC::$REQUESTEDFILE,-3) == 'css'){
OC_App::loadApps();
OC::loadfile();
}
// Someone is logged in :
elseif(OC_User::isLoggedIn()) {
OC_App::loadApps();
if(isset($_GET["logout"]) and ($_GET["logout"])) {
OC_User::logout();
header("Location: ".OC::$WEBROOT.'/');
exit();
}else{
if(is_null(OC::$REQUESTEDFILE)){
OC::loadapp();
}else{
OC::loadfile();
}
}
// For all others cases, we display the guest page :
} else {
OC_App::loadApps();
$error = false;
// remember was checked after last login
if(isset($_COOKIE["oc_remember_login"]) && isset($_COOKIE["oc_token"]) && isset($_COOKIE["oc_username"]) && $_COOKIE["oc_remember_login"]) {
if(defined("DEBUG") && DEBUG) {
OC_Log::write('core','Trying to login from cookie',OC_Log::DEBUG);
}
// confirm credentials in cookie
if(isset($_COOKIE['oc_token']) && OC_User::userExists($_COOKIE['oc_username']) &&
OC_Preferences::getValue($_COOKIE['oc_username'], "login", "token") == $_COOKIE['oc_token']) {
OC_User::setUserId($_COOKIE['oc_username']);
OC_Util::redirectToDefaultPage();
}
else {
OC_User::unsetMagicInCookie();
}
// Someone wants to log in :
} elseif(isset($_POST["user"]) and isset($_POST['password']) and isset($_SESSION['sectoken']) and isset($_POST['sectoken']) and ($_SESSION['sectoken']==$_POST['sectoken']) ) {
if(OC_User::login($_POST["user"], $_POST["password"])) {
if(!empty($_POST["remember_login"])){
if(defined("DEBUG") && DEBUG) {
OC_Log::write('core','Setting remember login to cookie',OC_Log::DEBUG);
}
$token = md5($_POST["user"].time().$_POST['password']);
OC_Preferences::setValue($_POST['user'], 'login', 'token', $token);
OC_User::setMagicInCookie($_POST["user"], $token);
}
else {
OC_User::unsetMagicInCookie();
}
OC_Util::redirectToDefaultPage();
} else {
$error = true;
}
// The user is already authenticated using Apaches AuthType Basic... very usable in combination with LDAP
} elseif(isset($_SERVER["PHP_AUTH_USER"]) && isset($_SERVER["PHP_AUTH_PW"])){
if (OC_User::login($_SERVER["PHP_AUTH_USER"],$_SERVER["PHP_AUTH_PW"])) {
//OC_Log::write('core',"Logged in with HTTP Authentication",OC_Log::DEBUG);
OC_User::unsetMagicInCookie();
$_REQUEST['redirect_url'] = (isset($_SERVER['REQUEST_URI'])?$_SERVER['REQUEST_URI']:'');
OC_Util::redirectToDefaultPage();
}else{
$error = true;
}
}
if(!array_key_exists('sectoken', $_SESSION) || (array_key_exists('sectoken', $_SESSION) && is_null(OC::$REQUESTEDFILE)) || substr(OC::$REQUESTEDFILE, -3) == 'php'){
$sectoken=rand(1000000,9999999);
$_SESSION['sectoken']=$sectoken;
$redirect_url = (isset($_REQUEST['redirect_url'])) ? $_REQUEST['redirect_url'] : $_SERVER['REQUEST_URI'];
OC_Template::printGuestPage('', 'login', array('error' => $error, 'sectoken' => $sectoken, 'redirect' => $redirect_url));
}
}
|
<?php
/**
* ownCloud
*
* @author Frank Karlitschek
* @copyright 2010 Frank Karlitschek karlitschek@kde.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
$RUNTIME_NOAPPS = TRUE; //no apps, yet
require_once('lib/base.php');
// Setup required :
$not_installed = !OC_Config::getValue('installed', false);
if($not_installed) {
// Check for autosetup:
$autosetup_file = OC::$SERVERROOT."/config/autoconfig.php";
if( file_exists( $autosetup_file )){
OC_Log::write('core','Autoconfig file found, setting up owncloud...',OC_Log::INFO);
include( $autosetup_file );
$_POST['install'] = 'true';
$_POST = array_merge ($_POST, $AUTOCONFIG);
unlink($autosetup_file);
}
OC_Util::addScript('setup');
require_once('setup.php');
exit();
}
// Handle WebDAV
if($_SERVER['REQUEST_METHOD']=='PROPFIND'){
header('location: '.OC_Helper::linkToRemote('webdav'));
exit();
}
elseif(!OC_User::isLoggedIn() && substr(OC::$REQUESTEDFILE,-3) == 'css'){
OC_App::loadApps();
OC::loadfile();
}
// Someone is logged in :
elseif(OC_User::isLoggedIn()) {
OC_App::loadApps();
if(isset($_GET["logout"]) and ($_GET["logout"])) {
OC_User::logout();
header("Location: ".OC::$WEBROOT.'/');
exit();
}else{
if(is_null(OC::$REQUESTEDFILE)){
OC::loadapp();
}else{
OC::loadfile();
}
}
// For all others cases, we display the guest page :
} else {
OC_App::loadApps();
$error = false;
// remember was checked after last login
if(isset($_COOKIE["oc_remember_login"]) && isset($_COOKIE["oc_token"]) && isset($_COOKIE["oc_username"]) && $_COOKIE["oc_remember_login"]) {
if(defined("DEBUG") && DEBUG) {
OC_Log::write('core','Trying to login from cookie',OC_Log::DEBUG);
}
// confirm credentials in cookie
if(isset($_COOKIE['oc_token']) && OC_User::userExists($_COOKIE['oc_username']) &&
OC_Preferences::getValue($_COOKIE['oc_username'], "login", "token") == $_COOKIE['oc_token']) {
OC_User::setUserId($_COOKIE['oc_username']);
OC_Util::redirectToDefaultPage();
}
else {
OC_User::unsetMagicInCookie();
}
// Someone wants to log in :
} elseif(isset($_POST["user"]) and isset($_POST['password']) and isset($_SESSION['sectoken']) and isset($_POST['sectoken']) and ($_SESSION['sectoken']==$_POST['sectoken']) ) {
if(OC_User::login($_POST["user"], $_POST["password"])) {
if(!empty($_POST["remember_login"])){
if(defined("DEBUG") && DEBUG) {
OC_Log::write('core','Setting remember login to cookie',OC_Log::DEBUG);
}
$token = md5($_POST["user"].time().$_POST['password']);
OC_Preferences::setValue($_POST['user'], 'login', 'token', $token);
OC_User::setMagicInCookie($_POST["user"], $token);
}
else {
OC_User::unsetMagicInCookie();
}
OC_Util::redirectToDefaultPage();
} else {
$error = true;
}
// The user is already authenticated using Apaches AuthType Basic... very usable in combination with LDAP
} elseif(isset($_SERVER["PHP_AUTH_USER"]) && isset($_SERVER["PHP_AUTH_PW"])){
if (OC_User::login($_SERVER["PHP_AUTH_USER"],$_SERVER["PHP_AUTH_PW"])) {
//OC_Log::write('core',"Logged in with HTTP Authentication",OC_Log::DEBUG);
OC_User::unsetMagicInCookie();
$_REQUEST['redirect_url'] = (isset($_SERVER['REQUEST_URI'])?$_SERVER['REQUEST_URI']:'');
OC_Util::redirectToDefaultPage();
}else{
$error = true;
}
}
if(!array_key_exists('sectoken', $_SESSION) || (array_key_exists('sectoken', $_SESSION) && is_null(OC::$REQUESTEDFILE)) || substr(OC::$REQUESTEDFILE, -3) == 'php'){
$sectoken=rand(1000000,9999999);
$_SESSION['sectoken']=$sectoken;
$redirect_url = (isset($_REQUEST['redirect_url'])) ? strip_tags($_REQUEST['redirect_url']) : $_SERVER['REQUEST_URI'];
OC_Template::printGuestPage('', 'login', array('error' => $error, 'sectoken' => $sectoken, 'redirect' => $redirect_url));
}
}
|
0074062b5329c3d43679909fddce2d70608a4475
|
https://github.com/owncloud/core
|
add.php
|
php
|
<?
$id = $_GET["module"];
$table = isset($_GET["table"]) ? $_GET["table"] : "";
$title = isset($_GET["title"]) ? htmlspecialchars($_GET["title"]) : "";
$module = $admin->getModule($id);
$landing_exists = $admin->doesModuleLandingActionExist($id);
if (isset($_SESSION["bigtree_admin"]["developer"]["saved_view"])) {
BigTree::globalizeArray($_SESSION["bigtree_admin"]["developer"]["saved_view"],array("htmlspecialchars"));
unset($_SESSION["bigtree_admin"]["developer"]["saved_view"]);
} else {
// Stop notices
$description = $type = $preview_url = "";
}
?>
<div class="container">
<form method="post" action="<?=$developer_root?>modules/views/create/<?=$id?>/" class="module">
<section>
<? if ($landing_exists) { ?>
<div class="alert">
<span></span>
<p><strong>Default View Taken:</strong> If this view is for a different edit action, please specify the suffix below (i.e. edit-group's suffix is "group").</p>
</div>
<fieldset>
<label>Add/Edit Suffix</label>
<input type="text" name="suffix" />
</fieldset>
<? } ?>
<div class="left">
<fieldset>
<label class="required">Item Title <small>(for example, "Questions" to make the title "Viewing Questions")</small></label>
<input type="text" class="required" name="title" value="<?=$title?>" />
</fieldset>
<fieldset>
<label class="required">Data Table</label>
<select name="table" id="view_table" class="required" >
<option></option>
<? BigTree::getTableSelectOptions($table); ?>
</select>
</fieldset>
<fieldset>
<label>View Type</label>
<select name="type" id="view_type" class="left" >
<? foreach ($admin->ViewTypes as $key => $t) { ?>
<option value="<?=$key?>"<? if ($key == $type) { ?> selected="selected"<? } ?>><?=$t?></option>
<? } ?>
</select>
<a href="#" class="options icon_settings"></a>
<input type="hidden" name="options" id="view_options" value="<?=$options?>" />
</fieldset>
</div>
<div class="right">
<fieldset>
<label>Description <small>(instructions for the user)</small></label>
<textarea name="description" ><?=$description?></textarea>
</fieldset>
</div>
<fieldset>
<label>Preview URL <small>(optional, i.e. http://www.website.com/news/preview/ — the item's id will be entered as the final route)</small></label>
<input type="text" name="preview_url" value="<?=$preview_url?>" />
</fieldset>
</section>
<section class="sub" id="field_area">
<? if (!$table) { ?>
<p>Please choose a table to populate this area.</p>
<? } else { ?>
<? include BigTree::path("admin/ajax/developer/load-view-fields.php") ?>
<? } ?>
</section>
<footer>
<input type="submit" class="button blue" value="Create" />
</footer>
</form>
</div>
<? include BigTree::path("admin/modules/developer/modules/views/_js.php") ?>
|
<?
$id = htmlspecialchars($_GET["module"]);
$table = isset($_GET["table"]) ? $_GET["table"] : "";
$title = isset($_GET["title"]) ? htmlspecialchars($_GET["title"]) : "";
$module = $admin->getModule($id);
$landing_exists = $admin->doesModuleLandingActionExist($id);
if (isset($_SESSION["bigtree_admin"]["developer"]["saved_view"])) {
BigTree::globalizeArray($_SESSION["bigtree_admin"]["developer"]["saved_view"],array("htmlspecialchars"));
unset($_SESSION["bigtree_admin"]["developer"]["saved_view"]);
} else {
// Stop notices
$description = $type = $preview_url = "";
}
?>
<div class="container">
<form method="post" action="<?=$developer_root?>modules/views/create/<?=$id?>/" class="module">
<section>
<? if ($landing_exists) { ?>
<div class="alert">
<span></span>
<p><strong>Default View Taken:</strong> If this view is for a different edit action, please specify the suffix below (i.e. edit-group's suffix is "group").</p>
</div>
<fieldset>
<label>Add/Edit Suffix</label>
<input type="text" name="suffix" />
</fieldset>
<? } ?>
<div class="left">
<fieldset>
<label class="required">Item Title <small>(for example, "Questions" to make the title "Viewing Questions")</small></label>
<input type="text" class="required" name="title" value="<?=$title?>" />
</fieldset>
<fieldset>
<label class="required">Data Table</label>
<select name="table" id="view_table" class="required" >
<option></option>
<? BigTree::getTableSelectOptions($table); ?>
</select>
</fieldset>
<fieldset>
<label>View Type</label>
<select name="type" id="view_type" class="left" >
<? foreach ($admin->ViewTypes as $key => $t) { ?>
<option value="<?=$key?>"<? if ($key == $type) { ?> selected="selected"<? } ?>><?=$t?></option>
<? } ?>
</select>
<a href="#" class="options icon_settings"></a>
<input type="hidden" name="options" id="view_options" value="<?=$options?>" />
</fieldset>
</div>
<div class="right">
<fieldset>
<label>Description <small>(instructions for the user)</small></label>
<textarea name="description" ><?=$description?></textarea>
</fieldset>
</div>
<fieldset>
<label>Preview URL <small>(optional, i.e. http://www.website.com/news/preview/ — the item's id will be entered as the final route)</small></label>
<input type="text" name="preview_url" value="<?=$preview_url?>" />
</fieldset>
</section>
<section class="sub" id="field_area">
<? if (!$table) { ?>
<p>Please choose a table to populate this area.</p>
<? } else { ?>
<? include BigTree::path("admin/ajax/developer/load-view-fields.php") ?>
<? } ?>
</section>
<footer>
<input type="submit" class="button blue" value="Create" />
</footer>
</form>
</div>
<? include BigTree::path("admin/modules/developer/modules/views/_js.php") ?>
|
8a59c2e13f8e151b6a9e98f73e641e1ec8d928df
|
https://github.com/bigtreecms/bigtree-cms
|
manage_user_page.php
|
php
|
<?php
# MantisBT - A PHP based bugtracking system
# MantisBT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# MantisBT 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 MantisBT. If not, see <http://www.gnu.org/licenses/>.
/**
* User Page
*
* @package MantisBT
* @copyright Copyright 2000 - 2002 Kenzaburo Ito - kenito@300baud.org
* @copyright Copyright 2002 MantisBT Team - mantisbt-dev@lists.sourceforge.net
* @link http://www.mantisbt.org
*
* @uses core.php
* @uses access_api.php
* @uses authentication_api.php
* @uses config_api.php
* @uses constant_inc.php
* @uses database_api.php
* @uses gpc_api.php
* @uses helper_api.php
* @uses html_api.php
* @uses icon_api.php
* @uses lang_api.php
* @uses print_api.php
* @uses string_api.php
* @uses utility_api.php
*/
require_once( 'core.php' );
require_api( 'access_api.php' );
require_api( 'authentication_api.php' );
require_api( 'config_api.php' );
require_api( 'constant_inc.php' );
require_api( 'database_api.php' );
require_api( 'gpc_api.php' );
require_api( 'helper_api.php' );
require_api( 'html_api.php' );
require_api( 'icon_api.php' );
require_api( 'lang_api.php' );
require_api( 'print_api.php' );
require_api( 'string_api.php' );
require_api( 'utility_api.php' );
auth_reauthenticate();
access_ensure_global_level( config_get( 'manage_user_threshold' ) );
$t_cookie_name = config_get( 'manage_users_cookie' );
$t_lock_image = '<i class="fa fa-lock fa-lg" alt="' . lang_get( 'protected' ) . '" />';
$f_save = gpc_get_bool( 'save' );
$f_filter = utf8_strtoupper( gpc_get_string( 'filter', config_get( 'default_manage_user_prefix' ) ) );
$f_page_number = gpc_get_int( 'page_number', 1 );
if( !$f_save && !is_blank( gpc_get_cookie( $t_cookie_name, '' ) ) ) {
$t_manage_arr = explode( ':', gpc_get_cookie( $t_cookie_name ) );
# Hide Inactive
$f_hide_inactive = (bool)$t_manage_arr[0];
# Sort field
if ( isset( $t_manage_arr[1] ) ) {
$f_sort = $t_manage_arr[1];
} else {
$f_sort = 'username';
}
# Sort order
if ( isset( $t_manage_arr[2] ) ) {
$f_dir = $t_manage_arr[2];
} else {
$f_dir = 'DESC';
}
# Show Disabled
if ( isset( $t_manage_arr[3] ) ) {
$f_show_disabled = $t_manage_arr[3];
}
} else {
$f_sort = gpc_get_string( 'sort', 'username' );
$f_dir = gpc_get_string( 'dir', 'ASC' );
$f_hide_inactive = gpc_get_bool( 'hideinactive' );
$f_show_disabled = gpc_get_bool( 'showdisabled' );
}
# Clean up the form variables
if( !db_field_exists( $f_sort, db_get_table( 'user' ) ) ) {
$c_sort = 'username';
} else {
$c_sort = addslashes( $f_sort );
}
$c_dir = ( $f_dir == 'ASC' ) ? 'ASC' : 'DESC';
# OFF = show inactive users, anything else = hide them
$c_hide_inactive = ( $f_hide_inactive == OFF ) ? OFF : ON;
$t_hide_inactive_filter = '&hideinactive=' . $c_hide_inactive;
# OFF = hide disabled users, anything else = show them
$c_show_disabled = ( $f_show_disabled == OFF ) ? OFF : ON;
$t_show_disabled_filter = '&showdisabled=' . $c_show_disabled;
# set cookie values for hide inactive, sort by, dir and show disabled
if( $f_save ) {
$t_manage_string = $c_hide_inactive.':'.$c_sort.':'.$c_dir.':'.$c_show_disabled;
gpc_set_cookie( $t_cookie_name, $t_manage_string, true );
}
layout_page_header( lang_get( 'manage_users_link' ) );
layout_page_begin( 'manage_overview_page.php' );
print_manage_menu( 'manage_user_page.php' );
# New Accounts Form BEGIN
$t_days_old = 7 * SECONDS_PER_DAY;
$t_query = 'SELECT COUNT(*) AS new_user_count FROM {user}
WHERE ' . db_helper_compare_time( db_param(), '<=', 'date_created', $t_days_old );
$t_result = db_query( $t_query, array( db_now() ) );
$t_row = db_fetch_array( $t_result );
$t_new_user_count = $t_row['new_user_count'];
# Never Logged In Form BEGIN
$t_query = 'SELECT COUNT(*) AS unused_user_count FROM {user}
WHERE ( login_count = 0 ) AND ( date_created = last_visit )';
$t_result = db_query( $t_query );
$t_row = db_fetch_array( $t_result );
$t_unused_user_count = $t_row['unused_user_count'];
# Manage Form BEGIN
$t_prefix_array = array();
$t_prefix_array['ALL'] = lang_get( 'show_all_users' );
for( $i = 'A'; $i != 'AA'; $i++ ) {
$t_prefix_array[$i] = $i;
}
for( $i = 0; $i <= 9; $i++ ) {
$t_prefix_array[(string)$i] = (string)$i;
}
$t_prefix_array['UNUSED'] = lang_get( 'users_unused' );
$t_prefix_array['NEW'] = lang_get( 'users_new' );
echo '<div class="col-md-12 col-xs-12">';
echo '<div class = "space-10"></div>';
echo '<div class="center" >';
echo ' <div class="btn-toolbar inline" >';
echo ' <div class="btn-group" >';
foreach ( $t_prefix_array as $t_prefix => $t_caption ) {
if( $t_prefix === 'UNUSED' ) {
$t_title = ' title="[' . $t_unused_user_count . '] (' . lang_get( 'never_logged_in_title' ) . ')"';
} else if( $t_prefix === 'NEW' ) {
$t_title = ' title="[' . $t_new_user_count . '] (' . lang_get( '1_week_title' ) . ')"';
} else {
$t_title = '';
}
$t_active = (string)$t_prefix === $f_filter ? 'active' : '';
print_manage_user_sort_link( 'manage_user_page.php',
$t_caption,
$c_sort,
$c_dir, null, $c_hide_inactive, $t_prefix, $c_show_disabled,
'btn btn-xs btn-white btn-primary ' . $t_active );
}
echo '</div>';
echo '</div>';
echo '</div>';
echo '<div class="space-10"></div >';
$t_where_params = array();
if( $f_filter === 'ALL' ) {
$t_where = '(1 = 1)';
} else if( $f_filter === 'UNUSED' ) {
$t_where = '(login_count = 0) AND ( date_created = last_visit )';
} else if( $f_filter === 'NEW' ) {
$t_where = db_helper_compare_time( db_param(), '<=', 'date_created', $t_days_old );
$t_where_params[] = db_now();
} else {
$t_where_params[] = $f_filter . '%';
$t_where = db_helper_like( 'UPPER(username)' );
}
$p_per_page = 50;
$t_offset = ( ( $f_page_number - 1 ) * $p_per_page );
$t_total_user_count = 0;
# Get the user data in $c_sort order
$t_result = '';
if( ON != $c_show_disabled ) {
$t_where .= ' AND enabled = ' . db_param();
$t_where_params[] = true;
}
if( OFF != $c_hide_inactive ) {
$t_where .= ' AND ' . db_helper_compare_time( db_param(), '<', 'last_visit', $t_days_old );
$t_where_params[] = db_now();
}
$t_query = 'SELECT count(*) as user_count FROM {user} WHERE ' . $t_where;
$t_result = db_query( $t_query, $t_where_params );
$t_row = db_fetch_array( $t_result );
$t_total_user_count = $t_row['user_count'];
$t_page_count = ceil( $t_total_user_count / $p_per_page );
if( $t_page_count < 1 ) {
$t_page_count = 1;
}
# Make sure $p_page_number isn't past the last page.
if( $f_page_number > $t_page_count ) {
$f_page_number = $t_page_count;
}
# Make sure $p_page_number isn't before the first page
if( $f_page_number < 1 ) {
$f_page_number = 1;
}
$t_query = 'SELECT * FROM {user} WHERE ' . $t_where . ' ORDER BY ' . $c_sort . ' ' . $c_dir;
$t_result = db_query( $t_query, $t_where_params, $p_per_page, $t_offset );
$t_users = array();
while( $t_row = db_fetch_array( $t_result ) ) {
$t_users[] = $t_row;
}
$t_user_count = count( $t_users );
?>
<div class="widget-box widget-color-blue2">
<div class="widget-header widget-header-small">
<h4 class="widget-title lighter">
<i class="ace-icon fa fa-users"></i>
<?php echo lang_get('manage_accounts_title') ?>
<span class="badge"><?php echo $t_total_user_count ?></span>
</h4>
</div>
<div class="widget-body">
<div class="widget-toolbox padding-8 clearfix">
<div id="manage-user-div" class="form-container">
<div class="pull-left">
<?php print_form_button( 'manage_user_create_page.php', lang_get( 'create_new_account_link' ), null, null, 'btn btn-primary btn-white btn-round' ) ?>
</div>
<?php if( $f_filter === 'UNUSED' ) { ?>
<div class="pull-left">
<?php print_form_button('manage_user_prune.php', lang_get('prune_accounts'), null, null, 'btn btn-primary btn-white btn-round') ?>
</div>
<?php } ?>
<div class="pull-right">
<form id="manage-user-filter" method="post" action="manage_user_page.php" class="form-inline">
<fieldset>
<?php # CSRF protection not required here - form does not result in modifications ?>
<input type="hidden" name="sort" value="<?php echo $c_sort ?>" />
<input type="hidden" name="dir" value="<?php echo $c_dir ?>" />
<input type="hidden" name="save" value="1" />
<input type="hidden" name="filter" value="<?php echo $f_filter ?>" />
<label class="inline">
<input type="checkbox" class="ace" name="hideinactive" value="<?php echo ON ?>" <?php check_checked( (int)$c_hide_inactive, ON ); ?> />
<span class="lbl"> <?php echo lang_get( 'hide_inactive' ) ?></span>
</label>
<label class="inline">
<input type="checkbox" class="ace" name="showdisabled" value="<?php echo ON ?>" <?php check_checked( (int)$c_show_disabled, ON ); ?> />
<span class="lbl"> <?php echo lang_get( 'show_disabled' ) ?></span>
</label>
<input type="submit" class="btn btn-primary btn-sm btn-white btn-round" value="<?php echo lang_get( 'filter_button' ) ?>" />
</fieldset>
</form>
</div>
</div>
</div>
<div class="widget-main no-padding">
<div class="table-responsive">
<table class="table table-striped table-bordered table-condensed table-hover">
<thead>
<tr>
<?php
# Print column headers with sort links
$t_columns = array(
'username', 'realname', 'email', 'access_level',
'enabled', 'protected', 'date_created', 'last_visit'
);
foreach( $t_columns as $t_col ) {
echo "\t<th>";
print_manage_user_sort_link( 'manage_user_page.php',
lang_get( $t_col ),
$t_col,
$c_dir, $c_sort, $c_hide_inactive, $f_filter, $c_show_disabled );
print_sort_icon( $c_dir, $c_sort, $t_col );
echo "</th>\n";
}
?>
</tr>
</thead>
<tbody>
<?php
$t_date_format = config_get( 'normal_date_format' );
$t_access_level = array();
for( $i=0; $i<$t_user_count; $i++ ) {
# prefix user data with u_
$t_user = $t_users[$i];
extract( $t_user, EXTR_PREFIX_ALL, 'u' );
$u_date_created = date( $t_date_format, $u_date_created );
$u_last_visit = date( $t_date_format, $u_last_visit );
if( !isset( $t_access_level[$u_access_level] ) ) {
$t_access_level[$u_access_level] = get_enum_element( 'access_levels', $u_access_level );
} ?>
<tr>
<td><?php
if( access_has_global_level( $u_access_level ) ) { ?>
<a href="manage_user_edit_page.php?user_id=<?php echo $u_id ?>"><?php echo string_display_line( $u_username ) ?></a><?php
} else {
echo string_display_line( $u_username );
} ?>
</td>
<td><?php echo string_display_line( $u_realname ) ?></td>
<td><?php print_email_link( $u_email, $u_email ) ?></td>
<td><?php echo $t_access_level[$u_access_level] ?></td>
<td class="center"><?php echo trans_bool( $u_enabled ) ?></td>
<td class="center"><?php
if( $u_protected ) {
echo ' ' . $t_lock_image;
} else {
echo ' ';
} ?>
</td>
<td><?php echo $u_date_created ?></td>
<td><?php echo $u_last_visit ?></td>
</tr>
<?php
} # end for
?>
</tbody>
</table>
</div>
</div>
<div class="widget-toolbox padding-8 clearfix">
<div id="manage-user-edit-div" class="form-inline pull-left">
<form id="manage-user-edit-form" method="get" action="manage_user_edit_page.php" class="form-inline"
<?php # CSRF protection not required here - form does not result in modifications ?>>
<label class="inline" for="username"><?php echo lang_get( 'search' ) ?></label>
<input id="username" type="text" name="username" class="input-sm" value="" />
<input type="submit" class="btn btn-primary btn-sm btn-white btn-round" value="<?php echo lang_get( 'manage_user' ) ?>" />
</form>
</div>
<div class="btn-toolbar pull-right">
<?php
# @todo hack - pass in the hide inactive filter via cheating the actual filter value
print_page_links( 'manage_user_page.php', 1, $t_page_count, (int)$f_page_number, $f_filter . $t_hide_inactive_filter . $t_show_disabled_filter . "&sort=$c_sort&dir=$c_dir");
?>
</div>
</div>
</div>
</div>
</div>
<?php
layout_page_end();
|
<?php
# MantisBT - A PHP based bugtracking system
# MantisBT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# MantisBT 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 MantisBT. If not, see <http://www.gnu.org/licenses/>.
/**
* User Page
*
* @package MantisBT
* @copyright Copyright 2000 - 2002 Kenzaburo Ito - kenito@300baud.org
* @copyright Copyright 2002 MantisBT Team - mantisbt-dev@lists.sourceforge.net
* @link http://www.mantisbt.org
*
* @uses core.php
* @uses access_api.php
* @uses authentication_api.php
* @uses config_api.php
* @uses constant_inc.php
* @uses database_api.php
* @uses gpc_api.php
* @uses helper_api.php
* @uses html_api.php
* @uses icon_api.php
* @uses lang_api.php
* @uses print_api.php
* @uses string_api.php
* @uses utility_api.php
*/
require_once( 'core.php' );
require_api( 'access_api.php' );
require_api( 'authentication_api.php' );
require_api( 'config_api.php' );
require_api( 'constant_inc.php' );
require_api( 'database_api.php' );
require_api( 'gpc_api.php' );
require_api( 'helper_api.php' );
require_api( 'html_api.php' );
require_api( 'icon_api.php' );
require_api( 'lang_api.php' );
require_api( 'print_api.php' );
require_api( 'string_api.php' );
require_api( 'utility_api.php' );
auth_reauthenticate();
access_ensure_global_level( config_get( 'manage_user_threshold' ) );
$t_cookie_name = config_get( 'manage_users_cookie' );
$t_lock_image = '<i class="fa fa-lock fa-lg" alt="' . lang_get( 'protected' ) . '" />';
$f_save = gpc_get_bool( 'save' );
$f_filter = utf8_strtoupper( gpc_get_string( 'filter', config_get( 'default_manage_user_prefix' ) ) );
$f_page_number = gpc_get_int( 'page_number', 1 );
if( !$f_save && !is_blank( gpc_get_cookie( $t_cookie_name, '' ) ) ) {
$t_manage_arr = explode( ':', gpc_get_cookie( $t_cookie_name ) );
# Hide Inactive
$f_hide_inactive = (bool)$t_manage_arr[0];
# Sort field
if ( isset( $t_manage_arr[1] ) ) {
$f_sort = $t_manage_arr[1];
} else {
$f_sort = 'username';
}
# Sort order
if ( isset( $t_manage_arr[2] ) ) {
$f_dir = $t_manage_arr[2];
} else {
$f_dir = 'DESC';
}
# Show Disabled
if ( isset( $t_manage_arr[3] ) ) {
$f_show_disabled = $t_manage_arr[3];
}
} else {
$f_sort = gpc_get_string( 'sort', 'username' );
$f_dir = gpc_get_string( 'dir', 'ASC' );
$f_hide_inactive = gpc_get_bool( 'hideinactive' );
$f_show_disabled = gpc_get_bool( 'showdisabled' );
}
# Clean up the form variables
if( !db_field_exists( $f_sort, db_get_table( 'user' ) ) ) {
$c_sort = 'username';
} else {
$c_sort = addslashes( $f_sort );
}
$c_dir = ( $f_dir == 'ASC' ) ? 'ASC' : 'DESC';
# OFF = show inactive users, anything else = hide them
$c_hide_inactive = ( $f_hide_inactive == OFF ) ? OFF : ON;
$t_hide_inactive_filter = '&hideinactive=' . $c_hide_inactive;
# OFF = hide disabled users, anything else = show them
$c_show_disabled = ( $f_show_disabled == OFF ) ? OFF : ON;
$t_show_disabled_filter = '&showdisabled=' . $c_show_disabled;
# set cookie values for hide inactive, sort by, dir and show disabled
if( $f_save ) {
$t_manage_string = $c_hide_inactive.':'.$c_sort.':'.$c_dir.':'.$c_show_disabled;
gpc_set_cookie( $t_cookie_name, $t_manage_string, true );
}
layout_page_header( lang_get( 'manage_users_link' ) );
layout_page_begin( 'manage_overview_page.php' );
print_manage_menu( 'manage_user_page.php' );
# New Accounts Form BEGIN
$t_days_old = 7 * SECONDS_PER_DAY;
$t_query = 'SELECT COUNT(*) AS new_user_count FROM {user}
WHERE ' . db_helper_compare_time( db_param(), '<=', 'date_created', $t_days_old );
$t_result = db_query( $t_query, array( db_now() ) );
$t_row = db_fetch_array( $t_result );
$t_new_user_count = $t_row['new_user_count'];
# Never Logged In Form BEGIN
$t_query = 'SELECT COUNT(*) AS unused_user_count FROM {user}
WHERE ( login_count = 0 ) AND ( date_created = last_visit )';
$t_result = db_query( $t_query );
$t_row = db_fetch_array( $t_result );
$t_unused_user_count = $t_row['unused_user_count'];
# Manage Form BEGIN
$t_prefix_array = array();
$t_prefix_array['ALL'] = lang_get( 'show_all_users' );
for( $i = 'A'; $i != 'AA'; $i++ ) {
$t_prefix_array[$i] = $i;
}
for( $i = 0; $i <= 9; $i++ ) {
$t_prefix_array[(string)$i] = (string)$i;
}
$t_prefix_array['UNUSED'] = lang_get( 'users_unused' );
$t_prefix_array['NEW'] = lang_get( 'users_new' );
echo '<div class="col-md-12 col-xs-12">';
echo '<div class = "space-10"></div>';
echo '<div class="center" >';
echo ' <div class="btn-toolbar inline" >';
echo ' <div class="btn-group" >';
foreach ( $t_prefix_array as $t_prefix => $t_caption ) {
if( $t_prefix === 'UNUSED' ) {
$t_title = ' title="[' . $t_unused_user_count . '] (' . lang_get( 'never_logged_in_title' ) . ')"';
} else if( $t_prefix === 'NEW' ) {
$t_title = ' title="[' . $t_new_user_count . '] (' . lang_get( '1_week_title' ) . ')"';
} else {
$t_title = '';
}
$t_active = (string)$t_prefix === $f_filter ? 'active' : '';
print_manage_user_sort_link( 'manage_user_page.php',
$t_caption,
$c_sort,
$c_dir, null, $c_hide_inactive, $t_prefix, $c_show_disabled,
'btn btn-xs btn-white btn-primary ' . $t_active );
}
echo '</div>';
echo '</div>';
echo '</div>';
echo '<div class="space-10"></div >';
$t_where_params = array();
if( $f_filter === 'ALL' ) {
$t_where = '(1 = 1)';
} else if( $f_filter === 'UNUSED' ) {
$t_where = '(login_count = 0) AND ( date_created = last_visit )';
} else if( $f_filter === 'NEW' ) {
$t_where = db_helper_compare_time( db_param(), '<=', 'date_created', $t_days_old );
$t_where_params[] = db_now();
} else {
$t_where_params[] = $f_filter . '%';
$t_where = db_helper_like( 'UPPER(username)' );
}
$p_per_page = 50;
$t_offset = ( ( $f_page_number - 1 ) * $p_per_page );
$t_total_user_count = 0;
# Get the user data in $c_sort order
$t_result = '';
if( ON != $c_show_disabled ) {
$t_where .= ' AND enabled = ' . db_param();
$t_where_params[] = true;
}
if( OFF != $c_hide_inactive ) {
$t_where .= ' AND ' . db_helper_compare_time( db_param(), '<', 'last_visit', $t_days_old );
$t_where_params[] = db_now();
}
$t_query = 'SELECT count(*) as user_count FROM {user} WHERE ' . $t_where;
$t_result = db_query( $t_query, $t_where_params );
$t_row = db_fetch_array( $t_result );
$t_total_user_count = $t_row['user_count'];
$t_page_count = ceil( $t_total_user_count / $p_per_page );
if( $t_page_count < 1 ) {
$t_page_count = 1;
}
# Make sure $p_page_number isn't past the last page.
if( $f_page_number > $t_page_count ) {
$f_page_number = $t_page_count;
}
# Make sure $p_page_number isn't before the first page
if( $f_page_number < 1 ) {
$f_page_number = 1;
}
$t_query = 'SELECT * FROM {user} WHERE ' . $t_where . ' ORDER BY ' . $c_sort . ' ' . $c_dir;
$t_result = db_query( $t_query, $t_where_params, $p_per_page, $t_offset );
$t_users = array();
while( $t_row = db_fetch_array( $t_result ) ) {
$t_users[] = $t_row;
}
$t_user_count = count( $t_users );
?>
<div class="widget-box widget-color-blue2">
<div class="widget-header widget-header-small">
<h4 class="widget-title lighter">
<i class="ace-icon fa fa-users"></i>
<?php echo lang_get('manage_accounts_title') ?>
<span class="badge"><?php echo $t_total_user_count ?></span>
</h4>
</div>
<div class="widget-body">
<div class="widget-toolbox padding-8 clearfix">
<div id="manage-user-div" class="form-container">
<div class="pull-left">
<?php print_form_button( 'manage_user_create_page.php', lang_get( 'create_new_account_link' ), null, null, 'btn btn-primary btn-white btn-round' ) ?>
</div>
<?php if( $f_filter === 'UNUSED' ) { ?>
<div class="pull-left">
<?php print_form_button('manage_user_prune.php', lang_get('prune_accounts'), null, null, 'btn btn-primary btn-white btn-round') ?>
</div>
<?php } ?>
<div class="pull-right">
<form id="manage-user-filter" method="post" action="manage_user_page.php" class="form-inline">
<fieldset>
<?php # CSRF protection not required here - form does not result in modifications ?>
<input type="hidden" name="sort" value="<?php echo $c_sort ?>" />
<input type="hidden" name="dir" value="<?php echo $c_dir ?>" />
<input type="hidden" name="save" value="1" />
<input type="hidden" name="filter" value="<?php echo string_attribute( $f_filter ); ?>" />
<label class="inline">
<input type="checkbox" class="ace" name="hideinactive" value="<?php echo ON ?>" <?php check_checked( (int)$c_hide_inactive, ON ); ?> />
<span class="lbl"> <?php echo lang_get( 'hide_inactive' ) ?></span>
</label>
<label class="inline">
<input type="checkbox" class="ace" name="showdisabled" value="<?php echo ON ?>" <?php check_checked( (int)$c_show_disabled, ON ); ?> />
<span class="lbl"> <?php echo lang_get( 'show_disabled' ) ?></span>
</label>
<input type="submit" class="btn btn-primary btn-sm btn-white btn-round" value="<?php echo lang_get( 'filter_button' ) ?>" />
</fieldset>
</form>
</div>
</div>
</div>
<div class="widget-main no-padding">
<div class="table-responsive">
<table class="table table-striped table-bordered table-condensed table-hover">
<thead>
<tr>
<?php
# Print column headers with sort links
$t_columns = array(
'username', 'realname', 'email', 'access_level',
'enabled', 'protected', 'date_created', 'last_visit'
);
foreach( $t_columns as $t_col ) {
echo "\t<th>";
print_manage_user_sort_link( 'manage_user_page.php',
lang_get( $t_col ),
$t_col,
$c_dir, $c_sort, $c_hide_inactive, $f_filter, $c_show_disabled );
print_sort_icon( $c_dir, $c_sort, $t_col );
echo "</th>\n";
}
?>
</tr>
</thead>
<tbody>
<?php
$t_date_format = config_get( 'normal_date_format' );
$t_access_level = array();
for( $i=0; $i<$t_user_count; $i++ ) {
# prefix user data with u_
$t_user = $t_users[$i];
extract( $t_user, EXTR_PREFIX_ALL, 'u' );
$u_date_created = date( $t_date_format, $u_date_created );
$u_last_visit = date( $t_date_format, $u_last_visit );
if( !isset( $t_access_level[$u_access_level] ) ) {
$t_access_level[$u_access_level] = get_enum_element( 'access_levels', $u_access_level );
} ?>
<tr>
<td><?php
if( access_has_global_level( $u_access_level ) ) { ?>
<a href="manage_user_edit_page.php?user_id=<?php echo $u_id ?>"><?php echo string_display_line( $u_username ) ?></a><?php
} else {
echo string_display_line( $u_username );
} ?>
</td>
<td><?php echo string_display_line( $u_realname ) ?></td>
<td><?php print_email_link( $u_email, $u_email ) ?></td>
<td><?php echo $t_access_level[$u_access_level] ?></td>
<td class="center"><?php echo trans_bool( $u_enabled ) ?></td>
<td class="center"><?php
if( $u_protected ) {
echo ' ' . $t_lock_image;
} else {
echo ' ';
} ?>
</td>
<td><?php echo $u_date_created ?></td>
<td><?php echo $u_last_visit ?></td>
</tr>
<?php
} # end for
?>
</tbody>
</table>
</div>
</div>
<div class="widget-toolbox padding-8 clearfix">
<div id="manage-user-edit-div" class="form-inline pull-left">
<form id="manage-user-edit-form" method="get" action="manage_user_edit_page.php" class="form-inline"
<?php # CSRF protection not required here - form does not result in modifications ?>>
<label class="inline" for="username"><?php echo lang_get( 'search' ) ?></label>
<input id="username" type="text" name="username" class="input-sm" value="" />
<input type="submit" class="btn btn-primary btn-sm btn-white btn-round" value="<?php echo lang_get( 'manage_user' ) ?>" />
</form>
</div>
<div class="btn-toolbar pull-right">
<?php
# @todo hack - pass in the hide inactive filter via cheating the actual filter value
print_page_links( 'manage_user_page.php', 1, $t_page_count, (int)$f_page_number, $f_filter . $t_hide_inactive_filter . $t_show_disabled_filter . "&sort=$c_sort&dir=$c_dir");
?>
</div>
</div>
</div>
</div>
</div>
<?php
layout_page_end();
|
9b5b71dadbeeeec27efea59f562ac5bd6d2673b7
|
https://github.com/mantisbt/mantisbt
|
trust.tpl.php
|
php
|
<?php
$this->includeAtTemplateBase('includes/header.php');
?>
<div class="form">
<?php
$params = array(
'%SITEURL%' => '<code>' . htmlspecialchars($this->data['trustRoot']) . '</code>',
);
echo('<p>' . $this->t('{openidProvider:openidProvider:confirm_question}', $params) . '</p>');
?>
<form method="post" action="?">
<input type="hidden" name="StateID" value="<?php echo $this->data['StateID']; ?>" />
<input type="checkbox" name="TrustRemember" value="on" id="remember" />
<label for="TrustRemember"><?php echo($this->t('{openidProvider:openidProvider:remember}')); ?></label>
<br />
<input type="submit" name="TrustYes" value="<?php echo($this->t('{openidProvider:openidProvider:confirm}')); ?>" />
<input type="submit" name="TrustNo" value="<?php echo($this->t('{openidProvider:openidProvider:notconfirm}')); ?>" />
</form>
</div>
<?php
$this->includeAtTemplateBase('includes/footer.php');
?>
|
<?php
$this->includeAtTemplateBase('includes/header.php');
?>
<div class="form">
<?php
$params = array(
'%SITEURL%' => '<code>' . htmlspecialchars($this->data['trustRoot']) . '</code>',
);
echo('<p>' . $this->t('{openidProvider:openidProvider:confirm_question}', $params) . '</p>');
?>
<form method="post" action="?">
<input type="hidden" name="StateID" value="<?php echo htmlspecialchars($this->data['StateID']); ?>" />
<input type="checkbox" name="TrustRemember" value="on" id="remember" />
<label for="TrustRemember"><?php echo($this->t('{openidProvider:openidProvider:remember}')); ?></label>
<br />
<input type="submit" name="TrustYes" value="<?php echo($this->t('{openidProvider:openidProvider:confirm}')); ?>" />
<input type="submit" name="TrustNo" value="<?php echo($this->t('{openidProvider:openidProvider:notconfirm}')); ?>" />
</form>
</div>
<?php
$this->includeAtTemplateBase('includes/footer.php');
?>
|
8365d48c863cf06ccf1465cc0a161cefae29d69d
|
https://github.com/simplesamlphp/simplesamlphp-module-openidprovider
|
api.php
|
php
|
<?php
#API IS DISABLED BY DEFAULT AS ITS STILL IN DEV. ENABLE AT YOUR OWN RISK.
define("IN_WALLET", false); #TO ENABLE SET TO TRUE
###################################################
include('common.php');
$con = mysqli_connect("$db_host","$db_user","$db_pass","$db_name");
$key = $_GET['key'];
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL. Make sure to edit the common.php file: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM users where secret = '$key' and authused=1");
while($row = mysqli_fetch_array($result)) {
$id = $row['id'];
$username = $row['username'];
$pin = $row['supportpin'];
$twofactoren = $row['authused'];
$isadmin = $row['admin'];
$client = new Client($rpc_host, $rpc_port, $rpc_user, $rpc_pass);
$apibal = $client->getBalance($username) - $fee;
$addr = $client->getAddress($username);
}
if ($isadmin == 1) {
$ifadmin = "true";
} else {
$ifadmin = "false";
}
if ($twofactoren == 1) {
$iftwofactor = "true";
} else {
$iftwofactor = "false";
}
echo json_encode(array("id" => "$id", "username" => "$username", "balance" => "$apibal", "addresses" => "$addr", "Support Pin" => "$pin", "Two Factor Enabled"=> "$iftwofactor", "admin" => "$ifadmin"));
?>
|
<?php
#API IS DISABLED BY DEFAULT AS ITS STILL IN DEV. ENABLE AT YOUR OWN RISK.
define("IN_WALLET", false); #TO ENABLE SET TO TRUE
###################################################
include('common.php');
$con = mysqli_connect("$db_host","$db_user","$db_pass","$db_name");
$key = mysqli_real_escape_string($con, $_GET['key']);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL. Make sure to edit the common.php file: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM users where secret = '$key' and authused=1");
while($row = mysqli_fetch_array($result)) {
$id = $row['id'];
$username = $row['username'];
$pin = $row['supportpin'];
$twofactoren = $row['authused'];
$isadmin = $row['admin'];
$client = new Client($rpc_host, $rpc_port, $rpc_user, $rpc_pass);
$apibal = $client->getBalance($username) - $fee;
$addr = $client->getAddress($username);
}
if ($isadmin == 1) {
$ifadmin = "true";
} else {
$ifadmin = "false";
}
if ($twofactoren == 1) {
$iftwofactor = "true";
} else {
$iftwofactor = "false";
}
echo json_encode(array("id" => "$id", "username" => "$username", "balance" => "$apibal", "addresses" => "$addr", "Support Pin" => "$pin", "Two Factor Enabled"=> "$iftwofactor", "admin" => "$ifadmin"));
?>
|
b420f8c4cbe7f06a34d1b05e90ee5cdfe0aa83bb
|
https://github.com/jfm-so/piwallet
|
add.php
|
php
|
<?php
/**
* Elgg report action
*/
$title = get_input('title');
$description = get_input('description');
$address = get_input('address');
$access = ACCESS_PRIVATE; //this is private and only admins can see it
$fail = function () use ($address) {
return elgg_error_response(elgg_echo('reportedcontent:failed'), $address);
};
if (!$title || !$address) {
$fail();
}
$report = new ElggReportedContent();
$report->owner_guid = elgg_get_logged_in_user_guid();
$report->title = $title;
$report->address = $address;
$report->description = $description;
$report->access_id = $access;
if (!$report->save()) {
$fail();
}
if (!elgg_trigger_plugin_hook('reportedcontent:add', 'system', ['report' => $report], true)) {
$report->delete();
$fail();
}
$report->state = 'active';
return elgg_ok_response('', elgg_echo('reportedcontent:success'), $address);
|
<?php
/**
* Elgg report action
*/
$title = get_input('title');
$description = get_input('description');
$address = get_input('address');
$access = ACCESS_PRIVATE; //this is private and only admins can see it
$fail = function () use ($address) {
return elgg_error_response(elgg_echo('reportedcontent:failed'), $address);
};
if (!$title || !$address) {
$fail();
}
$report = new ElggReportedContent();
$report->owner_guid = elgg_get_logged_in_user_guid();
$report->title = $title;
$report->address = elgg_normalize_site_url($address);
$report->description = $description;
$report->access_id = $access;
if (!$report->save()) {
$fail();
}
if (!elgg_trigger_plugin_hook('reportedcontent:add', 'system', ['report' => $report], true)) {
$report->delete();
$fail();
}
$report->state = 'active';
return elgg_ok_response('', elgg_echo('reportedcontent:success'), $address);
|
c30b17bf75256ed3fcc84e2083147cc3951423d0
|
https://github.com/elgg/elgg
|
appconfig.php
|
php
|
<?php
/**
* Copyright (c) 2011, Robin Appelman <icewind1991@gmail.com>
* This file is licensed under the Affero General Public License version 3 or later.
* See the COPYING-README file.
*/
require_once ("../../lib/base.php");
OC_JSON::checkLoggedIn();
$action=isset($_POST['action'])?$_POST['action']:$_GET['action'];
$result=false;
switch($action){
case 'getValue':
$result=OC_Appconfig::getValue($_GET['app'],$_GET['key'],$_GET['defaultValue']);
break;
case 'setValue':
$result=OC_Appconfig::setValue($_POST['app'],$_POST['key'],$_POST['value']);
break;
case 'getApps':
$result=OC_Appconfig::getApps();
break;
case 'getKeys':
$result=OC_Appconfig::getKeys($_GET['app']);
break;
case 'hasKey':
$result=OC_Appconfig::hasKey($_GET['app'],$_GET['key']);
break;
case 'deleteKey':
$result=OC_Appconfig::deleteKey($_POST['app'],$_POST['key']);
break;
case 'deleteApp':
$result=OC_Appconfig::deleteApp($_POST['app']);
break;
}
OC_JSON::success(array('data'=>$result));
|
<?php
/**
* Copyright (c) 2011, Robin Appelman <icewind1991@gmail.com>
* This file is licensed under the Affero General Public License version 3 or later.
* See the COPYING-README file.
*/
require_once ("../../lib/base.php");
OC_Util::checkAdminUser();
OC_JSON::checkLoggedIn();
$action=isset($_POST['action'])?$_POST['action']:$_GET['action'];
$result=false;
switch($action){
case 'getValue':
$result=OC_Appconfig::getValue($_GET['app'],$_GET['key'],$_GET['defaultValue']);
break;
case 'setValue':
$result=OC_Appconfig::setValue($_POST['app'],$_POST['key'],$_POST['value']);
break;
case 'getApps':
$result=OC_Appconfig::getApps();
break;
case 'getKeys':
$result=OC_Appconfig::getKeys($_GET['app']);
break;
case 'hasKey':
$result=OC_Appconfig::hasKey($_GET['app'],$_GET['key']);
break;
case 'deleteKey':
$result=OC_Appconfig::deleteKey($_POST['app'],$_POST['key']);
break;
case 'deleteApp':
$result=OC_Appconfig::deleteApp($_POST['app']);
break;
}
OC_JSON::success(array('data'=>$result));
|
9605e1926c6081e88326bf78a02c1d1b83126c4f
|
https://github.com/owncloud/core
|
thread_info.h
|
objective-c
|
/* thread_info.h: MIPS low-level thread information
*
* Copyright (C) 2002 David Howells (dhowells@redhat.com)
* - Incorporating suggestions made by Linus Torvalds and Dave Miller
*/
#ifndef _ASM_THREAD_INFO_H
#define _ASM_THREAD_INFO_H
#ifdef __KERNEL__
#ifndef __ASSEMBLY__
#include <asm/processor.h>
/*
* low level task data that entry.S needs immediate access to
* - this struct should fit entirely inside of one cache line
* - this struct shares the supervisor stack pages
* - if the contents of this structure are changed, the assembly constants
* must also be changed
*/
struct thread_info {
struct task_struct *task; /* main task structure */
struct exec_domain *exec_domain; /* execution domain */
unsigned long flags; /* low level flags */
unsigned long tp_value; /* thread pointer */
__u32 cpu; /* current CPU */
int preempt_count; /* 0 => preemptable, <0 => BUG */
mm_segment_t addr_limit; /*
* thread address space limit:
* 0x7fffffff for user-thead
* 0xffffffff for kernel-thread
*/
struct restart_block restart_block;
struct pt_regs *regs;
};
/*
* macros/functions for gaining access to the thread information structure
*/
#define INIT_THREAD_INFO(tsk) \
{ \
.task = &tsk, \
.exec_domain = &default_exec_domain, \
.flags = _TIF_FIXADE, \
.cpu = 0, \
.preempt_count = INIT_PREEMPT_COUNT, \
.addr_limit = KERNEL_DS, \
.restart_block = { \
.fn = do_no_restart_syscall, \
}, \
}
#define init_thread_info (init_thread_union.thread_info)
#define init_stack (init_thread_union.stack)
/* How to get the thread information struct from C. */
static inline struct thread_info *current_thread_info(void)
{
register struct thread_info *__current_thread_info __asm__("$28");
return __current_thread_info;
}
#endif /* !__ASSEMBLY__ */
/* thread information allocation */
#if defined(CONFIG_PAGE_SIZE_4KB) && defined(CONFIG_32BIT)
#define THREAD_SIZE_ORDER (1)
#endif
#if defined(CONFIG_PAGE_SIZE_4KB) && defined(CONFIG_64BIT)
#define THREAD_SIZE_ORDER (2)
#endif
#ifdef CONFIG_PAGE_SIZE_8KB
#define THREAD_SIZE_ORDER (1)
#endif
#ifdef CONFIG_PAGE_SIZE_16KB
#define THREAD_SIZE_ORDER (0)
#endif
#ifdef CONFIG_PAGE_SIZE_32KB
#define THREAD_SIZE_ORDER (0)
#endif
#ifdef CONFIG_PAGE_SIZE_64KB
#define THREAD_SIZE_ORDER (0)
#endif
#define THREAD_SIZE (PAGE_SIZE << THREAD_SIZE_ORDER)
#define THREAD_MASK (THREAD_SIZE - 1UL)
#define STACK_WARN (THREAD_SIZE / 8)
/*
* thread information flags
* - these are process state flags that various assembly files may need to
* access
* - pending work-to-be-done flags are in LSW
* - other flags in MSW
*/
#define TIF_SIGPENDING 1 /* signal pending */
#define TIF_NEED_RESCHED 2 /* rescheduling necessary */
#define TIF_SYSCALL_AUDIT 3 /* syscall auditing active */
#define TIF_SECCOMP 4 /* secure computing */
#define TIF_NOTIFY_RESUME 5 /* callback before returning to user */
#define TIF_RESTORE_SIGMASK 9 /* restore signal mask in do_signal() */
#define TIF_USEDFPU 16 /* FPU was used by this task this quantum (SMP) */
#define TIF_MEMDIE 18 /* is terminating due to OOM killer */
#define TIF_NOHZ 19 /* in adaptive nohz mode */
#define TIF_FIXADE 20 /* Fix address errors in software */
#define TIF_LOGADE 21 /* Log address errors to syslog */
#define TIF_32BIT_REGS 22 /* 32-bit general purpose registers */
#define TIF_32BIT_ADDR 23 /* 32-bit address space (o32/n32) */
#define TIF_FPUBOUND 24 /* thread bound to FPU-full CPU set */
#define TIF_LOAD_WATCH 25 /* If set, load watch registers */
#define TIF_SYSCALL_TRACEPOINT 26 /* syscall tracepoint instrumentation */
#define TIF_32BIT_FPREGS 27 /* 32-bit floating point registers */
#define TIF_SYSCALL_TRACE 31 /* syscall trace active */
#define _TIF_SYSCALL_TRACE (1<<TIF_SYSCALL_TRACE)
#define _TIF_SIGPENDING (1<<TIF_SIGPENDING)
#define _TIF_NEED_RESCHED (1<<TIF_NEED_RESCHED)
#define _TIF_SYSCALL_AUDIT (1<<TIF_SYSCALL_AUDIT)
#define _TIF_SECCOMP (1<<TIF_SECCOMP)
#define _TIF_NOTIFY_RESUME (1<<TIF_NOTIFY_RESUME)
#define _TIF_USEDFPU (1<<TIF_USEDFPU)
#define _TIF_NOHZ (1<<TIF_NOHZ)
#define _TIF_FIXADE (1<<TIF_FIXADE)
#define _TIF_LOGADE (1<<TIF_LOGADE)
#define _TIF_32BIT_REGS (1<<TIF_32BIT_REGS)
#define _TIF_32BIT_ADDR (1<<TIF_32BIT_ADDR)
#define _TIF_FPUBOUND (1<<TIF_FPUBOUND)
#define _TIF_LOAD_WATCH (1<<TIF_LOAD_WATCH)
#define _TIF_32BIT_FPREGS (1<<TIF_32BIT_FPREGS)
#define _TIF_SYSCALL_TRACEPOINT (1<<TIF_SYSCALL_TRACEPOINT)
#define _TIF_WORK_SYSCALL_ENTRY (_TIF_NOHZ | _TIF_SYSCALL_TRACE | \
_TIF_SYSCALL_AUDIT | _TIF_SYSCALL_TRACEPOINT)
/* work to do in syscall_trace_leave() */
#define _TIF_WORK_SYSCALL_EXIT (_TIF_NOHZ | _TIF_SYSCALL_TRACE | \
_TIF_SYSCALL_AUDIT | _TIF_SYSCALL_TRACEPOINT)
/* work to do on interrupt/exception return */
#define _TIF_WORK_MASK \
(_TIF_SIGPENDING | _TIF_NEED_RESCHED | _TIF_NOTIFY_RESUME)
/* work to do on any return to u-space */
#define _TIF_ALLWORK_MASK (_TIF_NOHZ | _TIF_WORK_MASK | \
_TIF_WORK_SYSCALL_EXIT | \
_TIF_SYSCALL_TRACEPOINT)
/*
* We stash processor id into a COP0 register to retrieve it fast
* at kernel exception entry.
*/
#if defined(CONFIG_MIPS_MT_SMTC)
#define SMP_CPUID_REG 2, 2 /* TCBIND */
#define ASM_SMP_CPUID_REG $2, 2
#define SMP_CPUID_PTRSHIFT 19
#elif defined(CONFIG_MIPS_PGD_C0_CONTEXT)
#define SMP_CPUID_REG 20, 0 /* XCONTEXT */
#define ASM_SMP_CPUID_REG $20
#define SMP_CPUID_PTRSHIFT 48
#else
#define SMP_CPUID_REG 4, 0 /* CONTEXT */
#define ASM_SMP_CPUID_REG $4
#define SMP_CPUID_PTRSHIFT 23
#endif
#ifdef CONFIG_64BIT
#define SMP_CPUID_REGSHIFT (SMP_CPUID_PTRSHIFT + 3)
#else
#define SMP_CPUID_REGSHIFT (SMP_CPUID_PTRSHIFT + 2)
#endif
#ifdef CONFIG_MIPS_MT_SMTC
#define ASM_CPUID_MFC0 mfc0
#define UASM_i_CPUID_MFC0 uasm_i_mfc0
#else
#define ASM_CPUID_MFC0 MFC0
#define UASM_i_CPUID_MFC0 UASM_i_MFC0
#endif
#endif /* __KERNEL__ */
#endif /* _ASM_THREAD_INFO_H */
|
/* thread_info.h: MIPS low-level thread information
*
* Copyright (C) 2002 David Howells (dhowells@redhat.com)
* - Incorporating suggestions made by Linus Torvalds and Dave Miller
*/
#ifndef _ASM_THREAD_INFO_H
#define _ASM_THREAD_INFO_H
#ifdef __KERNEL__
#ifndef __ASSEMBLY__
#include <asm/processor.h>
/*
* low level task data that entry.S needs immediate access to
* - this struct should fit entirely inside of one cache line
* - this struct shares the supervisor stack pages
* - if the contents of this structure are changed, the assembly constants
* must also be changed
*/
struct thread_info {
struct task_struct *task; /* main task structure */
struct exec_domain *exec_domain; /* execution domain */
unsigned long flags; /* low level flags */
unsigned long tp_value; /* thread pointer */
__u32 cpu; /* current CPU */
int preempt_count; /* 0 => preemptable, <0 => BUG */
mm_segment_t addr_limit; /*
* thread address space limit:
* 0x7fffffff for user-thead
* 0xffffffff for kernel-thread
*/
struct restart_block restart_block;
struct pt_regs *regs;
};
/*
* macros/functions for gaining access to the thread information structure
*/
#define INIT_THREAD_INFO(tsk) \
{ \
.task = &tsk, \
.exec_domain = &default_exec_domain, \
.flags = _TIF_FIXADE, \
.cpu = 0, \
.preempt_count = INIT_PREEMPT_COUNT, \
.addr_limit = KERNEL_DS, \
.restart_block = { \
.fn = do_no_restart_syscall, \
}, \
}
#define init_thread_info (init_thread_union.thread_info)
#define init_stack (init_thread_union.stack)
/* How to get the thread information struct from C. */
static inline struct thread_info *current_thread_info(void)
{
register struct thread_info *__current_thread_info __asm__("$28");
return __current_thread_info;
}
#endif /* !__ASSEMBLY__ */
/* thread information allocation */
#if defined(CONFIG_PAGE_SIZE_4KB) && defined(CONFIG_32BIT)
#define THREAD_SIZE_ORDER (1)
#endif
#if defined(CONFIG_PAGE_SIZE_4KB) && defined(CONFIG_64BIT)
#define THREAD_SIZE_ORDER (2)
#endif
#ifdef CONFIG_PAGE_SIZE_8KB
#define THREAD_SIZE_ORDER (1)
#endif
#ifdef CONFIG_PAGE_SIZE_16KB
#define THREAD_SIZE_ORDER (0)
#endif
#ifdef CONFIG_PAGE_SIZE_32KB
#define THREAD_SIZE_ORDER (0)
#endif
#ifdef CONFIG_PAGE_SIZE_64KB
#define THREAD_SIZE_ORDER (0)
#endif
#define THREAD_SIZE (PAGE_SIZE << THREAD_SIZE_ORDER)
#define THREAD_MASK (THREAD_SIZE - 1UL)
#define STACK_WARN (THREAD_SIZE / 8)
/*
* thread information flags
* - these are process state flags that various assembly files may need to
* access
* - pending work-to-be-done flags are in LSW
* - other flags in MSW
*/
#define TIF_SIGPENDING 1 /* signal pending */
#define TIF_NEED_RESCHED 2 /* rescheduling necessary */
#define TIF_SYSCALL_AUDIT 3 /* syscall auditing active */
#define TIF_SECCOMP 4 /* secure computing */
#define TIF_NOTIFY_RESUME 5 /* callback before returning to user */
#define TIF_RESTORE_SIGMASK 9 /* restore signal mask in do_signal() */
#define TIF_USEDFPU 16 /* FPU was used by this task this quantum (SMP) */
#define TIF_MEMDIE 18 /* is terminating due to OOM killer */
#define TIF_NOHZ 19 /* in adaptive nohz mode */
#define TIF_FIXADE 20 /* Fix address errors in software */
#define TIF_LOGADE 21 /* Log address errors to syslog */
#define TIF_32BIT_REGS 22 /* 32-bit general purpose registers */
#define TIF_32BIT_ADDR 23 /* 32-bit address space (o32/n32) */
#define TIF_FPUBOUND 24 /* thread bound to FPU-full CPU set */
#define TIF_LOAD_WATCH 25 /* If set, load watch registers */
#define TIF_SYSCALL_TRACEPOINT 26 /* syscall tracepoint instrumentation */
#define TIF_32BIT_FPREGS 27 /* 32-bit floating point registers */
#define TIF_SYSCALL_TRACE 31 /* syscall trace active */
#define _TIF_SYSCALL_TRACE (1<<TIF_SYSCALL_TRACE)
#define _TIF_SIGPENDING (1<<TIF_SIGPENDING)
#define _TIF_NEED_RESCHED (1<<TIF_NEED_RESCHED)
#define _TIF_SYSCALL_AUDIT (1<<TIF_SYSCALL_AUDIT)
#define _TIF_SECCOMP (1<<TIF_SECCOMP)
#define _TIF_NOTIFY_RESUME (1<<TIF_NOTIFY_RESUME)
#define _TIF_USEDFPU (1<<TIF_USEDFPU)
#define _TIF_NOHZ (1<<TIF_NOHZ)
#define _TIF_FIXADE (1<<TIF_FIXADE)
#define _TIF_LOGADE (1<<TIF_LOGADE)
#define _TIF_32BIT_REGS (1<<TIF_32BIT_REGS)
#define _TIF_32BIT_ADDR (1<<TIF_32BIT_ADDR)
#define _TIF_FPUBOUND (1<<TIF_FPUBOUND)
#define _TIF_LOAD_WATCH (1<<TIF_LOAD_WATCH)
#define _TIF_32BIT_FPREGS (1<<TIF_32BIT_FPREGS)
#define _TIF_SYSCALL_TRACEPOINT (1<<TIF_SYSCALL_TRACEPOINT)
#define _TIF_WORK_SYSCALL_ENTRY (_TIF_NOHZ | _TIF_SYSCALL_TRACE | \
_TIF_SYSCALL_AUDIT | \
_TIF_SYSCALL_TRACEPOINT | _TIF_SECCOMP)
/* work to do in syscall_trace_leave() */
#define _TIF_WORK_SYSCALL_EXIT (_TIF_NOHZ | _TIF_SYSCALL_TRACE | \
_TIF_SYSCALL_AUDIT | _TIF_SYSCALL_TRACEPOINT)
/* work to do on interrupt/exception return */
#define _TIF_WORK_MASK \
(_TIF_SIGPENDING | _TIF_NEED_RESCHED | _TIF_NOTIFY_RESUME)
/* work to do on any return to u-space */
#define _TIF_ALLWORK_MASK (_TIF_NOHZ | _TIF_WORK_MASK | \
_TIF_WORK_SYSCALL_EXIT | \
_TIF_SYSCALL_TRACEPOINT)
/*
* We stash processor id into a COP0 register to retrieve it fast
* at kernel exception entry.
*/
#if defined(CONFIG_MIPS_MT_SMTC)
#define SMP_CPUID_REG 2, 2 /* TCBIND */
#define ASM_SMP_CPUID_REG $2, 2
#define SMP_CPUID_PTRSHIFT 19
#elif defined(CONFIG_MIPS_PGD_C0_CONTEXT)
#define SMP_CPUID_REG 20, 0 /* XCONTEXT */
#define ASM_SMP_CPUID_REG $20
#define SMP_CPUID_PTRSHIFT 48
#else
#define SMP_CPUID_REG 4, 0 /* CONTEXT */
#define ASM_SMP_CPUID_REG $4
#define SMP_CPUID_PTRSHIFT 23
#endif
#ifdef CONFIG_64BIT
#define SMP_CPUID_REGSHIFT (SMP_CPUID_PTRSHIFT + 3)
#else
#define SMP_CPUID_REGSHIFT (SMP_CPUID_PTRSHIFT + 2)
#endif
#ifdef CONFIG_MIPS_MT_SMTC
#define ASM_CPUID_MFC0 mfc0
#define UASM_i_CPUID_MFC0 uasm_i_mfc0
#else
#define ASM_CPUID_MFC0 MFC0
#define UASM_i_CPUID_MFC0 UASM_i_MFC0
#endif
#endif /* __KERNEL__ */
#endif /* _ASM_THREAD_INFO_H */
|
137f7df8cead00688524c82360930845396b8a21
|
https://github.com/torvalds/linux
|
index.php
|
php
|
<html>
<head>
<?php include('parts/head.html.part'); ?>
</head>
<body class="vflex">
<div class="header hflex">
<?php include('parts/header.html.part'); ?>
</div>
<div class="center hflex">
<div class="page">
<?php include('pages/' . array_merge(array('p'=>'home'), $_GET)['p'] . '.html.part'); ?>
</div>
<div class="sidebar">
<?php include('parts/sidebar.html.part'); ?>
</div>
</div>
<div class="footer hflex">
<?php include('parts/footer.html.part'); ?>
</div>
</body>
</html>
|
<html>
<head>
<?php include('parts/head.html.part'); ?>
</head>
<body class="vflex">
<div class="header hflex">
<?php include('parts/header.html.part'); ?>
</div>
<div class="center hflex">
<div class="page">
<?php
$page_spec = array_merge(array('p'=>'home'), $_GET)['p'];
if (strpos($page_spec, '/') === false)
{
include("{$_SERVER['DOCUMENT_ROOT']}/pages/$page_spec.html.part");
}
else
{
echo 'no one here but us chickens';
}
?>
</div>
<div class="sidebar">
<?php include('parts/sidebar.html.part'); ?>
</div>
</div>
<div class="footer hflex">
<?php include('parts/footer.html.part'); ?>
</div>
</body>
</html>
|
567bc33e6ed82b0d0179c9add707ac2b257aeaf2
|
https://github.com/soshtolsus/wing-tight
|
main.ts
|
typescript
|
import { NestFactory } from '@nestjs/core';
import { json } from 'express';
import { AppModule } from './app.module';
import * as cookieParser from 'cookie-parser';
import { VersioningType } from '@nestjs/common';
import * as session from 'express-session';
import { emitGQLSchemaFile } from './gql-schema';
async function bootstrap() {
console.log(`Running in production: ${process.env.PRODUCTION}`);
console.log(`Port: ${process.env.PORT}`);
console.log(`Database: ${process.env.DATABASE_URL}`);
const app = await NestFactory.create(AppModule);
app.use(
session({
secret: process.env.SESSION_SECRET,
}),
);
// Increase fil upload limit to 50MB
app.use(
json({
limit: '100mb',
}),
);
if (process.env.PRODUCTION === 'false') {
console.log('Enabling CORS with development settings');
app.enableCors({
origin: process.env.WHITELISTED_ORIGINS.split(','),
credentials: true,
});
} else {
console.log('Enabling CORS with production settings');
app.enableCors({
origin: process.env.WHITELISTED_ORIGINS.split(','),
credentials: true,
});
}
app.enableVersioning({
type: VersioningType.URI,
});
app.use(cookieParser());
await app.listen(process.env.PORT || 3170);
}
if (!process.env.GENERATE_GQL_SCHEMA) {
bootstrap();
} else {
emitGQLSchemaFile();
}
|
import { NestFactory } from '@nestjs/core';
import { json } from 'express';
import { AppModule } from './app.module';
import * as cookieParser from 'cookie-parser';
import { VersioningType } from '@nestjs/common';
import * as session from 'express-session';
import { emitGQLSchemaFile } from './gql-schema';
async function bootstrap() {
console.log(`Running in production: ${process.env.PRODUCTION}`);
console.log(`Port: ${process.env.PORT}`);
const app = await NestFactory.create(AppModule);
app.use(
session({
secret: process.env.SESSION_SECRET,
}),
);
// Increase fil upload limit to 50MB
app.use(
json({
limit: '100mb',
}),
);
if (process.env.PRODUCTION === 'false') {
console.log('Enabling CORS with development settings');
app.enableCors({
origin: process.env.WHITELISTED_ORIGINS.split(','),
credentials: true,
});
} else {
console.log('Enabling CORS with production settings');
app.enableCors({
origin: process.env.WHITELISTED_ORIGINS.split(','),
credentials: true,
});
}
app.enableVersioning({
type: VersioningType.URI,
});
app.use(cookieParser());
await app.listen(process.env.PORT || 3170);
}
if (!process.env.GENERATE_GQL_SCHEMA) {
bootstrap();
} else {
emitGQLSchemaFile();
}
|
15424903ede20b155d764abf4c4f7c2c84c11247
|
https://github.com/hoppscotch/hoppscotch
|
ajax.php
|
php
|
<?php
/**
* Copyright (C) 2020 Laurent Destailleur <eldy@users.sourceforge.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* \file htdocs/public/ticket/ajax/ajax.php
* \brief Ajax component for Ticket.
*/
if (!defined('NOTOKENRENEWAL')) {
define('NOTOKENRENEWAL', '1'); // Disables token renewal
}
if (!defined('NOREQUIREHTML')) {
define('NOREQUIREHTML', '1');
}
if (!defined('NOREQUIREAJAX')) {
define('NOREQUIREAJAX', '1');
}
if (!defined('NOREQUIRESOC')) {
define('NOREQUIRESOC', '1');
}
if (!defined('NOCSRFCHECK')) {
define('NOCSRFCHECK', '1');
}
// Do not check anti CSRF attack test
if (!defined('NOREQUIREMENU')) {
define('NOREQUIREMENU', '1');
}
// If there is no need to load and show top and left menu
if (!defined("NOLOGIN")) {
define("NOLOGIN", '1');
}
if (!defined('NOIPCHECK')) {
define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip
}
if (!defined('NOBROWSERNOTIF')) {
define('NOBROWSERNOTIF', '1');
}
include_once '../../../main.inc.php'; // Load $user and permissions
$action = GETPOST('action', 'aZ09');
$id = GETPOST('id', 'int');
$email = GETPOST('email', 'custom', 0, 'FILTER_VALIDATE_EMAIL');
if (!isModEnabled('ticket')) {
accessforbidden('', 0, 0, 1);
}
if (empty($conf->global->TICKET_CREATE_THIRD_PARTY_WITH_CONTACT_IF_NOT_EXIST)) {
accessforbidden('', 0, 0, 1);
}
/*
* View
*/
top_httphead();
if ($action == 'getContacts') {
$return = array(
'contacts' => array(),
'error' => '',
);
if (!empty($email)) {
require_once DOL_DOCUMENT_ROOT.'/ticket/class/ticket.class.php';
$ticket = new Ticket($db);
$contacts = $ticket->searchContactByEmail($email);
if (is_array($contacts)) {
$return['contacts'] = $contacts;
} else {
$return['error'] = $ticket->errorsToString();
}
}
echo json_encode($return);
exit();
}
|
<?php
/**
* Copyright (C) 2020 Laurent Destailleur <eldy@users.sourceforge.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* \file htdocs/public/ticket/ajax/ajax.php
* \brief Ajax component for Ticket.
*/
if (!defined('NOTOKENRENEWAL')) {
define('NOTOKENRENEWAL', '1'); // Disables token renewal
}
if (!defined('NOREQUIREHTML')) {
define('NOREQUIREHTML', '1');
}
if (!defined('NOREQUIREAJAX')) {
define('NOREQUIREAJAX', '1');
}
if (!defined('NOREQUIRESOC')) {
define('NOREQUIRESOC', '1');
}
if (!defined('NOCSRFCHECK')) {
define('NOCSRFCHECK', '1');
}
// Do not check anti CSRF attack test
if (!defined('NOREQUIREMENU')) {
define('NOREQUIREMENU', '1');
}
// If there is no need to load and show top and left menu
if (!defined("NOLOGIN")) {
define("NOLOGIN", '1');
}
if (!defined('NOIPCHECK')) {
define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip
}
if (!defined('NOBROWSERNOTIF')) {
define('NOBROWSERNOTIF', '1');
}
include_once '../../../main.inc.php'; // Load $user and permissions
$action = GETPOST('action', 'aZ09');
$id = GETPOST('id', 'int');
$email = GETPOST('email', 'custom', 0, FILTER_VALIDATE_EMAIL);
if (!isModEnabled('ticket')) {
accessforbidden('', 0, 0, 1);
}
if (empty($conf->global->TICKET_CREATE_THIRD_PARTY_WITH_CONTACT_IF_NOT_EXIST)) {
accessforbidden('', 0, 0, 1);
}
/*
* View
*/
top_httphead();
if ($action == 'getContacts') {
$return = array(
'contacts' => array(),
'error' => '',
);
if (!empty($email)) {
require_once DOL_DOCUMENT_ROOT.'/ticket/class/ticket.class.php';
$ticket = new Ticket($db);
$contacts = $ticket->searchContactByEmail($email);
if (is_array($contacts)) {
$return['contacts'] = $contacts;
} else {
$return['error'] = $ticket->errorsToString();
}
}
echo json_encode($return);
exit();
}
|
bb7b69ef43673ed403436eac05e0bc31d5033ff7
|
https://github.com/dolibarr/dolibarr
|
api.php
|
php
|
<?php
include "../../includes/stracker/mysql.php";
include "../../includes/stracker/apiHeaders.php";
include "../../includes/stracker/validation.php";
$task = $_GET['task'];
$symbol = $_GET['symbol'];
$startDate = $_GET['startDate'];
$endDate = $_GET['endDate'];
function getHistory($symbol, $startDate, $endDate, $pdo) {
$history = array();
$query = "select date, EOD, MA20, MA50, delta, deltaMA5, deltaMA10, deltaMA20, P0, P1, P2, M1, M2, M3 from $symbol where date >= $startDate and date <= $endDate order by date DESC";
$stmt = $pdo->query($query);
return $stmt->fetchAll(\PDO::FETCH_ASSOC);
}
function getSymbols($pdo) {
$query = "select symbol, name from _symbols ORDER by symbol ASC";
$stmt = $pdo->query($query);
return $stmt->fetchAll(\PDO::FETCH_ASSOC);
}
$db = dbConnect();
if($task == 'history' & areValidDates($startDate, $endDate) & isValidSymbol($symbol) ) {
$data = getHistory($symbol, $startDate, $endDate, $db);
$data = array_reverse($data);
} else if($task == 'symbols' ) {
$data = getSymbols($db);
} else {
$data = '{"err":"no/invalid task defined or required params are not present. (symbol = ['.$symbol.'] and '.(isValidSymbol($symbol) ? 'is valid' : 'is not valid').'). dates are valid: '.(areValidDates($startDate, $endDate) ? 'true' : 'false').'"}';
}
$data = json_encode($data);
header('Content-type: application/json');
print($data);
?>
|
<?php
include "../../includes/stracker/mysql.php";
include "../../includes/stracker/apiHeaders.php";
include "../../includes/stracker/validation.php";
$task = $_GET['task'];
$symbol = $_GET['symbol'];
$startDate = $_GET['startDate'];
$endDate = $_GET['endDate'];
function getHistory($symbol, $startDate, $endDate, $pdo) {
$history = array();
$query = "select date, EOD, MA20, MA50, delta, deltaMA5, deltaMA10, deltaMA20, P0, P1, P2, M1, M2, M3 from $pdo->quote($symbol) where date between $pdo->quote($startDate) and $pdo->quote($endDate) order by date DESC";
$stmt = $pdo->query($query);
return $stmt->fetchAll(\PDO::FETCH_ASSOC);
}
function getSymbols($pdo) {
$query = "select symbol, name from _symbols ORDER by symbol ASC";
$stmt = $pdo->query($query);
return $stmt->fetchAll(\PDO::FETCH_ASSOC);
}
$db = dbConnect();
if($task == 'history' & areValidDates($startDate, $endDate) & isValidSymbol($symbol) ) {
$data = getHistory($symbol, $startDate, $endDate, $db);
$data = array_reverse($data);
} else if($task == 'symbols' ) {
$data = getSymbols($db);
} else {
$data = '{"err":"no/invalid task defined or required params are not present. (symbol = ['.$symbol.'] and '.(isValidSymbol($symbol) ? 'is valid' : 'is not valid').'). dates are valid: '.(areValidDates($startDate, $endDate) ? 'true' : 'false').'"}';
}
$data = json_encode($data);
header('Content-type: application/json');
print($data);
?>
|
63e1b040373ee5b6c7d1e165ecf5ae1603d29e0a
|
https://github.com/visegripped/stracker
|
sys.c
|
c
|
/*
* AArch64-specific system calls implementation
*
* Copyright (C) 2012 ARM Ltd.
* Author: Catalin Marinas <catalin.marinas@arm.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <linux/compiler.h>
#include <linux/errno.h>
#include <linux/fs.h>
#include <linux/mm.h>
#include <linux/export.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/syscalls.h>
asmlinkage long sys_mmap(unsigned long addr, unsigned long len,
unsigned long prot, unsigned long flags,
unsigned long fd, off_t off)
{
if (offset_in_page(off) != 0)
return -EINVAL;
return sys_mmap_pgoff(addr, len, prot, flags, fd, off >> PAGE_SHIFT);
}
/*
* Wrappers to pass the pt_regs argument.
*/
asmlinkage long sys_rt_sigreturn_wrapper(void);
#define sys_rt_sigreturn sys_rt_sigreturn_wrapper
#undef __SYSCALL
#define __SYSCALL(nr, sym) [nr] = sym,
/*
* The sys_call_table array must be 4K aligned to be accessible from
* kernel/entry.S.
*/
void *sys_call_table[__NR_syscalls] __aligned(4096) = {
[0 ... __NR_syscalls - 1] = sys_ni_syscall,
#include <asm/unistd.h>
};
|
/*
* AArch64-specific system calls implementation
*
* Copyright (C) 2012 ARM Ltd.
* Author: Catalin Marinas <catalin.marinas@arm.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <linux/compiler.h>
#include <linux/errno.h>
#include <linux/fs.h>
#include <linux/mm.h>
#include <linux/export.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/syscalls.h>
asmlinkage long sys_mmap(unsigned long addr, unsigned long len,
unsigned long prot, unsigned long flags,
unsigned long fd, off_t off)
{
if (offset_in_page(off) != 0)
return -EINVAL;
return sys_mmap_pgoff(addr, len, prot, flags, fd, off >> PAGE_SHIFT);
}
/*
* Wrappers to pass the pt_regs argument.
*/
asmlinkage long sys_rt_sigreturn_wrapper(void);
#define sys_rt_sigreturn sys_rt_sigreturn_wrapper
#undef __SYSCALL
#define __SYSCALL(nr, sym) [nr] = sym,
/*
* The sys_call_table array must be 4K aligned to be accessible from
* kernel/entry.S.
*/
void * const sys_call_table[__NR_syscalls] __aligned(4096) = {
[0 ... __NR_syscalls - 1] = sys_ni_syscall,
#include <asm/unistd.h>
};
|
c623b33b4e9599c6ac5076f7db7369eb9869aa04
|
https://github.com/torvalds/linux
|
ConditionsController.php
|
php
|
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\controllers;
use Craft;
use craft\base\conditions\ConditionInterface;
use craft\base\conditions\ConditionRuleInterface;
use craft\helpers\ArrayHelper;
use craft\helpers\Component;
use craft\helpers\Json;
use craft\web\Controller;
use Illuminate\Support\Collection;
/**
* The ConditionsController class is a controller that handles various condition related actions including managing
* rendering of the condition, and adding and removing rules, and returning the result.
*
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 4.0.0
*/
class ConditionsController extends Controller
{
/**
* @var ConditionInterface
*/
private ConditionInterface $_condition;
/**
* @inheritdoc
*/
public function beforeAction($action): bool
{
if (!parent::beforeAction($action)) {
return false;
}
$this->requireCpRequest();
$baseConfig = Json::decodeIfJson($this->request->getBodyParam('config'));
$config = Component::cleanseConfig($this->request->getBodyParam($baseConfig['name']));
$newRuleType = ArrayHelper::remove($config, 'new-rule-type');
$conditionsService = Craft::$app->getConditions();
$this->_condition = $conditionsService->createCondition($config);
Craft::configure($this->_condition, $baseConfig);
if ($newRuleType) {
$newRuleType = Json::decodeIfJson($newRuleType);
$rule = $conditionsService->createConditionRule($newRuleType);
$rule->setAutofocus();
$this->_condition->addConditionRule($rule);
}
return true;
}
/**
* @return string
*/
public function actionRender(): string
{
return $this->_condition->getBuilderInnerHtml();
}
/**
* @return string
* @deprecated in 4.1.0
*/
public function actionAddRule(): string
{
/** @var ConditionRuleInterface|null $rule */
$rule = Collection::make($this->_condition->getSelectableConditionRules())
->sortBy(fn(ConditionRuleInterface $rule) => $rule->getLabel())
->first();
if ($rule) {
$rule->setAutofocus();
$this->_condition->addConditionRule($rule);
}
return $this->_condition->getBuilderInnerHtml();
}
/**
* @return string
*/
public function actionRemoveRule(): string
{
$ruleUid = $this->request->getRequiredBodyParam('uid');
$conditionRules = Collection::make($this->_condition->getConditionRules())
->filter(fn(ConditionRuleInterface $rule) => $rule->uid !== $ruleUid)
->all();
$this->_condition->setConditionRules($conditionRules);
return $this->_condition->getBuilderInnerHtml(true);
}
}
|
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\controllers;
use Craft;
use craft\base\conditions\ConditionInterface;
use craft\base\conditions\ConditionRuleInterface;
use craft\helpers\ArrayHelper;
use craft\helpers\Component;
use craft\helpers\Json;
use craft\web\Controller;
use Illuminate\Support\Collection;
/**
* The ConditionsController class is a controller that handles various condition related actions including managing
* rendering of the condition, and adding and removing rules, and returning the result.
*
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 4.0.0
*/
class ConditionsController extends Controller
{
/**
* @var ConditionInterface
*/
private ConditionInterface $_condition;
/**
* @inheritdoc
*/
public function beforeAction($action): bool
{
if (!parent::beforeAction($action)) {
return false;
}
$this->requireCpRequest();
$baseConfig = Component::cleanseConfig(Json::decodeIfJson($this->request->getBodyParam('config')));
$config = Component::cleanseConfig($this->request->getBodyParam($baseConfig['name']));
$newRuleType = ArrayHelper::remove($config, 'new-rule-type');
$conditionsService = Craft::$app->getConditions();
$this->_condition = $conditionsService->createCondition($config);
Craft::configure($this->_condition, $baseConfig);
if ($newRuleType) {
$newRuleType = Json::decodeIfJson($newRuleType);
$rule = $conditionsService->createConditionRule($newRuleType);
$rule->setAutofocus();
$this->_condition->addConditionRule($rule);
}
return true;
}
/**
* @return string
*/
public function actionRender(): string
{
return $this->_condition->getBuilderInnerHtml();
}
/**
* @return string
* @deprecated in 4.1.0
*/
public function actionAddRule(): string
{
/** @var ConditionRuleInterface|null $rule */
$rule = Collection::make($this->_condition->getSelectableConditionRules())
->sortBy(fn(ConditionRuleInterface $rule) => $rule->getLabel())
->first();
if ($rule) {
$rule->setAutofocus();
$this->_condition->addConditionRule($rule);
}
return $this->_condition->getBuilderInnerHtml();
}
/**
* @return string
*/
public function actionRemoveRule(): string
{
$ruleUid = $this->request->getRequiredBodyParam('uid');
$conditionRules = Collection::make($this->_condition->getConditionRules())
->filter(fn(ConditionRuleInterface $rule) => $rule->uid !== $ruleUid)
->all();
$this->_condition->setConditionRules($conditionRules);
return $this->_condition->getBuilderInnerHtml(true);
}
}
|
a270b928f3d34ad3bd953b81c304424edd57355e
|
https://github.com/craftcms/cms
|
XWikiCommentsDocumentInitializer.java
|
java
|
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* 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 com.xpn.xwiki.internal.mandatory;
import javax.inject.Named;
import javax.inject.Singleton;
import org.xwiki.component.annotation.Component;
import org.xwiki.model.reference.LocalDocumentReference;
import org.xwiki.model.reference.RegexEntityReference;
import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.objects.BaseObjectReference;
import com.xpn.xwiki.objects.classes.BaseClass;
import com.xpn.xwiki.objects.classes.TextAreaClass;
/**
* Update XWiki.XWikiComments document with all required informations.
*
* @version $Id$
* @since 4.3M1
*/
@Component
@Named(XWikiCommentsDocumentInitializer.LOCAL_REFERENCE_STRING)
@Singleton
public class XWikiCommentsDocumentInitializer extends AbstractCommentsDocumentInitializer
{
/**
* The name of the initialized document.
*
* @since 9.4RC1
*/
public static final String NAME = "XWikiComments";
/**
* The local reference of the initialized document as String.
*
* @since 9.4RC1
*/
public static final String LOCAL_REFERENCE_STRING = XWiki.SYSTEM_SPACE + '.' + NAME;
/**
* The local reference of the initialized document as String.
*
* @since 9.4RC1
*/
public static final LocalDocumentReference LOCAL_REFERENCE = new LocalDocumentReference(XWiki.SYSTEM_SPACE, NAME);
/**
* A regex to match any object reference with initialized class.
*
* @since 9.4RC1
*/
public static final RegexEntityReference OBJECT_REFERENCE = BaseObjectReference.any(LOCAL_REFERENCE_STRING);
/**
* Default constructor.
*/
public XWikiCommentsDocumentInitializer()
{
super(LOCAL_REFERENCE);
}
@Override
protected void createClass(BaseClass xclass)
{
super.createClass(xclass);
xclass.addTextAreaField("highlight", "Highlighted Text", 40, 2);
xclass.addNumberField("replyto", "Reply To", 5, "integer");
String commentPropertyName = "comment";
xclass.addTextAreaField(commentPropertyName, "Comment", 40, 5);
// FIXME: Ensure that the comment text editor is set to its default value after an upgrade. This should be
// handled in a cleaner way in BaseClass#addTextAreaField. See: https://jira.xwiki.org/browse/XWIKI-17605
TextAreaClass comment = (TextAreaClass) xclass.getField(commentPropertyName);
comment.setEditor((String) null);
}
}
|
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* 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 com.xpn.xwiki.internal.mandatory;
import javax.inject.Named;
import javax.inject.Singleton;
import org.xwiki.component.annotation.Component;
import org.xwiki.model.reference.LocalDocumentReference;
import org.xwiki.model.reference.RegexEntityReference;
import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.objects.BaseObjectReference;
import com.xpn.xwiki.objects.classes.BaseClass;
import com.xpn.xwiki.objects.classes.TextAreaClass;
/**
* Update XWiki.XWikiComments document with all required informations.
*
* @version $Id$
* @since 4.3M1
*/
@Component
@Named(XWikiCommentsDocumentInitializer.LOCAL_REFERENCE_STRING)
@Singleton
public class XWikiCommentsDocumentInitializer extends AbstractCommentsDocumentInitializer
{
/**
* The name of the initialized document.
*
* @since 9.4RC1
*/
public static final String NAME = "XWikiComments";
/**
* The local reference of the initialized document as String.
*
* @since 9.4RC1
*/
public static final String LOCAL_REFERENCE_STRING = XWiki.SYSTEM_SPACE + '.' + NAME;
/**
* The local reference of the initialized document as String.
*
* @since 9.4RC1
*/
public static final LocalDocumentReference LOCAL_REFERENCE = new LocalDocumentReference(XWiki.SYSTEM_SPACE, NAME);
/**
* A regex to match any object reference with initialized class.
*
* @since 9.4RC1
*/
public static final RegexEntityReference OBJECT_REFERENCE = BaseObjectReference.any(LOCAL_REFERENCE_STRING);
/**
* Default constructor.
*/
public XWikiCommentsDocumentInitializer()
{
super(LOCAL_REFERENCE);
}
@Override
protected void createClass(BaseClass xclass)
{
super.createClass(xclass);
xclass.addTextAreaField("highlight", "Highlighted Text", 40, 2);
xclass.addNumberField("replyto", "Reply To", 5, "integer");
String commentPropertyName = "comment";
xclass.addTextAreaField(commentPropertyName, "Comment", 40, 5, true);
// FIXME: Ensure that the comment text editor is set to its default value after an upgrade. This should be
// handled in a cleaner way in BaseClass#addTextAreaField. See: https://jira.xwiki.org/browse/XWIKI-17605
TextAreaClass comment = (TextAreaClass) xclass.getField(commentPropertyName);
comment.setEditor((String) null);
}
}
|
d87d7bfd8db18c20d3264f98c6deefeae93b99f7
|
https://github.com/xwiki/xwiki-platform
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.