text:
/* $NetBSD: kauth.h,v 1.71 2013/03/18 19:35:46 plunky Exp $ */

/*-
 * Copyright (c) 2005, 2006 Elad Efrat <elad@NetBSD.org>
 * 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. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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.
 */

/*
 * This is based on Apple TN2127, available online at
 * http://developer.apple.com/technotes/tn2005/tn2127.html
 */

#ifndef _SYS_KAUTH_H_
#define	_SYS_KAUTH_H_

#include <secmodel/secmodel.h> /* for secmodel_t type */
#include <sys/stat.h> /* for modes */

struct uucred;
struct ki_ucred;
struct ki_pcred;
struct proc;
struct tty;
struct vnode;
struct cwdinfo;

/* Types. */
typedef struct kauth_scope     *kauth_scope_t;
typedef struct kauth_listener  *kauth_listener_t;
typedef uint32_t		kauth_action_t;
typedef int (*kauth_scope_callback_t)(kauth_cred_t, kauth_action_t,
				      void *, void *, void *, void *, void *);
typedef	struct kauth_key       *kauth_key_t;

/*
 * Possible return values for a listener.
 */
#define	KAUTH_RESULT_ALLOW	0	/* allow access */
#define	KAUTH_RESULT_DENY	1	/* deny access */
#define	KAUTH_RESULT_DEFER	2	/* let others decide */

/*
 * Scopes.
 */
#define	KAUTH_SCOPE_GENERIC	"org.netbsd.kauth.generic"
#define	KAUTH_SCOPE_SYSTEM	"org.netbsd.kauth.system"
#define	KAUTH_SCOPE_PROCESS	"org.netbsd.kauth.process"
#define	KAUTH_SCOPE_NETWORK	"org.netbsd.kauth.network"
#define	KAUTH_SCOPE_MACHDEP	"org.netbsd.kauth.machdep"
#define	KAUTH_SCOPE_DEVICE	"org.netbsd.kauth.device"
#define	KAUTH_SCOPE_CRED	"org.netbsd.kauth.cred"
#define	KAUTH_SCOPE_VNODE	"org.netbsd.kauth.vnode"

/*
 * Generic scope - actions.
 */
enum {
	KAUTH_GENERIC_UNUSED1=1,
	KAUTH_GENERIC_ISSUSER,
};

/*
 * System scope - actions.
 */
enum {
	KAUTH_SYSTEM_ACCOUNTING=1,
	KAUTH_SYSTEM_CHROOT,
	KAUTH_SYSTEM_CHSYSFLAGS,
	KAUTH_SYSTEM_CPU,
	KAUTH_SYSTEM_DEBUG,
	KAUTH_SYSTEM_FILEHANDLE,
	KAUTH_SYSTEM_MKNOD,
	KAUTH_SYSTEM_MOUNT,
	KAUTH_SYSTEM_PSET,
	KAUTH_SYSTEM_REBOOT,
	KAUTH_SYSTEM_SETIDCORE,
	KAUTH_SYSTEM_SWAPCTL,
	KAUTH_SYSTEM_SYSCTL,
	KAUTH_SYSTEM_TIME,
	KAUTH_SYSTEM_MODULE,
	KAUTH_SYSTEM_FS_RESERVEDSPACE,
	KAUTH_SYSTEM_FS_QUOTA,
	KAUTH_SYSTEM_SEMAPHORE,
	KAUTH_SYSTEM_SYSVIPC,
	KAUTH_SYSTEM_MQUEUE,
	KAUTH_SYSTEM_VERIEXEC,
	KAUTH_SYSTEM_DEVMAPPER,
	KAUTH_SYSTEM_MAP_VA_ZERO,
	KAUTH_SYSTEM_LFS,
	KAUTH_SYSTEM_FS_EXTATTR,
	KAUTH_SYSTEM_FS_SNAPSHOT,
};

/*
 * System scope - sub-actions.
 */
enum kauth_system_req {
	KAUTH_REQ_SYSTEM_CHROOT_CHROOT=1,
	KAUTH_REQ_SYSTEM_CHROOT_FCHROOT,
	KAUTH_REQ_SYSTEM_CPU_SETSTATE,
	KAUTH_REQ_SYSTEM_DEBUG_IPKDB,
	KAUTH_REQ_SYSTEM_MOUNT_GET,
	KAUTH_REQ_SYSTEM_MOUNT_NEW,
	KAUTH_REQ_SYSTEM_MOUNT_UNMOUNT,
	KAUTH_REQ_SYSTEM_MOUNT_UPDATE,
	KAUTH_REQ_SYSTEM_PSET_ASSIGN,
	KAUTH_REQ_SYSTEM_PSET_BIND,
	KAUTH_REQ_SYSTEM_PSET_CREATE,
	KAUTH_REQ_SYSTEM_PSET_DESTROY,
	KAUTH_REQ_SYSTEM_SYSCTL_ADD,
	KAUTH_REQ_SYSTEM_SYSCTL_DELETE,
	KAUTH_REQ_SYSTEM_SYSCTL_DESC,
	KAUTH_REQ_SYSTEM_SYSCTL_MODIFY,
	KAUTH_REQ_SYSTEM_SYSCTL_PRVT,
	KAUTH_REQ_SYSTEM_TIME_ADJTIME,
	KAUTH_REQ_SYSTEM_TIME_NTPADJTIME,
	KAUTH_REQ_SYSTEM_TIME_RTCOFFSET,
	KAUTH_REQ_SYSTEM_TIME_SYSTEM,
	KAUTH_REQ_SYSTEM_TIME_TIMECOUNTERS,
	KAUTH_REQ_SYSTEM_FS_QUOTA_GET,
	KAUTH_REQ_SYSTEM_FS_QUOTA_MANAGE,
	KAUTH_REQ_SYSTEM_FS_QUOTA_NOLIMIT,
	KAUTH_REQ_SYSTEM_FS_QUOTA_ONOFF,
	KAUTH_REQ_SYSTEM_SYSVIPC_BYPASS,
	KAUTH_REQ_SYSTEM_SYSVIPC_SHM_LOCK,
	KAUTH_REQ_SYSTEM_SYSVIPC_SHM_UNLOCK,
	KAUTH_REQ_SYSTEM_SYSVIPC_MSGQ_OVERSIZE,
	KAUTH_REQ_SYSTEM_VERIEXEC_ACCESS,
	KAUTH_REQ_SYSTEM_VERIEXEC_MODIFY,
	KAUTH_REQ_SYSTEM_LFS_MARKV,
	KAUTH_REQ_SYSTEM_LFS_BMAPV,
	KAUTH_REQ_SYSTEM_LFS_SEGCLEAN,
	KAUTH_REQ_SYSTEM_LFS_SEGWAIT,
	KAUTH_REQ_SYSTEM_LFS_FCNTL,
	KAUTH_REQ_SYSTEM_MOUNT_UMAP,
	KAUTH_REQ_SYSTEM_MOUNT_DEVICE,
};

/*
 * Process scope - actions.
 */
enum {
	KAUTH_PROCESS_CANSEE=1,
	KAUTH_PROCESS_CORENAME,
	KAUTH_PROCESS_FORK,
	KAUTH_PROCESS_KEVENT_FILTER,
	KAUTH_PROCESS_KTRACE,
	KAUTH_PROCESS_NICE,
	KAUTH_PROCESS_PROCFS,
	KAUTH_PROCESS_PTRACE,
	KAUTH_PROCESS_RLIMIT,
	KAUTH_PROCESS_SCHEDULER_GETAFFINITY,
	KAUTH_PROCESS_SCHEDULER_SETAFFINITY,
	KAUTH_PROCESS_SCHEDULER_GETPARAM,
	KAUTH_PROCESS_SCHEDULER_SETPARAM,
	KAUTH_PROCESS_SETID,
	KAUTH_PROCESS_SIGNAL,
	KAUTH_PROCESS_STOPFLAG
};

/*
 * Process scope - sub-actions.
 */
enum kauth_process_req {
	KAUTH_REQ_PROCESS_CANSEE_ARGS=1,
	KAUTH_REQ_PROCESS_CANSEE_ENTRY,
	KAUTH_REQ_PROCESS_CANSEE_ENV,
	KAUTH_REQ_PROCESS_CANSEE_OPENFILES,
	KAUTH_REQ_PROCESS_CORENAME_GET,
	KAUTH_REQ_PROCESS_CORENAME_SET,
	KAUTH_REQ_PROCESS_KTRACE_PERSISTENT,
	KAUTH_REQ_PROCESS_PROCFS_CTL,
	KAUTH_REQ_PROCESS_PROCFS_READ,
	KAUTH_REQ_PROCESS_PROCFS_RW,
	KAUTH_REQ_PROCESS_PROCFS_WRITE,
	KAUTH_REQ_PROCESS_RLIMIT_GET,
	KAUTH_REQ_PROCESS_RLIMIT_SET,
	KAUTH_REQ_PROCESS_RLIMIT_BYPASS,
};

/*
 * Network scope - actions.
 */
enum {
	KAUTH_NETWORK_ALTQ=1,
	KAUTH_NETWORK_BIND,
	KAUTH_NETWORK_FIREWALL,
	KAUTH_NETWORK_INTERFACE,
	KAUTH_NETWORK_FORWSRCRT,
	KAUTH_NETWORK_NFS,
	KAUTH_NETWORK_ROUTE,
	KAUTH_NETWORK_SOCKET,
	KAUTH_NETWORK_INTERFACE_PPP,
	KAUTH_NETWORK_INTERFACE_SLIP,
	KAUTH_NETWORK_INTERFACE_STRIP,
	KAUTH_NETWORK_INTERFACE_TUN,
	KAUTH_NETWORK_INTERFACE_BRIDGE,
	KAUTH_NETWORK_IPSEC,
	KAUTH_NETWORK_INTERFACE_PVC,
	KAUTH_NETWORK_IPV6,
	KAUTH_NETWORK_SMB,
};

/*
 * Network scope - sub-actions.
 */
enum kauth_network_req {
	KAUTH_REQ_NETWORK_ALTQ_AFMAP=1,
	KAUTH_REQ_NETWORK_ALTQ_BLUE,
	KAUTH_REQ_NETWORK_ALTQ_CBQ,
	KAUTH_REQ_NETWORK_ALTQ_CDNR,
	KAUTH_REQ_NETWORK_ALTQ_CONF,
	KAUTH_REQ_NETWORK_ALTQ_FIFOQ,
	KAUTH_REQ_NETWORK_ALTQ_HFSC,
	KAUTH_REQ_NETWORK_ALTQ_JOBS,
	KAUTH_REQ_NETWORK_ALTQ_PRIQ,
	KAUTH_REQ_NETWORK_ALTQ_RED,
	KAUTH_REQ_NETWORK_ALTQ_RIO,
	KAUTH_REQ_NETWORK_ALTQ_WFQ,
	KAUTH_REQ_NETWORK_BIND_PORT,
	KAUTH_REQ_NETWORK_BIND_PRIVPORT,
	KAUTH_REQ_NETWORK_FIREWALL_FW,
	KAUTH_REQ_NETWORK_FIREWALL_NAT,
	KAUTH_REQ_NETWORK_INTERFACE_GET,
	KAUTH_REQ_NETWORK_INTERFACE_GETPRIV,
	KAUTH_REQ_NETWORK_INTERFACE_SET,
	KAUTH_REQ_NETWORK_INTERFACE_SETPRIV,
	KAUTH_REQ_NETWORK_NFS_EXPORT,
	KAUTH_REQ_NETWORK_NFS_SVC,
	KAUTH_REQ_NETWORK_SOCKET_OPEN,
	KAUTH_REQ_NETWORK_SOCKET_RAWSOCK,
	KAUTH_REQ_NETWORK_SOCKET_CANSEE,
	KAUTH_REQ_NETWORK_SOCKET_DROP,
	KAUTH_REQ_NETWORK_SOCKET_SETPRIV,
	KAUTH_REQ_NETWORK_INTERFACE_PPP_ADD,
	KAUTH_REQ_NETWORK_INTERFACE_SLIP_ADD,
	KAUTH_REQ_NETWORK_INTERFACE_STRIP_ADD,
	KAUTH_REQ_NETWORK_INTERFACE_TUN_ADD,
	KAUTH_REQ_NETWORK_IPV6_HOPBYHOP,
	KAUTH_REQ_NETWORK_INTERFACE_BRIDGE_GETPRIV,
	KAUTH_REQ_NETWORK_INTERFACE_BRIDGE_SETPRIV,
	KAUTH_REQ_NETWORK_IPSEC_BYPASS,
	KAUTH_REQ_NETWORK_IPV6_JOIN_MULTICAST,
	KAUTH_REQ_NETWORK_INTERFACE_PVC_ADD,
	KAUTH_REQ_NETWORK_SMB_SHARE_ACCESS,
	KAUTH_REQ_NETWORK_SMB_SHARE_CREATE,
	KAUTH_REQ_NETWORK_SMB_VC_ACCESS,
	KAUTH_REQ_NETWORK_SMB_VC_CREATE,
	KAUTH_REQ_NETWORK_INTERFACE_FIRMWARE,
};

/*
 * Machdep scope - actions.
 */
enum {
	KAUTH_MACHDEP_CACHEFLUSH=1,
	KAUTH_MACHDEP_CPU_UCODE_APPLY,
	KAUTH_MACHDEP_IOPERM_GET,
	KAUTH_MACHDEP_IOPERM_SET,
	KAUTH_MACHDEP_IOPL,
	KAUTH_MACHDEP_LDT_GET,
	KAUTH_MACHDEP_LDT_SET,
	KAUTH_MACHDEP_MTRR_GET,
	KAUTH_MACHDEP_MTRR_SET,
	KAUTH_MACHDEP_NVRAM,
	KAUTH_MACHDEP_UNMANAGEDMEM,
	KAUTH_MACHDEP_PXG,
};

/*
 * Device scope - actions.
 */
enum {
	KAUTH_DEVICE_TTY_OPEN=1,
	KAUTH_DEVICE_TTY_PRIVSET,
	KAUTH_DEVICE_TTY_STI,
	KAUTH_DEVICE_RAWIO_SPEC,
	KAUTH_DEVICE_RAWIO_PASSTHRU,
	KAUTH_DEVICE_BLUETOOTH_SETPRIV,
	KAUTH_DEVICE_RND_ADDDATA,
	KAUTH_DEVICE_RND_ADDDATA_ESTIMATE,
	KAUTH_DEVICE_RND_GETPRIV,
	KAUTH_DEVICE_RND_SETPRIV,
	KAUTH_DEVICE_BLUETOOTH_BCSP,
	KAUTH_DEVICE_BLUETOOTH_BTUART,
	KAUTH_DEVICE_GPIO_PINSET,
	KAUTH_DEVICE_BLUETOOTH_SEND,
	KAUTH_DEVICE_BLUETOOTH_RECV,
	KAUTH_DEVICE_TTY_VIRTUAL,
	KAUTH_DEVICE_WSCONS_KEYBOARD_BELL,
	KAUTH_DEVICE_WSCONS_KEYBOARD_KEYREPEAT,
};

/*
 * Device scope - sub-actions.
 */
enum kauth_device_req {
	KAUTH_REQ_DEVICE_RAWIO_SPEC_READ=1,
	KAUTH_REQ_DEVICE_RAWIO_SPEC_WRITE,
	KAUTH_REQ_DEVICE_RAWIO_SPEC_RW,
	KAUTH_REQ_DEVICE_BLUETOOTH_BCSP_ADD,
	KAUTH_REQ_DEVICE_BLUETOOTH_BTUART_ADD,
};

/*
 * Credentials scope - actions.
 */
enum {
	KAUTH_CRED_INIT=1,
	KAUTH_CRED_FORK,
	KAUTH_CRED_COPY,
	KAUTH_CRED_FREE,
	KAUTH_CRED_CHROOT
};

/*
 * Vnode scope - action bits.
 */
#define	KAUTH_VNODE_READ_DATA		(1U << 0)
#define	KAUTH_VNODE_LIST_DIRECTORY	KAUTH_VNODE_READ_DATA
#define	KAUTH_VNODE_WRITE_DATA		(1U << 1)
#define	KAUTH_VNODE_ADD_FILE		KAUTH_VNODE_WRITE_DATA
#define	KAUTH_VNODE_EXECUTE		(1U << 2)
#define	KAUTH_VNODE_SEARCH		KAUTH_VNODE_EXECUTE
#define	KAUTH_VNODE_DELETE		(1U << 3)
#define	KAUTH_VNODE_APPEND_DATA		(1U << 4)
#define	KAUTH_VNODE_ADD_SUBDIRECTORY	KAUTH_VNODE_APPEND_DATA
#define	KAUTH_VNODE_READ_TIMES		(1U << 5)
#define	KAUTH_VNODE_WRITE_TIMES		(1U << 6)
#define	KAUTH_VNODE_READ_FLAGS		(1U << 7)
#define	KAUTH_VNODE_WRITE_FLAGS		(1U << 8)
#define	KAUTH_VNODE_READ_SYSFLAGS	(1U << 9)
#define	KAUTH_VNODE_WRITE_SYSFLAGS	(1U << 10)
#define	KAUTH_VNODE_RENAME		(1U << 11)
#define	KAUTH_VNODE_CHANGE_OWNERSHIP	(1U << 12)
#define	KAUTH_VNODE_READ_SECURITY	(1U << 13)
#define	KAUTH_VNODE_WRITE_SECURITY	(1U << 14)
#define	KAUTH_VNODE_READ_ATTRIBUTES	(1U << 15)
#define	KAUTH_VNODE_WRITE_ATTRIBUTES	(1U << 16)
#define	KAUTH_VNODE_READ_EXTATTRIBUTES	(1U << 17)
#define	KAUTH_VNODE_WRITE_EXTATTRIBUTES	(1U << 18)
#define	KAUTH_VNODE_RETAIN_SUID		(1U << 19)
#define	KAUTH_VNODE_RETAIN_SGID		(1U << 20)
#define	KAUTH_VNODE_REVOKE		(1U << 21)

#define	KAUTH_VNODE_IS_EXEC		(1U << 29)
#define	KAUTH_VNODE_HAS_SYSFLAGS	(1U << 30)
#define	KAUTH_VNODE_ACCESS		(1U << 31)

/*
 * This is a special fs_decision indication that can be used by file-systems
 * that don't support decision-before-action to tell kauth(9) it can only
 * short-circuit the operation beforehand.
 */
#define	KAUTH_VNODE_REMOTEFS		(-1)

/*
 * Device scope, passthru request - identifiers.
 */
#define	KAUTH_REQ_DEVICE_RAWIO_PASSTHRU_READ		0x00000001
#define	KAUTH_REQ_DEVICE_RAWIO_PASSTHRU_WRITE		0x00000002
#define	KAUTH_REQ_DEVICE_RAWIO_PASSTHRU_READCONF	0x00000004
#define	KAUTH_REQ_DEVICE_RAWIO_PASSTHRU_WRITECONF	0x00000008
#define	KAUTH_REQ_DEVICE_RAWIO_PASSTHRU_ALL		0x0000000F

#define NOCRED ((kauth_cred_t)-1)	/* no credential available */
#define FSCRED ((kauth_cred_t)-2)	/* filesystem credential */

/* Macro to help passing arguments to authorization wrappers. */
#define	KAUTH_ARG(arg)	((void *)(unsigned long)(arg))

/*
 * A file-system object is determined to be able to execute if it's a
 * directory or if the execute bit is present in any of the
 * owner/group/other modes.
 *
 * This helper macro is intended to be used in order to implement a
 * policy that maintains the semantics of "a privileged user can enter
 * directory, and can execute any file, but only if the file is actually
 * executable."
 */
#define	FS_OBJECT_CAN_EXEC(vtype, mode)	(((vtype) == VDIR) ||		\
					 ((mode) &			\
					  (S_IXUSR|S_IXGRP|S_IXOTH)))

/*
 * Prototypes.
 */
void kauth_init(void);
kauth_scope_t kauth_register_scope(const char *, kauth_scope_callback_t, void *);
void kauth_deregister_scope(kauth_scope_t);
kauth_listener_t kauth_listen_scope(const char *, kauth_scope_callback_t, void *);
void kauth_unlisten_scope(kauth_listener_t);
int kauth_authorize_action(kauth_scope_t, kauth_cred_t, kauth_action_t, void *,
    void *, void *, void *);

/* Authorization wrappers. */
int kauth_authorize_generic(kauth_cred_t, kauth_action_t, void *);
int kauth_authorize_system(kauth_cred_t, kauth_action_t, enum kauth_system_req,
    void *, void *, void *);
int kauth_authorize_process(kauth_cred_t, kauth_action_t, struct proc *,
    void *, void *, void *);
int kauth_authorize_network(kauth_cred_t, kauth_action_t,
    enum kauth_network_req, void *, void *, void *);
int kauth_authorize_machdep(kauth_cred_t, kauth_action_t,
    void *, void *, void *, void *);
int kauth_authorize_device(kauth_cred_t, kauth_action_t,
    void *, void *, void *, void *);
int kauth_authorize_device_tty(kauth_cred_t, kauth_action_t, struct tty *);
int kauth_authorize_device_spec(kauth_cred_t, enum kauth_device_req,
    struct vnode *);
int kauth_authorize_device_passthru(kauth_cred_t, dev_t, u_long, void *);
int kauth_authorize_vnode(kauth_cred_t, kauth_action_t, struct vnode *,
    struct vnode *, int);

/* Kauth credentials management routines. */
kauth_cred_t kauth_cred_alloc(void);
void kauth_cred_free(kauth_cred_t);
void kauth_cred_clone(kauth_cred_t, kauth_cred_t);
kauth_cred_t kauth_cred_dup(kauth_cred_t);
kauth_cred_t kauth_cred_copy(kauth_cred_t);

uid_t kauth_cred_getuid(kauth_cred_t);
uid_t kauth_cred_geteuid(kauth_cred_t);
uid_t kauth_cred_getsvuid(kauth_cred_t);
gid_t kauth_cred_getgid(kauth_cred_t);
gid_t kauth_cred_getegid(kauth_cred_t);
gid_t kauth_cred_getsvgid(kauth_cred_t);
int kauth_cred_ismember_gid(kauth_cred_t, gid_t, int *);
u_int kauth_cred_ngroups(kauth_cred_t);
gid_t kauth_cred_group(kauth_cred_t, u_int);

void kauth_cred_setuid(kauth_cred_t, uid_t);
void kauth_cred_seteuid(kauth_cred_t, uid_t);
void kauth_cred_setsvuid(kauth_cred_t, uid_t);
void kauth_cred_setgid(kauth_cred_t, gid_t);
void kauth_cred_setegid(kauth_cred_t, gid_t);
void kauth_cred_setsvgid(kauth_cred_t, gid_t);

void kauth_cred_hold(kauth_cred_t);
u_int kauth_cred_getrefcnt(kauth_cred_t);

int kauth_cred_setgroups(kauth_cred_t, const gid_t *, size_t, uid_t,
    enum uio_seg);
int kauth_cred_getgroups(kauth_cred_t, gid_t *, size_t, enum uio_seg);

/* This is for sys_setgroups() */
int kauth_proc_setgroups(struct lwp *, kauth_cred_t);

int kauth_register_key(secmodel_t, kauth_key_t *);
int kauth_deregister_key(kauth_key_t);
void kauth_cred_setdata(kauth_cred_t, kauth_key_t, void *);
void *kauth_cred_getdata(kauth_cred_t, kauth_key_t);

int kauth_cred_uidmatch(kauth_cred_t, kauth_cred_t);
void kauth_uucred_to_cred(kauth_cred_t, const struct uucred *);
void kauth_cred_to_uucred(struct uucred *, const kauth_cred_t);
int kauth_cred_uucmp(kauth_cred_t, const struct uucred *);
void kauth_cred_toucred(kauth_cred_t, struct ki_ucred *);
void kauth_cred_topcred(kauth_cred_t, struct ki_pcred *);

kauth_action_t kauth_mode_to_action(mode_t);
kauth_action_t kauth_extattr_action(mode_t);

#define KAUTH_ACCESS_ACTION(access_mode, vn_vtype, file_mode)	\
	(kauth_mode_to_action(access_mode) |			\
	(FS_OBJECT_CAN_EXEC(vn_vtype, file_mode) ? KAUTH_VNODE_IS_EXEC : 0))

kauth_cred_t kauth_cred_get(void);

void kauth_proc_fork(struct proc *, struct proc *);
void kauth_proc_chroot(kauth_cred_t cred, struct cwdinfo *cwdi);

#endif	/* !_SYS_KAUTH_H_ */


text:
package com.intellij.openapi.editor.ex;

import com.intellij.openapi.editor.FoldRegion;
import org.jetbrains.annotations.NotNull;

/**
 * Defines common contract for clients interested in folding processing.
 *
 * @author Denis Zhdanov
 * @since Sep 8, 2010 11:20:28 AM
 */
public interface FoldingListener {

  /**
   * Informs that {@code 'collapsed'} state of given fold region is just changed.
   *

   * Note: listener should delay fold region state processing until {@link #onFoldProcessingEnd()} is called.
   * I.e. folding model may return inconsistent data between current moment and {@link #onFoldProcessingEnd()}.
   *
   * @param region    fold region that is just collapsed or expanded
   */
  void onFoldRegionStateChange(@NotNull FoldRegion region);

  /**
   * Informs that fold processing is done.
   */
  void onFoldProcessingEnd();
}

redpajama_set_name: RedPajamaGithub


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.execution.scheduler;

import com.facebook.presto.execution.RemoteTask;
import com.facebook.presto.execution.SqlStageExecution;
import com.facebook.presto.execution.StageExecutionState;
import com.facebook.presto.execution.buffer.OutputBuffers;
import com.facebook.presto.sql.planner.PartitioningHandle;
import com.facebook.presto.sql.planner.plan.PlanFragmentId;
import com.google.common.primitives.Ints;

import java.util.List;
import java.util.Set;

import static com.facebook.presto.sql.planner.SystemPartitioningHandle.FIXED_BROADCAST_DISTRIBUTION;
import static com.facebook.presto.sql.planner.SystemPartitioningHandle.SCALED_WRITER_DISTRIBUTION;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableSet.toImmutableSet;

public class StageLinkage
{
    private final PlanFragmentId currentStageFragmentId;
    private final ExchangeLocationsConsumer parent;
    private final Set<OutputBufferManager> childOutputBufferManagers;

    public StageLinkage(PlanFragmentId fragmentId, ExchangeLocationsConsumer parent, Set<SqlStageExecution> children)
    {
        this.currentStageFragmentId = fragmentId;
        this.parent = parent;
        this.childOutputBufferManagers = children.stream()
                .map(childStage -> {
                    PartitioningHandle partitioningHandle = childStage.getFragment().getPartitioningScheme().getPartitioning().getHandle();
                    if (partitioningHandle.equals(FIXED_BROADCAST_DISTRIBUTION)) {
                        return new BroadcastOutputBufferManager(childStage::setOutputBuffers);
                    }
                    else if (partitioningHandle.equals(SCALED_WRITER_DISTRIBUTION)) {
                        return new ScaledOutputBufferManager(childStage::setOutputBuffers);
                    }
                    else {
                        int partitionCount = Ints.max(childStage.getFragment().getPartitioningScheme().getBucketToPartition().get()) + 1;
                        return new PartitionedOutputBufferManager(partitioningHandle, partitionCount, childStage::setOutputBuffers);
                    }
                })
                .collect(toImmutableSet());
    }

    public void processScheduleResults(StageExecutionState newState, Set<RemoteTask> newTasks)
    {
        boolean noMoreTasks = false;
        switch (newState) {
            case PLANNED:
            case SCHEDULING:
                // workers are still being added to the query
                break;
            case FINISHED_TASK_SCHEDULING:
            case SCHEDULING_SPLITS:
            case SCHEDULED:
            case RUNNING:
            case FINISHED:
            case CANCELED:
                // no more workers will be added to the query
                noMoreTasks = true;
            case ABORTED:
            case FAILED:
                // DO NOT complete a FAILED or ABORTED stage.  This will cause the
                // stage above to finish normally, which will result in a query
                // completing successfully when it should fail..
                break;
        }

        // Add an exchange location to the parent stage for each new task
        parent.addExchangeLocations(currentStageFragmentId, newTasks, noMoreTasks);

        if (!childOutputBufferManagers.isEmpty()) {
            // Add an output buffer to the child stages for each new task
            List<OutputBuffers.OutputBufferId> newOutputBuffers = newTasks.stream()
                    .map(task -> new OutputBuffers.OutputBufferId(task.getTaskId().getId()))
                    .collect(toImmutableList());
            for (OutputBufferManager child : childOutputBufferManagers) {
                child.addOutputBuffers(newOutputBuffers, noMoreTasks);
            }
        }
    }
}


text:
Impact of enabling ipfw, pf or ipf on forwarding performance
  - Netgate RCC-VE 4860 (4 cores Intel Atom C2558E)
  - Quad port Intel i350
  - FreeBSD 11.1
  - 2000 flows of smallest UDP packets
  - Traffic load at 1.448Mpps (Gigabit line-rate)
  - hw.igb.rx_process_limit=-1
  - harvest.mask=351

![Impact of enabling ipfw/pf/ipf on forwarding performance on FreeBSD 11.1](graph.png)


text:
import BottomBar from '../lib/ui/bottom-bar.js';
import cmdify from 'cmdify';
import { spawn } from 'node:child_process';

const loader = ['/ Installing', '| Installing', '\\ Installing', '- Installing'];
let i = 4;
const ui = new BottomBar({ bottomBar: loader[i % 4] });

setInterval(() => {
  ui.updateBottomBar(loader[i++ % 4]);
}, 300);

const cmd = spawn(cmdify('npm'), ['-g', 'install', 'inquirer'], { stdio: 'pipe' });
cmd.stdout.pipe(ui.log);
cmd.on('close', () => {
  ui.updateBottomBar('Installation done!\n');
  process.exit();
});


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>BOOST_TEST</title>
<link rel="stylesheet" href="../../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../../index.html" title="Boost.Test">
<link rel="up" href="../testing_tool_ref.html" title="Reference API for writing tests">
<link rel="prev" href="../testing_tool_ref.html" title="Reference API for writing tests">
<link rel="next" href="decorator_expected_failures.html" title="expected_failures (decorator)">

Home
Libraries
People
FAQ
More

BOOST_TEST

BOOST_TEST(statement);
BOOST_TEST_<level>(statement);

// replacement failure message, requires variadic macros
BOOST_TEST(statement, "failure message");

// Floating point comparison, requires variadic macros, auto and decltype
BOOST_TEST(statement, floating_point_comparison_manipulation);

// bitwise comparison, requires variadic macros, auto and decltype
BOOST_TEST(statement, boost::test_tools::bitwise() );

// element-wise comparison, for containers
BOOST_TEST(statement, boost::test_tools::per_element() );

// lexicographic comparison, for containers
BOOST_TEST(statement, boost::test_tools::lexicographic() );

          The full documentation of this macro is located here.

          The macro is available in three variants, corresponding to different assertion
          severity levels:

BOOST_TEST // or BOOST_TEST_CHECK
BOOST_TEST_REQUIRE
BOOST_TEST_WARN

              "failure message"
              is a C-string printed in case of failure in place of the default message.
              See this section
              for more details.

              floating_point_comparison_manipulation
              is one of the floating point comparison manipulators. See this
              section for more details.

              boost::test_tools::bitwise
              is a manipulator indicating that the comparison should be performed
              bitwise. See this
              section for more details

              boost::test_tools::per_element
              is a manipulator indicating that the comparison should be performed
              on each element, in sequence, rather than on containers. See this section for more details

              boost::test_tools::lexicographic
              is a manipulator indicating that the comparison should be performed
              with the lexicographic order. See this
              section for more details

          Limitations
          and workaround

          There are some restrictions on the statements that are supported by this
          tool. Those are explained in details in this
          section.

Copyright © 2001-2016 Boost.Test contributors

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
  Ambrières-les-Vallées est
      une commune géographiquement positionnée dans le département de Mayenne en Pays de la Loire. Elle comptait 2 775 habitants en 2008.

La ville est équipée s'agissant de des études de un collège.
Concernant les plus jeunes, la localité est équipée de une maternelle et trois écoles primaires.
Ambrières-les-Vallées est équipée des  installations facilitant une bonne prise en charge des jeunes.
Si vous avez un projet d'acquisition immobilière à Ambrières-les-Vallées, vous devrez impérativement évaluer la valeur des équipements éducatifs

La commune offre de multiples  équipements, elle dispose, entre autres, de un bassin de natation, un terrain de tennis, un centre d'équitation et une boucle de randonnée.

Le nombre de logements, à Ambrières-les-Vallées, se décomposait en 2011 en 136 appartements et 1 325 maisons soit
 un marché plutôt équilibré.

À Ambrières-les-Vallées, la valorisation moyenne à la vente d'un appartement s'évalue à 541 € du m² en vente. Le prix moyen d'une maison à l'achat se situe à 892 € du m². À la location le prix moyen se situe à 4,48 € du m² mensuel.

À Ambrières-les-Vallées le salaire moyen mensuel par personne est situé à approximativement 1 758 €  net. C'est au dessous de la moyenne du pays.

À coté de Ambrières-les-Vallées sont localisées les communes de
Saint-Loup-du-Gast à 3 km, 353 habitants,
Chantrigné localisée à 4 km, 609 habitants,
Le Pas située à 6 km, 523 habitants,
Saint-Mars-sur-Colmont située à 6 km, 458 habitants,
Saint-Fraimbault-de-Prières située à 6 km, 972 habitants,
La Haie-Traversaine à 3 km, 484 habitants,
 entre autres. De plus, Ambrières-les-Vallées est située à seulement dix km de Mayenne.


text:
package ca.ubc.ece.salt.pangor.learn;

import org.kohsuke.args4j.Option;

public class LearningDataSetOptions {

	@Option(name="-h", aliases={"--help"}, usage="Display the help file.")
	private boolean help = false;

	@Option(name="-ds", aliases={"--dataset"}, usage="The data set file to read.")
	private String dataSetPath = null;

	@Option(name="-cc", aliases={"--complexity"}, usage="The maximum number of modified statements for a feature vector.")
	private int maxChangeComplexity = 10;

	@Option(name = "-a", aliases = { "--arff-path" }, usage = "Folder to write the ARFF files.")
	private String arffFolder = null;

	@Option(name = "-o", aliases = {"--oracle"}, usage="The oracle to use for cluster evaluation.")
	private String oracle = null;

	@Option(name = "-e", aliases = {"--epsilon"}, usage="The value of epsilon for clustering.")
	private double epsilon = 0.3;

	@Option(name = "-cw", aliases = {"--complexityWeight"}, usage="The weight of the complexity feature for clustering.")
	private double complexityWeight = 0.2;

	@Option(name = "-min", aliases = {"--minClusterSize"}, usage="The minimum size parameter for DBSCAN.")
	private int minClusterSize = 5;

	public String getArffFolder() {
		return this.arffFolder;
	}

	public boolean getHelp() {
		return this.help;
	}

	public String getDataSetPath() {
		return this.dataSetPath;
	}

	public String getOraclePath() {
		return this.oracle;
	}

	public Integer getMaxChangeComplexity() {
		return this.maxChangeComplexity;
	}

	public Double getEpsilon() {
		return this.epsilon;
	}

	public Double getComplexityWeight() {
		return this.complexityWeight;
	}

	public Integer getMinClusterSize() {
		return this.minClusterSize;
	}

}


text:
var exec = require('cordova/exec');

/**
 * Initialize the Helpshift SDK like here: https://developers.helpshift.com/ios/getting-started/#initializing
 *
 * @param {string} user {
 *   apiKey: string;
 *   domainName: string;
 *   appID: string;
 * }
 */
exports.initialize = function (arg0, success, error) {
    console.log('hs initializing');

    // validate arg0 to the type
    exec(function () {
        console.log('HelpshiftPhonegap.initialize() success', arguments);
        if (success) {
            success.apply(success, arguments);
        }
    }, function (e) {
        console.error('HelpshiftPhonegap.initialize() error', arguments);
        if (error) {
            error.apply(error, arguments);
        }
    }, 'HelpshiftPhonegap', 'setup', [arg0]);
};

exports.showConversation = function (arg0, success, error) {
    // validate arg0 to the type
    exec(function () {
        console.log('HelpshiftPhonegap.showConversation() success', arguments);
        if (success) {
            success.apply(success, arguments);
        }
    }, function (e) {
        console.error('HelpshiftPhonegap.showConversation() error', arguments);
        if (error) {
            error.apply(error, arguments);
        }
    }, 'HelpshiftPhonegap', 'showConversation', [arg0]);
};

exports.showFAQs = function (arg0, success, error) {
    // validate arg0 to the type
    exec(function () {
        console.log('HelpshiftPhonegap.showFAQs() success', arguments);
        if (success) {
            success.apply(success, arguments);
        }
    }, function (e) {
        console.error('HelpshiftPhonegap.showFAQs() error', arguments);
        if (error) {
            error.apply(error, arguments);
        }
    }, 'HelpshiftPhonegap', 'showFAQs', [arg0]);
};

/**
* Login a user with a given identifier, name and email. This API introduces support for multiple login in Helpshift.
* The identifier uniquely identifies the user.
* If any Helpshift session is active, then any login attempt is ignored.
* @param {string} user {
*   id: string;
*   name: string;
*   email: string;
* }
*/
exports.login = function (user, success, error) {
    if (!(user.id && user.name && user.email)) {
        throw new Error('helpshiftPhonegap.login() User invalid', user);
    }

    var helpshiftUser = {
        id: String(user.id),
        name: String(user.name),
        email: String(user.email),
    }

    // validate arg0 to the type
    exec(function () {
        console.log('HelpshiftPhonegap.login() success', arguments);
        if (success) {
            success.apply(success, arguments);
        }
    }, function (e) {
        console.error('HelpshiftPhonegap.login() error', arguments);
        if (error) {
            error.apply(error, arguments);
        }
    }, 'HelpshiftPhonegap', "login", [helpshiftUser]);
};

/**
  * Logout a currently logged in user.
  * After logout, Helpshift falls back to the default login. If any Helpshift session is active, then any logout attempt is ignored.
  */
exports.logout = function (user, success, error) {
    // validate arg0 to the type
    exec(function () {
        console.log('HelpshiftPhonegap.logout() success', arguments);
        if (success) {
            success.apply(success, arguments);
        }
    }, function (e) {
        console.error('HelpshiftPhonegap.logout() error', arguments);
        if (error) {
            error.apply(error, arguments);
        }
    }, 'HelpshiftPhonegap', "logout", []);
};

exports.setName = function (user, success, error) {
    if (!(user.name && user.email && user.id)) {
        throw new Error('helpshiftPhonegap.setName() User invalid. User should be: {id, name, email}', user);
    }

    var helpshiftUser = {
      name: String(user.name),
      email: String(user.email),
      id: String(user.id),
    }

    // validate arg0 to the type
    exec(function () {
        console.log('HelpshiftPhonegap.setName() success', arguments);
        if (success) {
            success.apply(success, arguments);
        }
    }, function (e) {
        console.error('HelpshiftPhonegap.setName() error', arguments);
        if (error) {
            error.apply(error, arguments);
        }
    }, 'HelpshiftPhonegap', "setName", [helpshiftUser]);
};


text:
.class public final enum Lcom/android/internal/telephony/CommandsInterface$RadioState;
.super Ljava/lang/Enum;
.source "CommandsInterface.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/internal/telephony/CommandsInterface;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x4019
    name = "RadioState"
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Ljava/lang/Enum",
        "<",
        "Lcom/android/internal/telephony/CommandsInterface$RadioState;",
        ">;"
    }
.end annotation

# static fields
.field private static final synthetic $VALUES:[Lcom/android/internal/telephony/CommandsInterface$RadioState;

.field public static final enum RADIO_OFF:Lcom/android/internal/telephony/CommandsInterface$RadioState;

.field public static final enum RADIO_ON:Lcom/android/internal/telephony/CommandsInterface$RadioState;

.field public static final enum RADIO_UNAVAILABLE:Lcom/android/internal/telephony/CommandsInterface$RadioState;

# direct methods
.method static constructor <clinit>()V
    .locals 5

    .prologue
    const/4 v4, 0x2

    const/4 v3, 0x1

    const/4 v2, 0x0

    .line 33
    new-instance v0, Lcom/android/internal/telephony/CommandsInterface$RadioState;

    const-string v1, "RADIO_OFF"

    invoke-direct {v0, v1, v2}, Lcom/android/internal/telephony/CommandsInterface$RadioState;-><init>(Ljava/lang/String;I)V

    sput-object v0, Lcom/android/internal/telephony/CommandsInterface$RadioState;->RADIO_OFF:Lcom/android/internal/telephony/CommandsInterface$RadioState;

    .line 34
    new-instance v0, Lcom/android/internal/telephony/CommandsInterface$RadioState;

    const-string v1, "RADIO_UNAVAILABLE"

    invoke-direct {v0, v1, v3}, Lcom/android/internal/telephony/CommandsInterface$RadioState;-><init>(Ljava/lang/String;I)V

    sput-object v0, Lcom/android/internal/telephony/CommandsInterface$RadioState;->RADIO_UNAVAILABLE:Lcom/android/internal/telephony/CommandsInterface$RadioState;

    .line 35
    new-instance v0, Lcom/android/internal/telephony/CommandsInterface$RadioState;

    const-string v1, "RADIO_ON"

    invoke-direct {v0, v1, v4}, Lcom/android/internal/telephony/CommandsInterface$RadioState;-><init>(Ljava/lang/String;I)V

    sput-object v0, Lcom/android/internal/telephony/CommandsInterface$RadioState;->RADIO_ON:Lcom/android/internal/telephony/CommandsInterface$RadioState;

    .line 32
    const/4 v0, 0x3

    new-array v0, v0, [Lcom/android/internal/telephony/CommandsInterface$RadioState;

    sget-object v1, Lcom/android/internal/telephony/CommandsInterface$RadioState;->RADIO_OFF:Lcom/android/internal/telephony/CommandsInterface$RadioState;

    aput-object v1, v0, v2

    sget-object v1, Lcom/android/internal/telephony/CommandsInterface$RadioState;->RADIO_UNAVAILABLE:Lcom/android/internal/telephony/CommandsInterface$RadioState;

    aput-object v1, v0, v3

    sget-object v1, Lcom/android/internal/telephony/CommandsInterface$RadioState;->RADIO_ON:Lcom/android/internal/telephony/CommandsInterface$RadioState;

    aput-object v1, v0, v4

    sput-object v0, Lcom/android/internal/telephony/CommandsInterface$RadioState;->$VALUES:[Lcom/android/internal/telephony/CommandsInterface$RadioState;

    return-void
.end method

.method private constructor <init>(Ljava/lang/String;I)V
    .locals 0
    .parameter
    .parameter
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()V"
        }
    .end annotation

    .prologue
    .line 32
    invoke-direct {p0, p1, p2}, Ljava/lang/Enum;-><init>(Ljava/lang/String;I)V

    return-void
.end method

.method public static valueOf(Ljava/lang/String;)Lcom/android/internal/telephony/CommandsInterface$RadioState;
    .locals 1
    .parameter "name"

    .prologue
    .line 32
    const-class v0, Lcom/android/internal/telephony/CommandsInterface$RadioState;

    invoke-static {v0, p0}, Ljava/lang/Enum;->valueOf(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Enum;

    move-result-object v0

    check-cast v0, Lcom/android/internal/telephony/CommandsInterface$RadioState;

    return-object v0
.end method

.method public static values()[Lcom/android/internal/telephony/CommandsInterface$RadioState;
    .locals 1

    .prologue
    .line 32
    sget-object v0, Lcom/android/internal/telephony/CommandsInterface$RadioState;->$VALUES:[Lcom/android/internal/telephony/CommandsInterface$RadioState;

    invoke-virtual {v0}, [Lcom/android/internal/telephony/CommandsInterface$RadioState;->clone()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, [Lcom/android/internal/telephony/CommandsInterface$RadioState;

    return-object v0
.end method

# virtual methods
.method public isAvailable()Z
    .locals 1

    .prologue
    .line 42
    sget-object v0, Lcom/android/internal/telephony/CommandsInterface$RadioState;->RADIO_UNAVAILABLE:Lcom/android/internal/telephony/CommandsInterface$RadioState;

    if-eq p0, v0, :cond_0

    const/4 v0, 0x1

    :goto_0
    return v0

    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method

.method public isOn()Z
    .locals 1

    .prologue
    .line 38
    sget-object v0, Lcom/android/internal/telephony/CommandsInterface$RadioState;->RADIO_ON:Lcom/android/internal/telephony/CommandsInterface$RadioState;

    if-ne p0, v0, :cond_0

    const/4 v0, 0x1

    :goto_0
    return v0

    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method


text:
var CONSTANTS = {
	QUESTION_PREFIX: "Q. ",
	LABEL_ANSWER_POSTFIX: " ", // TODO: currently there is an extra space appearing at the end of the label text
	ANSWER_SUBMIT_BUTTON: "Submit Answers",
	SAMPLE_DATE_INVALID: "20/10/1945",
	SAMPLE_DATE_VALID: "10/10/1945"
}


text:
<component name="libraryTable">
  <library name="Maven: org.apache.tomcat:tomcat-annotations-api:7.0.68">
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/org/apache/tomcat/tomcat-annotations-api/7.0.68/tomcat-annotations-api-7.0.68.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$MAVEN_REPOSITORY$/org/apache/tomcat/tomcat-annotations-api/7.0.68/tomcat-annotations-api-7.0.68-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$MAVEN_REPOSITORY$/org/apache/tomcat/tomcat-annotations-api/7.0.68/tomcat-annotations-api-7.0.68-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
require "action_view"

module Datagrid

  extend ActiveSupport::Autoload

  autoload :Core
  autoload :ActiveModel
  autoload :Filters
  autoload :Columns
  autoload :Ordering

  autoload :Helper
  ActionView::Base.send(:include, Datagrid::Helper)

  autoload :FormBuilder
  ActionView::Helpers::FormBuilder.send(:include, Datagrid::FormBuilder)

  autoload :Renderer

  autoload :Engine

  def self.included(base)
    base.extend         ClassMethods
    base.class_eval do

      include ::Datagrid::Core
      include ::Datagrid::ActiveModel
      include ::Datagrid::Filters
      include ::Datagrid::Columns
      include ::Datagrid::Ordering

    end
    base.send :include, InstanceMethods
  end # self.included

  module ClassMethods

  end # ClassMethods

  module InstanceMethods

  end # InstanceMethods

  class ConfigurationError < StandardError; end
  class ArgumentError < ::ArgumentError; end

end


text:
  <mat-button-toggle-group
    [value] = "toggleButtonValue"
    (change) = "toggleActorOrganismChoiceChange($event)"
    appearance="legacy"
  >
    <mat-button-toggle
      value="organism"
      matTooltip="Renseigner un organisme uniquement"
    >
      <mat-icon>domain</mat-icon>
    </mat-button-toggle>
    <mat-button-toggle
      value="person"
      matTooltip="Renseigner une personne uniquement"
    >
      <mat-icon>person</mat-icon>
    </mat-button-toggle>
    <mat-button-toggle
      value="all"
      matTooltip="Renseigner un organisme et un personne"
    >
      <mat-icon>domain</mat-icon>
      <mat-icon>person</mat-icon>
    </mat-button-toggle>
  </mat-button-toggle-group>
  <button
    *ngIf="isRemovable"
    mat-icon-button
    color="warn"
    matTooltip="Supprimer cet acteur"
    (click)="remove()"
  >
    <mat-icon>clear</mat-icon>
  </button>

  <form [formGroup]="actorForm">
    <ng-container *ngIf="!isMainContact">
       Type de role
      <ng-select
        class="auto"
        [items]="role_types"
        bindLabel="label_default"
        bindValue="id_nomenclature"
        placeholder="Type de role"
        [multiple]="false"
        [clearable]="false"
        formControlName="id_nomenclature_actor_role"
      >
        <ng-template
          ng-option-tmp
          let-item="item"
          let-index="index"
          let-search="searchTerm"
        >

            {{item.label_default}}

        </ng-template>
      </ng-select>
    </ng-container>

    <ng-container *ngIf="toggleButtonValue == 'organism' || toggleButtonValue == 'all'">
       Organisme
      <ng-select
        class="auto"
        [items]="organisms"
        bindLabel="nom_organisme"
        bindValue="id_organisme"
        placeholder="Organisme"
        [multiple]="false"
        [clearable]="true"
        [virtualScroll]="true"
        formControlName="id_organism"
      >
        <ng-template
          ng-option-tmp
          let-item="item"
          let-index="index"
          let-search="searchTerm"
        >

            {{item.nom_organisme}}

        </ng-template>
      </ng-select>
    </ng-container>

    <ng-container *ngIf="toggleButtonValue == 'person' || toggleButtonValue == 'all'">
       Personne
      <ng-select
        class="auto"
        [items]="roles"
        bindLabel="nom_complet"
        bindValue="id_role"
        placeholder="Personne"
        [multiple]="false"
        [clearable]="true"
        [virtualScroll]="true"
        formControlName="id_role"
      >
        <ng-template
          ng-option-tmp
          let-item="item"
          let-index="index"
          let-search="searchTerm"
        >

            {{item.nom_complet}}

        </ng-template>
      </ng-select>
    </ng-container>

  </form>


text:
<?xml version="1.0" encoding="UTF-8"?>

<coreProperties xmlns="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <dcterms:created xsi:type="dcterms:W3CDTF">2018-05-08T14:56:50Z</dcterms:created>
  <dc:creator>Apache POI</dc:creator>
</coreProperties>


text:
(function (angular) {

  // Create all modules and define dependencies to make sure they exist
  // and are loaded in the correct order to satisfy dependency injection
  // before all nested files are concatenated by Gulp

  // Modules
  angular.module('ngRights', ['ngRightsProvider', 'ngRightsDirective']);

})(angular);


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/**
 * @name: S15.7.3.2_A1;
 * @section: 15.7.3.2;
 * @assertion: Number.MAX_VALUE is approximately 1.7976931348623157e308;
 * @description: Checking Number.MAX_VALUE value;
*/

$INCLUDE("math_precision.js");
$INCLUDE("math_isequal.js");

// CHECK#1
if (!isEqual(Number.MAX_VALUE, 1.7976931348623157e308)) {
  $ERROR('#1: Number.MAX_VALUE approximately equal to 1.7976931348623157e308');
}


text:
extern "C" {

// See crt_interceptors_macros.h for details.
ASAN_CRT_INTERCEPTORS(ASAN_CRT_INTERCEPTORS_DEFN, asan_);

}  // extern "C"


text:
/**
 * generated by Xtext 2.10.0
 */
package com.laegler.stubbr.lang.stubbrLang.impl;

import com.laegler.stubbr.lang.stubbrLang.Attribute;
import com.laegler.stubbr.lang.stubbrLang.Entity;
import com.laegler.stubbr.lang.stubbrLang.StubbrLangPackage;

import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;

import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;

import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;

import org.eclipse.xtext.common.types.JvmTypeReference;

/**
 *
 * An implementation of the model object 'Attribute'.
 *
 *

 * The following features are implemented:
 *

 *

 *
{@link com.laegler.stubbr.lang.stubbrLang.impl.AttributeImpl#getName Name}

 *
{@link com.laegler.stubbr.lang.stubbrLang.impl.AttributeImpl#getLabel Label}

 *
{@link com.laegler.stubbr.lang.stubbrLang.impl.AttributeImpl#getDocumentation Documentation}

 *
{@link com.laegler.stubbr.lang.stubbrLang.impl.AttributeImpl#isPrimaryKey Primary Key}

 *
{@link com.laegler.stubbr.lang.stubbrLang.impl.AttributeImpl#getType Type}

 *
{@link com.laegler.stubbr.lang.stubbrLang.impl.AttributeImpl#getJavaType Java Type}

 *

 *
 * @generated
 */
public class AttributeImpl extends MinimalEObjectImpl.Container implements Attribute
{
  /**
   * The default value of the '{@link #getName() Name}' attribute.
   *
   *
   * @see #getName()
   * @generated
   * @ordered
   */
  protected static final String NAME_EDEFAULT = null;

  /**
   * The cached value of the '{@link #getName() Name}' attribute.
   *
   *
   * @see #getName()
   * @generated
   * @ordered
   */
  protected String name = NAME_EDEFAULT;

  /**
   * The default value of the '{@link #getLabel() Label}' attribute.
   *
   *
   * @see #getLabel()
   * @generated
   * @ordered
   */
  protected static final String LABEL_EDEFAULT = null;

  /**
   * The cached value of the '{@link #getLabel() Label}' attribute.
   *
   *
   * @see #getLabel()
   * @generated
   * @ordered
   */
  protected String label = LABEL_EDEFAULT;

  /**
   * The default value of the '{@link #getDocumentation() Documentation}' attribute.
   *
   *
   * @see #getDocumentation()
   * @generated
   * @ordered
   */
  protected static final String DOCUMENTATION_EDEFAULT = null;

  /**
   * The cached value of the '{@link #getDocumentation() Documentation}' attribute.
   *
   *
   * @see #getDocumentation()
   * @generated
   * @ordered
   */
  protected String documentation = DOCUMENTATION_EDEFAULT;

  /**
   * The default value of the '{@link #isPrimaryKey() Primary Key}' attribute.
   *
   *
   * @see #isPrimaryKey()
   * @generated
   * @ordered
   */
  protected static final boolean PRIMARY_KEY_EDEFAULT = false;

  /**
   * The cached value of the '{@link #isPrimaryKey() Primary Key}' attribute.
   *
   *
   * @see #isPrimaryKey()
   * @generated
   * @ordered
   */
  protected boolean primaryKey = PRIMARY_KEY_EDEFAULT;

  /**
   * The cached value of the '{@link #getType() Type}' reference.
   *
   *
   * @see #getType()
   * @generated
   * @ordered
   */
  protected Entity type;

  /**
   * The cached value of the '{@link #getJavaType() Java Type}' containment reference.
   *
   *
   * @see #getJavaType()
   * @generated
   * @ordered
   */
  protected JvmTypeReference javaType;

  /**
   *
   *
   * @generated
   */
  protected AttributeImpl()
  {
    super();
  }

  /**
   *
   *
   * @generated
   */
  @Override
  protected EClass eStaticClass()
  {
    return StubbrLangPackage.eINSTANCE.getAttribute();
  }

  /**
   *
   *
   * @generated
   */
  public String getName()
  {
    return name;
  }

  /**
   *
   *
   * @generated
   */
  public void setName(String newName)
  {
    String oldName = name;
    name = newName;
    if (eNotificationRequired())
      eNotify(new ENotificationImpl(this, Notification.SET, StubbrLangPackage.ATTRIBUTE__NAME, oldName, name));
  }

  /**
   *
   *
   * @generated
   */
  public String getLabel()
  {
    return label;
  }

  /**
   *
   *
   * @generated
   */
  public void setLabel(String newLabel)
  {
    String oldLabel = label;
    label = newLabel;
    if (eNotificationRequired())
      eNotify(new ENotificationImpl(this, Notification.SET, StubbrLangPackage.ATTRIBUTE__LABEL, oldLabel, label));
  }

  /**
   *
   *
   * @generated
   */
  public String getDocumentation()
  {
    return documentation;
  }

  /**
   *
   *
   * @generated
   */
  public void setDocumentation(String newDocumentation)
  {
    String oldDocumentation = documentation;
    documentation = newDocumentation;
    if (eNotificationRequired())
      eNotify(new ENotificationImpl(this, Notification.SET, StubbrLangPackage.ATTRIBUTE__DOCUMENTATION, oldDocumentation, documentation));
  }

  /**
   *
   *
   * @generated
   */
  public boolean isPrimaryKey()
  {
    return primaryKey;
  }

  /**
   *
   *
   * @generated
   */
  public void setPrimaryKey(boolean newPrimaryKey)
  {
    boolean oldPrimaryKey = primaryKey;
    primaryKey = newPrimaryKey;
    if (eNotificationRequired())
      eNotify(new ENotificationImpl(this, Notification.SET, StubbrLangPackage.ATTRIBUTE__PRIMARY_KEY, oldPrimaryKey, primaryKey));
  }

  /**
   *
   *
   * @generated
   */
  public Entity getType()
  {
    if (type != null && type.eIsProxy())
    {
      InternalEObject oldType = (InternalEObject)type;
      type = (Entity)eResolveProxy(oldType);
      if (type != oldType)
      {
        if (eNotificationRequired())
          eNotify(new ENotificationImpl(this, Notification.RESOLVE, StubbrLangPackage.ATTRIBUTE__TYPE, oldType, type));
      }
    }
    return type;
  }

  /**
   *
   *
   * @generated
   */
  public Entity basicGetType()
  {
    return type;
  }

  /**
   *
   *
   * @generated
   */
  public void setType(Entity newType)
  {
    Entity oldType = type;
    type = newType;
    if (eNotificationRequired())
      eNotify(new ENotificationImpl(this, Notification.SET, StubbrLangPackage.ATTRIBUTE__TYPE, oldType, type));
  }

  /**
   *
   *
   * @generated
   */
  public JvmTypeReference getJavaType()
  {
    return javaType;
  }

  /**
   *
   *
   * @generated
   */
  public NotificationChain basicSetJavaType(JvmTypeReference newJavaType, NotificationChain msgs)
  {
    JvmTypeReference oldJavaType = javaType;
    javaType = newJavaType;
    if (eNotificationRequired())
    {
      ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, StubbrLangPackage.ATTRIBUTE__JAVA_TYPE, oldJavaType, newJavaType);
      if (msgs == null) msgs = notification; else msgs.add(notification);
    }
    return msgs;
  }

  /**
   *
   *
   * @generated
   */
  public void setJavaType(JvmTypeReference newJavaType)
  {
    if (newJavaType != javaType)
    {
      NotificationChain msgs = null;
      if (javaType != null)
        msgs = ((InternalEObject)javaType).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - StubbrLangPackage.ATTRIBUTE__JAVA_TYPE, null, msgs);
      if (newJavaType != null)
        msgs = ((InternalEObject)newJavaType).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - StubbrLangPackage.ATTRIBUTE__JAVA_TYPE, null, msgs);
      msgs = basicSetJavaType(newJavaType, msgs);
      if (msgs != null) msgs.dispatch();
    }
    else if (eNotificationRequired())
      eNotify(new ENotificationImpl(this, Notification.SET, StubbrLangPackage.ATTRIBUTE__JAVA_TYPE, newJavaType, newJavaType));
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs)
  {
    switch (featureID)
    {
      case StubbrLangPackage.ATTRIBUTE__JAVA_TYPE:
        return basicSetJavaType(null, msgs);
    }
    return super.eInverseRemove(otherEnd, featureID, msgs);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public Object eGet(int featureID, boolean resolve, boolean coreType)
  {
    switch (featureID)
    {
      case StubbrLangPackage.ATTRIBUTE__NAME:
        return getName();
      case StubbrLangPackage.ATTRIBUTE__LABEL:
        return getLabel();
      case StubbrLangPackage.ATTRIBUTE__DOCUMENTATION:
        return getDocumentation();
      case StubbrLangPackage.ATTRIBUTE__PRIMARY_KEY:
        return isPrimaryKey();
      case StubbrLangPackage.ATTRIBUTE__TYPE:
        if (resolve) return getType();
        return basicGetType();
      case StubbrLangPackage.ATTRIBUTE__JAVA_TYPE:
        return getJavaType();
    }
    return super.eGet(featureID, resolve, coreType);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public void eSet(int featureID, Object newValue)
  {
    switch (featureID)
    {
      case StubbrLangPackage.ATTRIBUTE__NAME:
        setName((String)newValue);
        return;
      case StubbrLangPackage.ATTRIBUTE__LABEL:
        setLabel((String)newValue);
        return;
      case StubbrLangPackage.ATTRIBUTE__DOCUMENTATION:
        setDocumentation((String)newValue);
        return;
      case StubbrLangPackage.ATTRIBUTE__PRIMARY_KEY:
        setPrimaryKey((Boolean)newValue);
        return;
      case StubbrLangPackage.ATTRIBUTE__TYPE:
        setType((Entity)newValue);
        return;
      case StubbrLangPackage.ATTRIBUTE__JAVA_TYPE:
        setJavaType((JvmTypeReference)newValue);
        return;
    }
    super.eSet(featureID, newValue);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public void eUnset(int featureID)
  {
    switch (featureID)
    {
      case StubbrLangPackage.ATTRIBUTE__NAME:
        setName(NAME_EDEFAULT);
        return;
      case StubbrLangPackage.ATTRIBUTE__LABEL:
        setLabel(LABEL_EDEFAULT);
        return;
      case StubbrLangPackage.ATTRIBUTE__DOCUMENTATION:
        setDocumentation(DOCUMENTATION_EDEFAULT);
        return;
      case StubbrLangPackage.ATTRIBUTE__PRIMARY_KEY:
        setPrimaryKey(PRIMARY_KEY_EDEFAULT);
        return;
      case StubbrLangPackage.ATTRIBUTE__TYPE:
        setType((Entity)null);
        return;
      case StubbrLangPackage.ATTRIBUTE__JAVA_TYPE:
        setJavaType((JvmTypeReference)null);
        return;
    }
    super.eUnset(featureID);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public boolean eIsSet(int featureID)
  {
    switch (featureID)
    {
      case StubbrLangPackage.ATTRIBUTE__NAME:
        return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name);
      case StubbrLangPackage.ATTRIBUTE__LABEL:
        return LABEL_EDEFAULT == null ? label != null : !LABEL_EDEFAULT.equals(label);
      case StubbrLangPackage.ATTRIBUTE__DOCUMENTATION:
        return DOCUMENTATION_EDEFAULT == null ? documentation != null : !DOCUMENTATION_EDEFAULT.equals(documentation);
      case StubbrLangPackage.ATTRIBUTE__PRIMARY_KEY:
        return primaryKey != PRIMARY_KEY_EDEFAULT;
      case StubbrLangPackage.ATTRIBUTE__TYPE:
        return type != null;
      case StubbrLangPackage.ATTRIBUTE__JAVA_TYPE:
        return javaType != null;
    }
    return super.eIsSet(featureID);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public String toString()
  {
    if (eIsProxy()) return super.toString();

    StringBuffer result = new StringBuffer(super.toString());
    result.append(" (name: ");
    result.append(name);
    result.append(", label: ");
    result.append(label);
    result.append(", documentation: ");
    result.append(documentation);
    result.append(", primaryKey: ");
    result.append(primaryKey);
    result.append(')');
    return result.toString();
  }

} //AttributeImpl


text:
package com.vector.libtools.ui;

import android.content.res.ColorStateList;
import android.graphics.Color;

import java.util.Random;

/**
 * Created by Vector
 * on 2017/6/29 0029.
 */

public class ColorUtil {

    /**
     * 颜色选择器
     *
     * @param pressedColor 按下的颜色
     * @param normalColor  正常的颜色
     * @return 颜色选择器
     */
    public static ColorStateList getColorStateList(int pressedColor, int normalColor) {
        //其他状态默认为白色
        return new ColorStateList(
                new int[][]{{android.R.attr.state_enabled, android.R.attr.state_pressed}, {android.R.attr.state_enabled}, {}},
                new int[]{pressedColor, normalColor, Color.WHITE});
    }

    /**
     * 加深颜色
     *
     * @param color 原色
     * @return 加深后的
     */
    public static int colorDeep(int color) {

        int alpha = Color.alpha(color);
        int red = Color.red(color);
        int green = Color.green(color);
        int blue = Color.blue(color);

        float ratio = 0.8F;

        red = (int) (red * ratio);
        green = (int) (green * ratio);
        blue = (int) (blue * ratio);

        return Color.argb(alpha, red, green, blue);
    }

    /**
     * @param color 背景颜色
     * @return 前景色是否深色
     */
    public static boolean isTextColorDark(int color) {
        float a = (Color.red(color) * 0.299f + Color.green(color) * 0.587f + Color.blue(color) * 0.114f);
        return a > 180;
    }

    /**
     * 按条件的到随机颜色
     *
     * @param alpha 透明
     * @param lower 下边界
     * @param upper 上边界
     * @return 颜色值
     */

    public static int getRandomColor(int alpha, int lower, int upper) {
        return new RandomColor(alpha, lower, upper).getColor();
    }

    /**
     * @return 获取随机色
     */
    public static int getRandomColor() {
        return new RandomColor(255, 80, 200).getColor();
    }

    /**
     * 随机颜色
     */
    public static class RandomColor {
        int alpha;
        int lower;
        int upper;

        public RandomColor(int alpha, int lower, int upper) {
            if (upper <= lower) {
                throw new IllegalArgumentException("must be lower < upper");
            }
            setAlpha(alpha);
            setLower(lower);
            setUpper(upper);
        }

        public int getColor() {

            //随机数是前闭  后开

            int red = getLower() + new Random().nextInt(getUpper() - getLower() + 1);
            int green = getLower() + new Random().nextInt(getUpper() - getLower() + 1);
            int blue = getLower() + new Random().nextInt(getUpper() - getLower() + 1);

            return Color.argb(getAlpha(), red, green, blue);
        }

        public int getAlpha() {
            return alpha;
        }

        public void setAlpha(int alpha) {
            if (alpha > 255) alpha = 255;
            if (alpha < 0) alpha = 0;
            this.alpha = alpha;
        }

        public int getLower() {
            return lower;
        }

        public void setLower(int lower) {
            if (lower < 0) lower = 0;
            this.lower = lower;
        }

        public int getUpper() {
            return upper;
        }

        public void setUpper(int upper) {
            if (upper > 255) upper = 255;
            this.upper = upper;
        }
    }
}


text:
<?php
    /*
    Module: Users
    File: /modules/users/users.php
    Developer: Dionyziz
    */
    include "modules/module.php";

    // authentication script
    include "modules/users/auth.php";

    // perform authentication: check if user is logged in and initialize $user
    auth();

    function PasswordStrength( $password ) {
        global $user;

        $sequences = Array(
            "`1234567890-=" ,
            "qwertyuiop[]\\" ,
            "asdfghjkl;'" ,
            "zxcvbnm,./" ,
            "~!@#$%^&*()_+" ,
            "QWERTYUIOP{}|" ,
            "ASDFGHJKL:\"" ,
            "ZXCVBNM<>?" ,
            "abcdefghijklmnopqrstuvwxyz" ,
            "ABCDEFGHIJKLMNOPQRSTUVWXYZ" );

        $pwdlength = strlen( $password );
        $strengthmodifier = 0;

        if( $pwdlength < 4 ) {
            // password too short
            return 0;
        }
        if( strpos( strtolower( $user->Username() ) , strtolower( $password ) ) !== false ) {
            return 1;
        }
        if( preg_match( "#^[0-9]+$#" , $password ) == 1 ) {
            // the whole password consists of numbers
            $strengthmodifier = 1;
        }
        else {
            for( $i = 0 ; $i < count( $sequences ) ; $i++ ) {
                if( strpos( $sequences , $password ) !== false ) {
                    // the whole password is a part of a sequence
                    $strengthmodifier = 2;
                    break;
                }
            }
            if( !$strength_modifier ) {
                if( bc_spell_start( Array( $password ) ) == 0 ) {
                    // the whole password is a dictionary word
                    $strengthmodifier = 3;
                }
                else if( preg_match( "#^[a-z]+$#" , $password ) == 1 || preg_match( "#^[A-Z]+$#" , $password ) == 1 ) {
                    // the whole password consists of lower-case-only or upper-case-only latin characters
                    $strengthmodifier = 4;
                }
                else if( preg_match( "#^[a-z0-9]+$#" , $password ) == 1 || preg_match( "#^[A-Z0-9]+$#" , $password ) == 1 ) {
                    // the whole password consists of either only lower-case characters and numbers or only upper-case characters and numbers
                    $strengthmodifier = 5;
                }
                else if( preg_match( "#^[A-Za-z]+$#" , $password ) == 1 ) {
                    // the whole password consists of mixed lower and upprt case latin characters
                    $strengthmodifier = 6;
                }
                else if( preg_match( "#^[A-Za-z0-9]+$#" , $password ) == 1 ) {
                    // the whole password consists of mixed lower-case letters, upper-case letters and numbers
                    $strengthmodifier = 7;
                }
            }
        }
        $result = $strengthmodifier * ( $pwdlength - 3 ) * 5.55;
        if( $result > 100 ) {
            $result = 100;
        }
        $result = round( $result );
        return $result;
    }

    function Register( $invitationid , $invitationcode , $username , $passwordplaintext , $email , $firstname , $lastname , $invitedbyuserid ) {
        global $users;
        global $s_username;
        global $s_password;

        // mark the invitation as "userd"
        if( !ValidId( $invitationid ) ) {
            bc_die( "Invalid invitation id provided" );
        }
        $invitation = New Invitation( $invitationid );
        if( !$invitation->CheckValidy( $invitationcode ) ) {
            bc_die( "The invitation code you provided does not match your invitation" );
        }
        if( $invitation->RegisteredUserId() ) {
            bc_die( "The invitation you are trying to use has already been used" );
        }

        $theuser = GetUserByUsername( $username );
        if( $theuser ) {
            // user with this username already exists
            return -1;
        }
        if( !ValidEmail( $email ) ) {
            // invalid email address
            return -2;
        }
        $validuname = ValidUname( $username );
        if( $validuname === -1 ) {
            // invalid username
            return -3;
        }
        elseif( $validuname === -2 ) {
            // reserved username
            return -4;
        }
        // will we allow two different accounts with the same e-mail address?
        $pwd = md5( $passwordplaintext );
        $nowdate = NowDate();
        $sql = "INSERT INTO `$users` ( `user_id` , `user_username` , `user_password` , `user_email` , `user_registerdate` , `user_invitedbyuserid` , `user_firstname` , `user_lastname` , `user_bcadmin` ) VALUES( '' , '$username' , '$pwd' , '$email' , '$nowdate' , '$invitedbyuserid' , '$firstname' , '$lastname' , '100' );";
        bcsql_query( $sql );
        $newuserid = bcsql_insert_id();

        $s_username = $username;
        $s_password = $pwd;

        $_SESSION[ "s_username" ] = $s_username;
        $_SESSION[ "s_password" ] = $s_password;

        auth();

        if( !$invitation->MarkAsUsed( $newuserid ) ) {
            bc_die( "Error marking invitation as used" );
        }

        UserRegistration_Friends( $invitedbyuserid );
        UserRegistration_Messaging();
        UserRegistration_Bookmarks();

        return $newuserid;
    }

    function URegister( $userid ) {
        global $users;

        UserURegistration_Friends( $userid );
        UserURegistration_Messaging( $userid );

        $sql = "DELETE FROM `$users` WHERE `user_id`='$userid' LIMIT 1;";
    }

    function GetUserByUsername( $username ) {
        global $users;

        $username = bcsql_escape( $username );
        $sql = "SELECT * FROM `$users` WHERE `user_username`='$username' LIMIT 1;";
        $sqlr = bcsql_query( $sql );
        if ( bcsql_num_rows( $sqlr ) ) {
            $sqluser = bcsql_fetch_array( $sqlr );
            return New User( $sqluser );
        }
        // no such user found
        return false;
    }

    function GetUserByEmail( $email ) {
        global $users;

        $email = bcsql_escape( $email );
        $sql = "SELECT * FROM `$users` WHERE `user_email`='$email';";
        $sqlr = bcsql_query( $sql );
        if ( bcsql_num_rows( $sqlr ) == 1 ) {
            $sqluser = bcsql_fetch_array( $sqlr );
            return New User( $sqluser );
        }
        // no such user found, or more than one user with that email found
        return false;
    }

    function ValidUname( $username ) {
        // warning: use the === operator when you check for ValidUname values
        global $reserved;

        $validusernames = "#^[a-z][-a-z0-9]{2,}$#i";
        if( preg_match( $validusernames , $username ) == 0 ) {
            return -1; // invalid
        }
        if( in_array( $username , $reserved ) ) {
            return -2; // reserved
        }
        return true;
    }

    function GetUnameSuggestion( $username ) {
        $date = getdate();
        $suggestions = array(
                $username . "isthebest",
                $username . "isablogger",
                $username . "lovesblogging",
                $username . $date['year'],
                $username . "-" . $date['year'] ,
                $username . "iscool" ,
                $username . "-blogger" ,
                $username . "-is-cool" ,
                $username . "-is-the-best" ,
                $username . "-loves-blogging" );

        $validsuggestions = array();
        while(list($index, $suggestion) = each($suggestions)) {
            $theuser = GetUserByUserName( $suggestion );
            if($theuser === false) {
                array_push($validsuggestions, $suggestion);
            }
        }
        if ( count( $validsuggestions ) ) {
            return $validsuggestions[ rand(0, count($validsuggestions) - 1) ];
        }
        return false;
    }

    class User {
        private $mId;
        private $mUsername;
        private $mPassword;
        private $mFailedLogins;
        private $mLastActive;
        private $mInvitedByUser;
        private $mInvitationsLeft;
        private $mBookmarksRootId; // @bookmarks
        private $mFriendsRootId; // @friends
        private $mGotFriendsRoot;
        private $mFriendsRoot;
        private $mEmail;
        private $mAvatar; // @media
        private $mBcAdmin;
        private $mBcDeveloper;
        private $mRegisterDate;
        private $mFirstName;
        private $mLastName;
        private $mCountryId; // @countries
        private $mGender;
        private $mDob;
        private $mWebsite;
        private $mMsn;
        private $mYahoo;
        private $mIcq;
        private $mJabber;
        private $mGtalk;
        private $mAim;
        private $mMobile;
        private $mPublicEmail;
        private $mPublicMsn;
        private $mPublicYahoo;
        private $mPublicIcq;
        private $mPublicJabber;
        private $mPublicGtalk;
        private $mPublicAim;
        private $mPublicBirthday;
        private $mPublicAge;
        private $mPublicMobile;
        private $mFavoriteMovie;
        private $mFavoriteBand;
        private $mFavoriteMusicGenre;
        private $mFavoriteGame;
        private $mFavoriteQuote;
        private $mHair;
        private $mEyes;
        private $mAboutMe;
        private $mBlogs;
        private $mBlogsLoaded;
        private $mHasBlogs;
        private $mPin;
        private $mAllowEmailBlogging;
        private $mAllowSMSBlogging;

        public function Su() {
            global $anonymous;

            $_SESSION[ "s_username" ] = $this->mUsername;
            $_SESSION[ "s_password" ] = $this->mPassword;
            auth();
            return !$anonymous;
        }
        public function HasPin() {
            return $this->mPin != "";
        }
        public function ClearPin() {
            global $users;

            $sql = "UPDATE `$users` SET `user_pin`='' WHERE `user_id`='" . $this->mId. "' LIMIT 1;";
            bcsql_query( $sql );
        }
        public function CheckPin( $pin ) {
            return md5( $pin ) == $this->mPin;
        }
        public function SetPin( $newpin ) {
            global $users;

            $newpin = md5( $newpin );
            $sql = "UPDATE `$users` SET `user_pin`='$newpin' WHERE `user_id`='" . $this->mId. "' LIMIT 1;";
            bcsql_query( $sql );
        }
        public function Id() {
            return $this->mId;
        }
        public function Username() {
            return $this->mUsername;
        }
        public function PasswordHash() {
            // for checking use CheckPassword instead
            return $this->mPassword;
        }
        public function CheckPassword( $password ) {
            return md5( $password ) == $this->mPassword;
        }
        public function SetPassword( $newpassword ) {
            global $users;

            if( strlen( $newpassword ) <= 3 ) {
                bc_die( "User::SetPassword(): Password must be at least four characters long!" );
            }
            $newpassword = md5( $newpassword );
            $sql = "UPDATE `$users` SET `user_password`='$newpassword' WHERE `user_id`='" . $this->mId . "' LIMIT 1;";
            bcsql_query( $sql );
            $this->mPassword = $newpassword;
        }
        public function FailedLogins() {
            return $this->mFailedLogins;
        }
        public function AddFailedLogin() {
            global $users;

            $sql = "UPDATE `$users` SET `user_failedlogins`= `user_failedlogins` + 1 WHERE `user_id`='" . $this->mId. "' LIMIT 1;";
            bcsql_query( $sql );
            $this->mFailedLogins++;
        }
        public function RemoveFailedLogins() {
            global $users;

            $sql = "UPDATE `$users` SET `user_failedlogins`= 0 WHERE `user_id`='" . $this->mId. "' LIMIT 1;";
            bcsql_query( $sql );
            $this->mFailedLogins = 0;
        }
        public function LastActive() {
            return $this->mLastActive;
        }
        public function InvitedByUser() {
            return $this->mInvitedByUser;
        }
        public function InvitationsLeft() {
            return $this->mInvitationsLeft;
        }
        public function BookmarksRootFolderId() {
            return $this->mBookmarksRootId;
        }
        public function FriendsRootFolderId() {
            return $this->mFriendsRootId;
        }
        /* public function Friends() { // @/modules/friends/friends.php::FriendFolder
            if ( !$this->mGotFriendsRoot ) {
                $this->mFriendsRoot = &New FriendFolder( $this->mFriendsRootId );
                $this->mGotFriendsRoot = true;
            }
            return $this->mFriendsRoot;
        } */
        public function Email() {
            return $this->mEmail;
        }
        public function SetEmail( $value ) {
            if( !ValidEmail( $value ) ) {
                return false;
            }
            return $this->mSet( "email" , $value );
        }
        public function Avatar() {
            return $this->mAvatar;
        }
        public function IsAdmin() {
            return $this->mBcAdmin;
        }
        public function IsDeveloper() {
            return $this->mBcDeveloper;
        }
        public function RegisterDate() {
            return $this->mRegisterDate;
        }
        public function FirstName() {
            return $this->mFirstName;
        }
        public function SetFirstName( $value ) {
            return $this->mSet( "firstname" , $value );
        }
        public function LastName() {
            return $this->mLastName;
        }
        public function SetLastName( $value ) {
            return $this->mSet( "lastname" , $value );
        }
        public function CountryId() {
            return $this->mCountryId;
        }
        public function Gender() {
            return $this->mGender;
        }
        public function SetGender( $value ) {
            switch( $value ) {
                case 'male':
                case 'female':
                    return $this->mSet( "gender" , $value );
            }
            return false;
        }
        public function Dob() {
            return $this->mDob;
        }
        public function SetDob( $value ) {
            return $this->mSet( "dob" , $value );
        }
        public function Website() {
            return $this->mWebsite;
        }
        public function SetWebsite( $value ) {
            return $this->mSet( "website" , $value );
        }
        public function Msn() {
            return $this->mMsn;
        }
        public function SetMsn( $value ) {
            return $this->mSet( "msn" , $value );
        }
        public function Yahoo() {
            return $this->mYahoo;
        }
        public function SetYahoo( $value ) {
            return $this->mSet( "yahoo" , $value );
        }
        public function Icq() {
            return $this->mIcq;
        }
        public function SetIcq( $value ) {
            return $this->mSet( "icq" , $value );
        }
        public function Jabber() {
            return $this->mJabber;
        }
        public function SetJabber( $value ) {
            return $this->mSet( "jabber" , $value );
        }
        public function Gtalk() {
            return $this->mGtalk;
        }
        public function SetGTalk( $value ) {
            return $this->mSet( "gtalk" , $value );
        }
        public function Aim() {
            return $this->mAim;
        }
        public function SetAim( $value ) {
            return $this->mSet( "aim" , $value );
        }
        private function mSetPub( $pubfield , $value ) {
            switch( $value ) {
                case "private":
                case "public":
                case "friends":
                case "ffriends":
                    return $this->mSet( "public" . $pubfield , $value );
                default:
                    return false;
            }
        }
        public function PublicEmail() {
            return $this->mPublicEmail;
        }
        public function SetPublicEmail( $value ) {
            return $this->mSetPub( "email" , $value );
        }
        public function PublicMsn() {
            return $this->mPublicMsn;
        }
        public function SetPublicMsn( $value ) {
            return $this->mSetPub( "msn" , $value );
        }
        public function PublicYahoo() {
            return $this->mPublicYahoo;
        }
        public function SetPublicYahoo( $value ) {
            return $this->mSetPub( "yahoo" , $value );
        }
        public function PublicIcq() {
            return $this->mPublicIcq;
        }
        public function SetPublicIcq( $value ) {
            return $this->mSetPub( "icq" , $value );
        }
        public function PublicJabber() {
            return $this->mPublicJabber;
        }
        public function SetPublicJabber( $value ) {
            return $this->mSetPub( "jabber" , $value );
        }
        public function PublicGtalk() {
            return $this->mPublicGtalk;
        }
        public function SetPublicGtalk( $value ) {
            return $this->mSetPub( "gtalk" , $value );
        }
        public function PublicAim() {
            return $this->mPublicAim;
        }
        public function SetPublicAim( $value ) {
            return $this->mSetPub( "aim" , $value );
        }
        public function PublicBirthday() {
            return $this->mPublicBirthday;
        }
        public function SetPublicBirthday( $value ) {
            return $this->mSetPub( "birthday" , $value );
        }
        public function PublicAge() {
            return $this->mPublicAge;
        }
        public function SetPublicAge( $value ) {
            return $this->mSetPub( "age" , $value );
        }
        public function PublicMobile() {
            return $this->mPublicMobile;
        }
        public function SetPublicMobile( $value ) {
            return $this->mSetPub( "mobile" , $value );
        }
        public function FavoriteMovie() {
            return $this->mFavoriteMovie;
        }
        public function SetFavoriteMovie( $value ) {
            return $this->mSet( "favoritemovie" , $value );
        }
        public function FavoriteBand() {
            return $this->mFavoriteBand;
        }
        public function SetFavoriteBand( $value ) {
            return $this->mSet( "favoriteband" , $value );
        }
        public function FavoriteMusicGenre() {
            return $this->mFavoriteMusicGenre;
        }
        public function SetFavoriteMusicGenre( $value ) {
            return $this->mSet( "favoritemusicgenre" , $value );
        }
        public function FavoriteGame() {
            return $this->mFavoriteGame;
        }
        public function SetFavoriteGame( $value ) {
            return $this->mSet( "favoritegame" , $value );
        }
        public function FavoriteQuote() {
            return $this->mFavoriteQuote;
        }
        public function SetFavoriteQuote( $value ) {
            return $this->mSet( "favoritequote" , $value );
        }
        public function Hair() {
            return $this->mHair;
        }
        public function SetHair( $value ) {
            return $this->mSet( "hair" , $value );
        }
        public function Eyes() {
            return $this->mEyes;
        }
        public function SetEyes( $value ) {
            return $this->mSet( "eyes" , $value );
        }
        public function AboutMe() {
            return $this->mAboutMe;
        }
        public function SetAboutMe( $values ) {
            return $this->mSet( "aboutme" , $values );
        }
        public function AllowEmailBlogging() {
            return $this->mAllowEmailBlogging;
        }
        public function SetAllowEmailBlogging( $value ) {
            if( $value === true || $value === false ) {
                return $this->mSet( "allowemailblogging" , $value ? "yes" : "no" );
            }
            bc_die( "SetAllowEmailBlogging should take one boolean parameter" );
        }
        public function AllowSMSBlogging() {
            return $this->mAllowSMSBlogging;
        }
        public function SetAllowSMSBlogging( $value ) {
            if( $value === true || $value === false ) {
                return $this->mSet( "allowsmsblogging" , $value ? "yes" : "no" );
            }
            bc_die( "SetAllowSMSBlogging should take one boolean parameter" );
        }
        public function AssignInvitations( $number_of_new_invitations ) {
            // assign the given number of invitations to the user
            global $users;

            if( !is_numeric( $number_of_new_invitations ) ) {
                bc_die( "AssignedInvitations should be a number" );
            }
            if( $number_of_new_invitations > 0 ) {
                $sql = "UPDATE `$users`
                        SET `$users`.`user_invitationsleft`=(`$users`.`user_invitationsleft`+$number_of_new_invitations)
                        WHERE `$users`.`user_id`='" . $this->mId . "' LIMIT 1;";
                bcsql_query( $sql );
                $this->mInvitationsLeft += $number_of_new_invitations;
                return true;
            }
            return false;
        }
        public function ReduceInvitations() {
            global $users;

            if( $this->mInvitationsLeft ) {
                $sql = "UPDATE `$users`
                        SET `$users`.`user_invitationsleft`=(`$users`.`user_invitationsleft`-1)
                        WHERE `$users`.`user_id`='" . $this->mId . "' LIMIT 1;";
                $this->mInvitationsLeft--;
                bcsql_query( $sql );
                return true;
            }
            else {
                return false;
            }
        }
        public function &Blogs() {
            global $blogs;
            global $permissions;

            if ( $this->mBlogsLoaded ) {
                if ( $this->mHasBlogs ) {
                    return $this->mBlogs;
                }
                else {
                    return false;
                }
            }
            else {
                $sql = "SELECT
                            `$blogs`.*
                        FROM
                            `$blogs`,`$permissions`
                        WHERE
                            `$permissions`.`permission_userid`='" . $this->mId . "' AND
                            `$blogs`.`blog_id`=`$permissions`.`permission_blogid` AND
                            `$blogs`.`blog_active`='yes'
                        ORDER BY
                            `$blogs`.`blog_title` ASC;";
                $sqlr = bcsql_query( $sql );
                if ( bcsql_num_rows( $sqlr ) ) {
                    $this->mHasBlogs = true;
                    $this->mBlogs = New Blogs( $sqlr );
                    return $this->mBlogs;
                }
                else {
                    $this->mHasBlogs = false;
                    return false;
                }
            }
        }
        // construct function; you can either pass a userid
        // or a mysql fetched array to it (in case you want to
        // create a user class for a specific user (e.g. specific username,
        // etc.)
        public function User( $construct ) {
            global $users;

            if ( is_array( $construct ) ) {
                $fetched_array = $construct;
            }
            else {
                if( !is_numeric( $construct ) ) {
                    bc_die( "User class constructor parameter should either be a fetched array or an integer representing the user id" );
                }
                $construct = bcsql_escape( $construct );
                $sql = "SELECT
                            `$users`.*
                        FROM
                            `$users`
                        WHERE
                            `$users`.`user_id`='" . $construct . "'
                        LIMIT 1;";
                $sqlr = bcsql_query( $sql );
                if ( bcsql_num_rows( $sqlr ) ) {
                    $fetched_array = bcsql_fetch_array( $sqlr );
                }
                else {
                    $fetched_array = Array();
                }
            }
            if( count( $fetched_array ) ) {
                $this->mId = $fetched_array[ "user_id" ];
                $this->mUsername = $fetched_array[ "user_username" ];
                $this->mPassword = $fetched_array[ "user_password" ];
                $this->mFailedLogins = $fetched_array[ "user_failedlogins" ];
                $this->mPin = $fetched_array[ "user_pin" ];
                $this->mLastActive = $fetched_array[ "user_lastactive" ];
                $this->mInvitedByUser = $fetched_array[ "user_invitedbyuserid" ];
                $this->mInvitationsLeft = $fetched_array[ "user_invitationsleft" ];
                $this->mFriendsRootId = $fetched_array[ "user_friendsrootfolderid" ];
                if( !ValidId( $this->mFriendsRootId ) ) {
                    // invalid rootid
                    $this->mGotFriendsRoot = true;
                    $this->mFriendsRoot = false; // store false instead of an object
                }
                else {
                    $this->mGotFriendsRoot = false;
                }
                $this->mBookmarksRootFolderId = $fetched_array[ "user_bookmarksrootfolderid" ];
                $this->mEmail = $fetched_array[ "user_email" ];
                $this->mAvatar = $fetched_array[ "user_defaultavatar" ];
                $this->mBcAdmin = $fetched_array[ "user_bcadmin" ] >= 1000;
                $this->mBcDeveloper = $fetched_array[ "user_bcadmin" ] >= 500;
                $this->mRegisterDate = $fetched_array[ "user_registerdate" ];
                $this->mFirstName = $fetched_array[ "user_firstname" ];
                $this->mLastName = $fetched_array[ "user_lastname" ];
                $this->mCountryId = $fetched_array[ "user_countryid" ];
                $this->mGender = $fetched_array[ "user_gender" ];
                $this->mDob = $fetched_array[ "user_dob" ];
                $this->mWebsite = $fetched_array[ "user_website" ];
                $this->mMsn = $fetched_array[ "user_msn" ];
                $this->mYahoo = $fetched_array[ "user_yahoo" ];
                $this->mIcq = $fetched_array[ "user_icq" ];
                $this->mJabber = $fetched_array[ "user_jabber" ];
                $this->mGtalk = $fetched_array[ "user_gtalk" ];
                $this->mAim = $fetched_array[ "user_aim" ];
                $this->mPublicEmail = $fetched_array[ "user_publicemail" ];
                $this->mPublicMsn = $fetched_array[ "user_publicmsn" ];
                $this->mPublicIcq = $fetched_array[ "user_publicicq" ];
                $this->mPublicJabber = $fetched_array[ "user_publicjabber" ];
                $this->mPublicGtalk = $fetched_array[ "user_publicgtalk" ];
                $this->mPublicAim = $fetched_array[ "user_publicaim" ];
                $this->mPublicBirthday = $fetched_array[ "user_publicbirthday" ];
                $this->mPublicAge = $fetched_array[ "user_publicage" ];
                $this->mPublicMobile = $fetched_array[ "user_publicmobile" ];
                $this->mFavoriteMovie = $fetched_array[ "user_favoritemovie" ];
                $this->mFavoriteBand = $fetched_array[ "user_favoriteband" ];
                $this->mFavoriteMusicGenre = $fetched_array[ "user_favoritemusicgenre" ];
                $this->mFavoriteGame = $fetched_array[ "user_favoritegame" ];
                $this->mFavoriteQuote = $fetched_array[ "user_favoritequote" ];
                $this->mHair = $fetched_array[ "user_hair" ];
                $this->mEyes = $fetched_array[ "user_eyes" ];
                $this->mAboutMe = $fetched_array[ "user_aboutme" ];
                $this->mAllowEmailBlogging = $fetched_array[ "user_allowemailblogging" ];
                $this->mAllowSMSBlogging = $fetched_array[ "user_allowsmsblogging" ];
            }
        }
        private function mSet( $fieldname , $fieldvalue ) {
            // NEVER pass $fieldname dynamic, only static values
            global $users;

            // bc_die( $fieldname . " = " . $fieldvalue );
            //bug-fix: users can use html tags in some contacts, quotes etc
            $fieldvalue = strip_tags( $fieldvalue );
            $fieldvalue = bcsql_escape( $fieldvalue );
            $sql = "UPDATE `$users` SET `user_$fieldname`='$fieldvalue' WHERE `user_id`='" . $this->mId . "' LIMIT 1;";
            bcsql_query( $sql );
            return true;
        }
        public function IsFriend( $userid ) {
            // returns true if user with $userid is a friend of $this
            global $friends;
            global $friendfolders;

            if( $userid == $this->mId ) {
                return true;
            }

            $userid = bcsql_escape( $userid );
            $sql = "SELECT
                        `$friends`.`friend_userid`
                    FROM
                        `$friends`,`$friendfolders`
                    WHERE
                        `$friendfolders`.`ffolder_userid`='" . $this->mId . "' AND
                        `$friends`.`friend_parentfolderid`=`$friendfolders`.`ffolder_id` AND
                        `$friends`.`friend_userid`='" . $userid . "'
                    LIMIT 1;";

            $sqlr = bcsql_query( $sql );
            return bcsql_num_rows( $sqlr ) == 1;
        }
        public function IsFFriend( $userid ) {
            // returns true if user with $userid is a friend of a friend of $this or a friend of $this
            global $friends;
            global $friendfolders;

            if( $userid == $this->mId ) {
                return true;
            }

            // there MUST be a faster way to do that (one query)
            $userid = bcsql_escape( $userid );
            $sql = "SELECT
                        `$friends`.`friend_userid`
                    FROM
                        `$friends`,`$friendfolders`
                    WHERE
                        `$friendfolders`.`ffolder_userid`='" . $this->mId . "' AND
                        `$friends`.`friend_parentfolderid`=`$friendfolders`.`ffolder_id`;";

            $sqlr = bcsql_query( $sql );
            while( $thisfriend = bcsql_fetch_array( $sqlr ) ) {
                if( $thisfriend[ "friend_userid" ] == $userid ) {
                    return true;
                }
                else {
                    $thisfriendi = New User( $thisfriend[ "friend_userid" ] );
                    if( $thisfriendi->IsFriend( $userid ) ) {
                        return true;
                    }
                }
            }
            return false;
        }
    }

    function GetUsers( $start = 0, $limit = 21 ) {
        global $users;

        $sql = "SELECT
                    `$users`.*
                FROM
                    `$users`
                ORDER BY
                    `$users`.`user_id` ASC
                LIMIT $start, $limit;";
        return New Users( bcsql_query( $sql ) );
    }

    class Users {
        var $mUser;
        var $mLength;

        public function User( $index ) {
            if ( $index < $this->mLength )
                return $this->mUser[ $index ];
            else
                return false;
        }
        public function Length() {
            return $this->mLength;
        }
        public function Users( $sql_resource ) {
            $this->mLength = 0;
            while ( $thisuser = bcsql_fetch_array( $sql_resource ) ) {
                $this->mUser[ $this->mLength ] = New User( $thisuser );
                ++$this->mLength;
            }
        }
    }
?>


text: <option name="foo">hello</option>