FIXME: see FCREPO-765 - this should be migrated to an admin API (possibly with other methods from this class)
351022
private void modifyDatastreamControlGroupAction(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String actionLabel = "modifying datastream control group";

        Context context =
                ReadOnlyContext.getContext(Constants.HTTP_REQUEST.REST.uri,
                                           request);
        if (m_server == null) {
            throw new InternalError500Exception(request,
                                                actionLabel,
                                                "server not available",
                                                EMPTY_STRING_ARRAY);
        }
        // FIXME: see FCREPO-765 Admin methods are currently in DefaultManagement and carried through to ManagementModule
        ManagementModule apimDefault = (ManagementModule) m_server.getModule("org.fcrepo.server.management.Management");

        // FIXME: see FCREPO-765. tidy up output writing

        // get parameters
        String pid = request.getParameter("pid");
        String dsID = request.getParameter("dsID");
        String controlGroup = request.getParameter("controlGroup");
        boolean addXMLHeader = getParameterAsBoolean(request, "addXMLHeader", false);
        boolean reformat = getParameterAsBoolean(request, "reformat", false);
        boolean setMIMETypeCharset = getParameterAsBoolean(request, "setMIMETypeCharset", false);

        // get datastream list (single ds id is a list of one)
        String[] datastreams = dsID.split(",");

        // get iterable for pid looping
        boolean singlePID;
        Iterable<String> pids = null;
        if (pid.startsWith(PROTOCOL_FILE)) {
            File pidFile = new File(pid.substring(PROTOCOL_FILE.length()));
            pids = new PIDStreamIterableWrapper(new FileInputStream(pidFile));
            singlePID = false;

        } else { // pid list
            String[] pidList = pid.split(",");
            pids = new ArrayList<String>(Arrays.asList(pidList));
            singlePID = (pidList.length == 1);
        }

        try {

            response.setStatus(HttpServletResponse.SC_OK);
            response.setCharacterEncoding("UTF-8");

            PrintWriter pw = response.getWriter();

            // if doing a single pid/datastream, simple xml output
            if (singlePID && datastreams.length == 1) {
                response.setContentType("text/xml; charset=UTF-8");
                Date[] versions = apimDefault.modifyDatastreamControlGroup(context, pid, dsID, controlGroup, addXMLHeader, reformat, setMIMETypeCharset);
                pw.write("<versions>\n");
                    for (Date version : versions) {
                        pw.write("<version>" + version.toString() + "</version>\n");
                    }
                pw.write("</versions>\n");

            } else { // logging style output
                response.setContentType("text/plain; charset=UTF-8");
                ServerUtilitySerializer ser = new ServerUtilitySerializer(pw);
                for (String curpid : pids) {
                    ser.startObject(curpid);
                    for (String curdsID : datastreams) {
                        ser.startDatastream(curdsID);
                        Date[] versions;
                        try {
                            versions = apimDefault.modifyDatastreamControlGroup(context, curpid, curdsID, controlGroup, addXMLHeader, reformat, setMIMETypeCharset);
                        } catch (DatastreamNotFoundException e) {
                            versions = null;
                        }
                        ser.writeVersions(versions);
                        ser.endDatastream();
                    }
                    ser.endObject();
                }

                ser.finish();
            }
            pw.flush();


        } catch (ObjectNotFoundException e) {
            logger.error("Object not found: " + pid + " - " + e.getMessage());
            throw new NotFound404Exception(request,
                                           actionLabel,
                                           e.getMessage(),
                                           EMPTY_STRING_ARRAY);
        } catch (DatastreamNotFoundException e) {
            logger.error("Datastream not found: " + pid + "/" + dsID + " - " + e.getMessage());
            throw new NotFound404Exception(request,
                                           actionLabel,
                                           e.getMessage(),
                                           EMPTY_STRING_ARRAY);


        } catch (GeneralException e) {
            logger.error(e.getMessage());
            throw new InternalError500Exception(request,
                                                actionLabel,
                                                e.getMessage(),
                                                EMPTY_STRING_ARRAY);
        } catch (AuthzOperationalException aoe) {
            throw new Forbidden403Exception(request,
                                            actionLabel,
                                            "authorization failed",
                                            EMPTY_STRING_ARRAY);
        } catch (AuthzDeniedException ade) {
            throw new Forbidden403Exception(request,
                                            actionLabel,
                                            "authorization denied",
                                            EMPTY_STRING_ARRAY);
        } catch (AuthzPermittedException ape) {
            throw new Continue100Exception(request,
                                           actionLabel,
                                           "authorization permitted",
                                           EMPTY_STRING_ARRAY);

        } catch (ServerException e) {
            logger.error(e.getMessage(),e);
            throw new InternalError500Exception(request,
                                                actionLabel,
                                                "Unexpected error: " + e.getMessage(),
                                                EMPTY_STRING_ARRAY);
        }

    }
966456
function initalizeAdmins (adminConfigObject) {
            
            const admins = adminConfigObject || client.config("admins");

            if (!Array.isArray(admins)) {
                const errormsg = "\"admins\" property in configuration must be an array";
                client.error(errormsg);
                throw new Error(errormsg);
            }

            return admins.map(cloneOnlyAdminKeys).map(regexify);
        }
528102
function (list, location, ext, sequence, perms, title, src) {
			var actions = list.get_userCustomActions();

			var action = actions.add();

			action.set_title(title);
			action.set_location(location);
			action.set_commandUIExtension(ext);
			action.set_sequence(sequence || 0);
			(src && action.set_scriptSrc(src));
			if (perms)
				action.set_rights(perms);
			action.update();
			ctx.load(action);
			var dfd = $.Deferred();

			ctx.executeQueryAsync(function () {
				trace.log("addCustomAction.done");
				dfd.resolve(action);
			}, function (r, a) { ns.sp.reqFailure(r, a, "addCustomAction", dfd); });

			return dfd.promise();
		}
372418
public function create()
    {
        $fs = new Filesystem();

        if (!$this->sourceDir) {
            throw new \Exception('O diretório de código fonte "singular.directory.src" da aplicação não foi definido!');
        }

        $migrationDir = $this->getMigrationDir();

        if (!$fs->exists($migrationDir)) {
            throw new \Exception(sprintf('O diretório de migration não existe!'));
        }

        $timestamp = time();

        $aplicacoes = $this->getAplicacoesToMigration();

        if (count($aplicacoes) > 0) {
            $template = file_get_contents(
                __DIR__.DIRECTORY_SEPARATOR."templates".DIRECTORY_SEPARATOR."app_migration.tpl"
            );

            $template = str_replace('$TIMESTAMP',$timestamp, $template);
            $template = str_replace('$APLICACOES', $this->arrayToString($aplicacoes, $timestamp) , $template);

            $dt = new \DateTime('now', new \DateTimeZone('UTC'));
            $date = $dt->format('YmdHis');

            file_put_contents($migrationDir.DIRECTORY_SEPARATOR.$date.'_insere_registros_aplicacoes_'.$timestamp.'.php', $template);
        }

        $modulos = $this->getModulosToMigration();

        if (count($modulos) > 0) {
            $template = file_get_contents(
                __DIR__.DIRECTORY_SEPARATOR."templates".DIRECTORY_SEPARATOR."mod_migration.tpl"
            );

            $template = str_replace('$TIMESTAMP',$timestamp, $template);
            $template = str_replace('$MODULOS', $this->arrayToString($modulos, $timestamp) , $template);

            sleep(1);

            $dt = new \DateTime('now', new \DateTimeZone('UTC'));
            $date = $dt->format('YmdHis');

            file_put_contents($migrationDir.DIRECTORY_SEPARATOR.$date.'_insere_registros_modulos_'.$timestamp.'.php', $template);
        }

        $this->clearMigrations();

        return count($modulos) + count($aplicacoes);
    }
249832
function composeAddRemoveGroupMember({ action="add", roles="members" }) {
  /**
   * Add/Remove user from group
   *
   * @param {String} username
   * @param {String} groupname
   * @param {Function} done - done(err)
   */
   return function(username, groupname, done) {
     return getGroup(groupname, function(getGroupErr, group) {
       if (getGroupErr) {
         return done(getGroupErr);
       }

       if (!group) {
         return done(new Error(`group '${groupname}' not found`));
       }

       return getUser(username, function(getUserErr, user) {
         if (getUserErr) {
           return done(getUserErr);
         }

         if (!user) {
           return done(new Error(`user '${username}' not found`));
         }

         group[roles][action](user.id);
         return group.save(done);
       });
     });
   };
}
3319
@Override
    @Path("/{groupName}/{'users'}/{cuid}")
    @ApiOperation(value="Create a workgroup or add a user to an existing workgroup",
        notes="If users/{cuid} is present, user is added to workgroup.", response=StatusMessage.class)
    @ApiImplicitParams({
        @ApiImplicitParam(name="Workgroup", paramType="body", required=true, dataType="com.centurylink.mdw.model.user.Workgroup"),
        @ApiImplicitParam(name="groupName", paramType="path", required=true)})
    public JSONObject post(String path, JSONObject content, Map<String,String> headers)
    throws ServiceException, JSONException {
        String name = getSegment(path, 1);
        String rel = getSegment(path, 2);

        UserServices userServices = ServiceLocator.getUserServices();
        try {
            if (rel == null) {
                Workgroup workgroup = new Workgroup(content);
                Workgroup existing = userServices.getWorkgroups().get(workgroup.getName());
                if (existing != null)
                    throw new ServiceException(HTTP_409_CONFLICT, "Workgroup name already exists: " + workgroup.getName());
                userServices.createWorkgroup(workgroup);
                headers.put(Listener.METAINFO_HTTP_STATUS_CODE, "201");
            }
            else if (rel.equals("users")) {
                String cuid = getSegment(path, 3);
                User user = UserGroupCache.getUser(cuid);
                if (user == null) {
                    throw new CachingException("Cannot find user: " + cuid);
                }
                if (user.belongsToGroup(name))  // in case added elsewhere
                    throw new ServiceException(HTTP_409_CONFLICT, "User " + cuid + " already belongs to workgroup " + name);

                userServices.addUserToWorkgroup(cuid, name);
            }
            else {
                String msg = "Unsupported relationship for workgroup " + name + ": " + rel;
                throw new ServiceException(HTTP_400_BAD_REQUEST, msg);
            }
            return null;
        }
        catch (DataAccessException ex) {
            throw new ServiceException(HTTP_500_INTERNAL_ERROR, ex.getMessage(), ex);
        }
        catch (CachingException ex) {
             throw new ServiceException(HTTP_500_INTERNAL_ERROR, ex.getMessage(), ex);
        }
    }
1274290
@Override
	public Result<Void> addAdminToNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id) {
		TimeTaken tt = trans.start(ADD_NS_ADMIN + ' ' + ns + ' ' + id, Env.SUB|Env.ALWAYS);
		try {
			Result<Void> rp = service.addAdminNS(trans,ns,id);
			switch(rp.status) {
				case OK: 
					//TODO Perms??
					setContentType(resp,nsRequestDF.getOutType());
					resp.getOutputStream().println();
					return Result.ok();
				default:
					return Result.err(rp);
			}
		} catch (Exception e) {
			trans.error().log(e,IN,ADD_NS_ADMIN);
			return Result.err(e);
		} finally {
			tt.done();
		}
	}
647056
private function create()
    {
        restoreRequest();
        $form = array(
            'name'=>'UserForm',
            'caption' => admUsersCreate,
            'width' => '400px',
            'fields' => array (
                array('type'=>'hidden','name'=>'action','value'=>'insert'),
                array('type'=>'edit','name'=>'name','label'=>admUsersName,'maxlength'=>32,'width'=>'100%',
                    'pattern'=>'/.+/', 'errormsg'=>admUsersNameInvalid),
                array('type'=>'edit','name'=>'login','label'=>admUsersLogin,'maxlength'=>16,'width'=>'100%',
                    'pattern'=>'/^[a-z0-9_]+$/i', 'errormsg'=>admUsersLoginInvalid),
                array('type'=>'select','name'=>'access','label'=>admAccessLevel, 'width'=>'100%',
                    'values'=>array('2','3','4'),'items'=>array(ACCESSLEVEL2,ACCESSLEVEL3,ACCESSLEVEL4),
                    'default' => USER),
                array('type'=>'checkbox','name'=>'active','label'=>admUsersAccountState, 'default' => true),
                array('type'=>'divider'),
                array('type'=>'password','name'=>'pswd1','label'=>admUsersPassword,'maxlength'=>32,
                    'width'=>'100%'),
                array('type'=>'password','name'=>'pswd2','label'=>admUsersConfirmation,'maxlength'=>32,
                    'width'=>'100%', 'equal'=>'pswd1', 'errormsg'=>admUsersConfirmInvalid),
                array('type'=>'divider'),
                array('type' => 'edit', 'name' => 'mail' , 'label' => admUsersMail,
                    'maxlength' => 32, 'width' => '100%'),
            ),
            'buttons'=>array('ok', 'cancel')
        );

        /** @var TAdminUI $page */
        $page = Eresus_Kernel::app()->getPage();
        $result = $page->renderForm($form, Eresus_CMS::getLegacyKernel()->request['arg']);
        return $result;
    }
670870
function(ident, defFunc) {

	/**
	 * Here's the actual class we're making.
	 */
	var model = function(params) {
		var me = this;

		if (Object.keys(model.columns).length == 0) {
			logger.error("Attempting to initialize `" + model.ident + "` instance before filling schema!");
			return null;
		} else if (model.primary === undefined) {
			logger.error("No primary key found for `" + model.ident + "`!");
			return null;
		}

		Object.defineProperty(me, 'values', {
			value: {},
			enumerable: false,
			writable: true,
			configurable: true,
		}); // Raw column values, accessed by setter/getter functions.

		params = params || {};

		/* --- Instance Methods --- */

		/**
		 * Saves the object's properties corresponding to table columns into the database.
		 */
		function save() {
			var act = new NobleMachine(function() {
				setStrs = [];

				for (var key in model.columns) {
					if ([model.primary].indexOf(key) == -1 && me[key] !== undefined) {
						setStrs.push('`' + key + '`' + " = " + nrutil.serialize(me[key]));
					}
				}

				if (model.columns['updatedAt'])
					setStrs.push('`updatedAt` = NOW()');

				var sql;
				if (me[model.primary]) {
					sql = "UPDATE " + model.table
							+ " SET " + setStrs.join(',')
							+ " WHERE `" + model.primary + "` = " + me[model.primary];
				} else {
					if (model.columns['createdAt'])
						setStrs.push('`createdAt` = NOW()');

					sql = "INSERT"
							+ " INTO " + model.table
							+ " SET " + setStrs.join(',');
				}


				act.toNext(db_query(sql));
			});

			act.next(function(result) {
				//log.debug("RESULT: " + JSON.stringify(result));

				if (result.insert_id) {
					me[model.primary] = result.insert_id;
				} else if (!me[model.primary]) {
					act.toError("No insert_id, and no extant primary key!");
					return;
				}

				
				logger.log("Successfully saved `" + model.ident + "` record `" + me[model.primary] + "`");

				act.toNext(me);
			});

			act.error(function(err) {
				logger.error("Error saving `" + model.ident + "` record: " + JSON.stringify(err));
				act.emitError(err);
			});

			return act;
		}

		/**
		 * Reloads the object's properties with the current database values.
		 */
		function reload() {
			var params = {}

			params[model.primary] = me[model.primary]
		
			var act = new NobleMachine(model.find(params));

			act.next(function(newInst) {
				if (newInst) {
					for (var col in model.columns) {
						me[col] = newInst[col];
					}

					act.toNext(me);
				} else {
					for (var key in model.columns) {
						me[key] = undefined
					}

					act.toNext(null);
				}
			});

			return act;
		}

		/**
		 * Removes this object's corresponding database row.
		 */
		function destroy() {
			var act = new NobleMachine(function() {
				if (me.onDestroy) {
					var preact = me.onDestroy();
					if (preact && preact.start instanceof Function) {
						act.toNext(preact)
						return;
					}
				}
			});

			act.next(function() {
				var sql = "DELETE FROM " + model.table
						+ " WHERE `" + model.primary + "` = " + me[model.primary];

				act.toNext(db_query(sql));
			});

			act.next(function() {
				logger.log("Successfully deleted `" + model.ident + "` record `" + me[model.primary] + "`");

				for (var param in me) {
					delete me[param];	
				}
			});

			act.error(function(err) {
				logger.error("Error deleting `" + model.ident + "` record: " + JSON.stringify(err));
				act.emitError(err);
			});

			return act;
		}

		// Generic setter for SQL-correspondent values. Forces typecasting for database compatibility.
		function setValue(key, val) {
			//util.log(key + ": " + JSON.stringify(val));

			if (val === null) {
				me.values[key] = null;
			} else if (val === undefined) {
				me.values[key] = undefined;
			} else {
				type = model.columns[key]['DATA_TYPE'];

				switch (type) {
					case 'datetime':
					case 'timestamp':
						me.values[key] = new Date(val);
						break;
					case 'text':
					case 'varchar':
						me.values[key] = val.toString();
						break;
					case 'int':
					case 'tinyint':
						if (model.columns[key]['COLUMN_TYPE'] == 'tinyint(1)') {
							me.values[key] = !!val // Boolean
						} else {
							me.values[key] = parseInt(val);
						}
						break;
					default:
						me.values[key] = val;
				}
			}
		}

		// Generic getter for SQL-correspondent values.
		function getValue(key) {
			return me.values[key];
		}

		for (var key in model.columns) {
			me.__defineSetter__(key, setValue.bind(me, key));
			me.__defineGetter__(key, getValue.bind(me, key));

			if (params[key] !== undefined) {
				setValue(key, params[key]);
			}
		}

		_.extend(me, {
			save: save,
			reload: reload,
			destroy: destroy,
			setValue: setValue
		});

		if (defFunc !== undefined) {
			defFunc(me);
		}

		return me;
	}

	// This should be a unique, proper-cased identifier for the model as a whole.
	model.ident = ident;

	// Will be filled with INFORMATION_SCHEMA data.
	model.columns = {};

	// Guess the table name based on clever pluralization of the identifier.
	model.table = 'tbl' + ident.pluralize();

	/* --- Definition Methods --- */

	// Use this to override the default guess based on ident pluralization.
	model.setTableName = function(name) {
		model.table = name;
	}

	model.hasOne = function(foreignIdent) {
		model.prototype["get" + foreignIdent] = function() {
			var foreign = Models[foreignIdent];

			var opts = {}
			opts[model.primary] = this[model.primary];
			return foreign.find(opts);
		}
	}

	model.belongsTo = function(foreignIdent) {
		model.prototype["get" + foreignIdent] = function() {
			var foreign = Models[foreignIdent];

			var opts = {}
			opts[foreign.primary] = this[foreign.primary];
			return foreign.find(opts);
		}
	}

	/* --- Retrieval Methods --- */

	/**
	 * Executes a SELECT query on the table associated with this class and returns
	 * the result.
	 * @param where Qualifier to be passed to WHERE e.g "`this` = 'that'""
	 * @param fields Fields to return. Defaults to '*'.
	 */
	model.select = function(where, fields) {
		fields = fields || '*';

		var act = new NobleMachine(function() {
			var sql = "SELECT " + fields + " FROM " + model.table +
					  (where.length ? " WHERE " : '') + where + ";"

			act.toNext(db_query(sql));
		});

		act.next(function(result) {
			if (result.affected_rows == -1)
				act.toNext([]);
			else
				act.toNext(result.map(function(sqlobj) {
					return new model(sqlobj);
				}));
		});

		act.error(function(err) {
			logger.error("Error executing select statement for `" + model.ident +"`: " + JSON.stringify(err));
			act.emitError(err);
		});

		return act;
	}

	/**
     * A very simple SELECT query wrapper that returns a list of model instances.
	 * @param params Key-value pairs to be matched.
	 * @param conjunction Default 'AND'.
	 * @param fields Fields to return. Default in select().
     */
	model.where = function(params, conjunction, fields) {
		conjunction = conjunction || 'AND'
		var where = '';
		var first = true;

		logger.log("Finding all `" + model.ident + "`" + (params === undefined ? '' : " matching: " + util.inspect(params) + " with conjunction '" + conjunction + "'"));

		if (params) {
			for (var key in model.columns) {
				if (params[key] !== undefined) {
					where += (first ? '' : " " + conjunction + " ")
					if (params[key] == null) {
						where += "`" + key + "` IS NULL";
					} else {
						where += "`" + key + "` = " + nrutil.serialize(params[key]);
					}

					first = false;
				}
			}
		}

		return model.select(where, fields);
	}

	/**
	 * Emits first result from where() query
	 * @param params Params for find().
	 */
	model.find = function(params) {
		var act = new NobleMachine(function() {
			act.toNext(model.where(params));
		});

		act.next(function(objs) {
			act.toNext(objs.length ? objs[0] : null);
		});

		return act;
	}

	/**
	 * Retrieves every record of this type!
	 */
	model.all = function() {
		return model.where({});
	}

	/* --- Initialization Methods --- */

	/**
	 * This action queries the database to determine the structure of the table we are bound to.
	 */
	model.fillSchema = function() {
		var act = new NobleMachine(function() {
			var sql = "SELECT * FROM INFORMATION_SCHEMA.COLUMNS"
					+ " WHERE TABLE_SCHEMA = '" + common.config.database.options.database + "'"
					+ " AND TABLE_NAME = '" + model.table + "';";

			act.toNext(db_query(sql));
		});

		act.next(function(res) {
			if (res.length == 0) {
				act.toError("No columns found for table `" + model.table + "`.");
				return;
			}

			res.forEach(function(col) {
				model.columns[col['COLUMN_NAME']] = col;

				if (col['COLUMN_KEY'] == 'PRI') { // Primary key!
					model.primary = col['COLUMN_NAME'];
				}
			});

			if (!model.primary) {
				act.toError("Could not detect primary key for table `" + model.table + "`.");
				return;
			}
		});

		return act;
	}

	Models[model.ident] = model;

	return model;
}
846089
private void doUpdateJavaCFX() throws PageException {
	String name = getString("admin", action, "name");
	if (StringUtil.startsWithIgnoreCase(name, "cfx_")) name = name.substring(4);
	lucee.runtime.db.ClassDefinition cd = new ClassDefinitionImpl(getString("admin", action, "class"), getString("bundleName", null), getString("bundleVersion", null),
		config.getIdentification());
	admin.updateJavaCFX(name, cd);
	store();
	adminSync.broadcast(attributes, config);
    }
213624
function create()
    {
        $content = $this->loadContentTypes();
        $templates = $this->loadTemplates();
        restoreRequest();
        $form = array (
            'name' => 'createPage',
            'caption' => strAdd,
            'width' => '600px',
            'fields' => array (
                array ('type' => 'hidden','name'=>'owner','value'=>arg('owner', 'int')),
                array ('type' => 'hidden','name'=>'action', 'value'=>'insert'),
                array ('type' => 'edit','name' => 'name','label' => admPagesName,'width' => '150px',
                    'maxlength' => '32', 'pattern'=>'/^[a-z0-9_]+$/i', 'errormsg'=>admPagesNameInvalid),
                array ('type' => 'edit','name' => 'title','label' => admPagesTitle,'width' => '100%',
                    'pattern'=>'/.+/', 'errormsg'=>admPagesTitleInvalid),
                array ('type' => 'edit','name' => 'caption','label' => admPagesCaption,'width' => '100%',
                    'maxlength' => '64', 'pattern'=>'/.+/', 'errormsg'=>admPagesCaptionInvalid),
                array ('type' => 'edit','name' => 'hint','label' => admPagesHint,'width' => '100%'),
                array ('type' => 'edit','name' => 'description','label' => admPagesDescription,
                    'width' => '100%'),
                array ('type' => 'edit','name' => 'keywords','label' => admPagesKeywords,'width' => '100%'),
                array ('type' => 'select','name' => 'template','label' => admPagesTemplate,
                    'items' => $templates[0], 'values' => $templates[1], 'default'=>pageTemplateDefault),
                array ('type' => 'select','name' => 'type','label' => admPagesContentType,
                    'items' => $content[0], 'values' => $content[1], 'default'=>contentTypeDefault),
                array ('type' => 'checkbox','name' => 'active','label' => admPagesActive, 'default'=>true),
                array ('type' => 'checkbox','name' => 'visible','label' => admPagesVisible,
                    'default'=>true),
                array ('type' => 'select','name' => 'access','label' => admAccessLevel,'access' => ADMIN,
                    'values'=>array(ADMIN,EDITOR,USER,GUEST),
                    'items' => array (ACCESSLEVEL2,ACCESSLEVEL3,ACCESSLEVEL4,ACCESSLEVEL5),
                    'default' => GUEST),
                array ('type' => 'edit','name' => 'position','label' => admPosition,'access' => ADMIN,
                    'width' => '4em','maxlength' => '5'),
                array ('type' => 'memo','name' => 'options','label' => admPagesOptions,'height' => '5')
            ),
            'buttons' => array('ok', 'cancel'),
        );

        /** @var TAdminUI $page */
        $page = Eresus_Kernel::app()->getPage();
        $result = $page->renderForm($form, Eresus_CMS::getLegacyKernel()->request['arg']);
        return $result;
    }
1145012
public function run()
    {
        Model::unguard();

        DB::statement('SET FOREIGN_KEY_CHECKS=0;');

        DB::table('users')->delete();

        $admin = User::create([
            'id'          => 1,
            'name'        => 'admin',
            'email'       => 'admin@vain.app',
            'password'    => bcrypt('123456'),
            'locale'      => 'en',
            'birthday_at' => '2000-01-01',
        ]);

        $fgreinus = User::create([
            'id'          => 2,
            'name'        => 'fgreinus',
            'email'       => 'florian.greinus@gmail.com',
            'password'    => bcrypt('123456'),
            'locale'      => 'de',
            'birthday_at' => '2000-01-01',
        ]);

        $voydz = User::create([
            'id'          => 3,
            'name'        => 'voydz',
            'email'       => 'voydz@hotmail.com',
            'password'    => bcrypt('123456'),
            'locale'      => 'de',
            'birthday_at' => '2000-01-01',
        ]);

        $ottowayne = User::create([
            'id'          => 4,
            'name'        => 'ottowayne',
            'email'       => 'mr.ottowayne@gmail.com',
            'password'    => bcrypt('123456'),
            'locale'      => 'de',
            'birthday_at' => '2000-01-01',
        ]);

        // add user to admin roles
        /** @var Role[] $adminRoles */
        $adminRoles = Role::where('name', 'administrator')->get();
        $admin->saveRoles($adminRoles);
        $fgreinus->saveRoles($adminRoles);
        $voydz->saveRoles($adminRoles);
        $ottowayne->saveRoles($adminRoles);

        // add all permissions to admin roles
        /** @var Permission[] $permissions */
        $permissions = Permission::all();
        foreach ($adminRoles as $role) {
            $role->savePermissions($permissions);
        }

        DB::statement('SET FOREIGN_KEY_CHECKS=1;');
    }
1088359
public function main()
    {

        // Set a default fetchmode if none was specified
        // (We're doing that here to prevent errors loading the class is PDO is not available.)
        if ($this->fetchMode === null) {
            $this->fetchMode = PDO::FETCH_ASSOC;
        }

        // Initialize the formatters here.  This ensures that any parameters passed to the formatter
        // element get passed along to the actual formatter object
        foreach ($this->formatters as $fe) {
            $fe->prepare($this->getLocation());
        }

        $savedTransaction = [];
        for ($i = 0, $size = count($this->transactions); $i < $size; $i++) {
            $savedTransaction[] = clone $this->transactions[$i];
        }

        $savedSqlCommand = $this->sqlCommand;

        $this->sqlCommand = trim($this->sqlCommand);

        try {
            if ($this->srcFile === null && $this->sqlCommand === ""
                && empty($this->filesets) && empty($this->filelists)
                && count($this->transactions) === 0
            ) {
                throw new BuildException(
                    "Source file or fileset/filelist, "
                    . "transactions or sql statement "
                    . "must be set!",
                    $this->getLocation()
                );
            }

            if ($this->srcFile !== null && !$this->srcFile->exists()) {
                throw new BuildException("Source file does not exist!", $this->getLocation());
            }

            // deal with the filesets
            foreach ($this->filesets as $fs) {
                $ds = $fs->getDirectoryScanner($this->project);
                $srcDir = $fs->getDir($this->project);
                $srcFiles = $ds->getIncludedFiles();
                // Make a transaction for each file
                foreach ($srcFiles as $srcFile) {
                    $t = $this->createTransaction();
                    $t->setSrc(new PhingFile($srcDir, $srcFile));
                }
            }

            // process filelists
            foreach ($this->filelists as $fl) {
                $srcDir = $fl->getDir($this->project);
                $srcFiles = $fl->getFiles($this->project);
                // Make a transaction for each file
                foreach ($srcFiles as $srcFile) {
                    $t = $this->createTransaction();
                    $t->setSrc(new PhingFile($srcDir, $srcFile));
                }
            }

            // Make a transaction group for the outer command
            $t = $this->createTransaction();
            if ($this->srcFile) {
                $t->setSrc($this->srcFile);
            }
            $t->addText($this->sqlCommand);
            $this->conn = $this->getConnection();

            try {
                $this->statement = null;

                // Initialize the formatters.
                $this->initFormatters();

                try {
                    // Process all transactions
                    for ($i = 0, $size = count($this->transactions); $i < $size; $i++) {
                        if (!$this->isAutocommit()) {
                            $this->log("Beginning transaction", Project::MSG_VERBOSE);
                            $this->conn->beginTransaction();
                        }
                        $this->transactions[$i]->runTransaction();
                        if (!$this->isAutocommit()) {
                            $this->log("Committing transaction", Project::MSG_VERBOSE);
                            $this->conn->commit();
                        }
                    }
                } catch (Exception $e) {
                    $this->closeConnection();
                    throw $e;
                }
            } catch (IOException $e) {
                if (!$this->isAutocommit() && $this->conn !== null && $this->onError == "abort") {
                    try {
                        $this->conn->rollback();
                    } catch (PDOException $ex) {
                    }
                }
                $this->closeConnection();
                throw new BuildException($e->getMessage(), $this->getLocation());
            } catch (PDOException $e) {
                if (!$this->isAutocommit() && $this->conn !== null && $this->onError == "abort") {
                    try {
                        $this->conn->rollback();
                    } catch (PDOException $ex) {
                    }
                }
                $this->closeConnection();
                throw new BuildException($e->getMessage(), $this->getLocation());
            }

            // Close the formatters.
            $this->closeFormatters();

            $this->log(
                $this->goodSql . " of " . $this->totalSql .
                " SQL statements executed successfully"
            );
        } catch (Exception $e) {
            $this->transactions = $savedTransaction;
            $this->sqlCommand = $savedSqlCommand;
            $this->closeConnection();
            throw $e;
        }
        // finally {
        $this->transactions = $savedTransaction;
        $this->sqlCommand = $savedSqlCommand;
        $this->closeConnection();
    }
714397
private static List<Validate> createAdminObject(Connector cmd,
         List<Failure> failures, ResourceBundle rb, ClassLoader cl)
   {
      List<Validate> result = new ArrayList<Validate>();

      if (cmd.getVersion() != Version.V_10 &&
          cmd.getResourceadapter() != null &&
          cmd.getResourceadapter().getAdminObjects() != null)
      {
         List<AdminObject> aoMetas = cmd.getResourceadapter().getAdminObjects();
         if (!aoMetas.isEmpty())
         {
            for (AdminObject aoMeta : aoMetas)
            {
               if (aoMeta.getAdminobjectClass() != null
                     && !aoMeta.getAdminobjectClass().equals(XsdString.NULL_XSDSTRING))
               {

                  try
                  {
                     Class<?> clazz = Class.forName(aoMeta.getAdminobjectClass().getValue(), true, cl);
                     List<ConfigProperty> configProperties = aoMeta.getConfigProperties();

                     ValidateClass vc = new ValidateClass(Key.ADMIN_OBJECT, clazz, configProperties);
                     result.add(vc);
                  }
                  catch (ClassNotFoundException e)
                  {
                     Failure failure = new Failure(Severity.ERROR,
                                                   rb.getString("uncategorized"),
                                                   rb.getString("ao.cnfe"),
                                                   e.getMessage());
                     failures.add(failure);
                  }
               }
            }
         }
      }
      return result;
   }
316533
function createDb(config, dbUser, dbUserPass, dbName, cb) {
  log.logger.trace({user: dbUser, pwd: dbUserPass, name: dbName}, 'creating new datatbase');
  var url = config.mongoUrl;
  var admin = config.mongo.admin_auth.user;
  var admin_pass = config.mongo.admin_auth.pass;

  MongoClient.connect(url, function(err, db){
    if (err) return handleError(null, err, 'cannot open mongodb connection', cb);

    var targetDb = db.db(dbName);
    targetDb.authenticate(admin, admin_pass, {'authSource': 'admin'}, function(err) {
      if (err) return handleError(db, err, 'can not authenticate admin user', cb);

      // update for mongodb3.2 - need to remove user first
      targetDb.removeUser(dbUser, function(err) {
        if(err){
          log.logger.error(err, 'failed to remove user');
        }
        // add user to database
        targetDb.addUser(dbUser, dbUserPass, function(err, user) {
          if (err) return handleError(db, err, 'can not add user', cb);
          log.logger.trace({user: user, database: dbName}, 'mongo added new user');
          db.close();
          return cb();
        });
      });
    });
  });
}
96825
function init(userOpts = {}) {
    const opts = Object.assign(
        {
            template: '[hash].[ext][query]',
            preservePath: false,
            hashFunction(contents) {
                return crypto
                    .createHash('sha1')
                    .update(contents)
                    .digest('hex')
                    .substr(0, 16);
            },
            transform(fileMeta) {
                return fileMeta;
            },
            ignore: []
        },
        userOpts
    );

    return (style, result) => {
        if (opts.basePath) {
            if (typeof opts.basePath === 'string') {
                opts.basePath = [path.resolve(opts.basePath)];
            } else {
                opts.basePath = opts.basePath.map(elem => path.resolve(elem));
            }
        } else {
            opts.basePath = [process.cwd()];
        }

        if (opts.dest) {
            opts.dest = path.resolve(opts.dest);
        } else {
            throw new Error('Option `dest` is required in postcss-copy');
        }

        const promises = [];
        style.walkDecls(decl => {
            if (decl.value && decl.value.indexOf('url(') > -1) {
                promises.push(processDecl(result, decl, opts));
            }
        });
        return Promise.all(promises).then(decls =>
            decls.forEach(decl => {
                decl.value = String(decl.value);
            })
        );
    };
}
1036741
public function createAdminMenu() {
        $connection = \Yii::$app->db;
        $query = new Query;
        if(!$this->singleMenu) {
            $menu_name = $this->friendly($this->getController());
            $menu = $query->from('AdminMenu')
                ->where('internal=:internal', [':internal'=>$this->menu])
                ->one();

            if(!$menu) {
                $query = new Query;
                // compose the query
                $last_main_menu = $query->from('AdminMenu')
                    ->where('AdminMenu_id IS NULL')
                    ->orderby('order DESC')          
                    ->one();

                $this->insert('AdminMenu', [
                    "name" => $this->menu,
                    "internal" => $this->menu,
                    "url" => '',
                    "ap" => 'read::'.$this->getController(),
                    "order" => $last_main_menu ? $last_main_menu['order'] + 1 : 1
                ]);
                $menu_id = $connection->getLastInsertID();
            } else {
                $menu_id = $menu['id'];
            }
        } else {
            $menu_id = NULL;
            $menu_name = $this->menu;
        }
        $query = new Query;

        $last_menu = $query->from('AdminMenu')
                ->from('AdminMenu')
                ->where('AdminMenu_id=:AdminMenu_id', [':AdminMenu_id'=>$menu_id])
                ->orderby('order DESC')
                ->one();

        $this->insert('AdminMenu', [
            "AdminMenu_id" => $menu_id,
            "name" => $menu_name,
            "internal" => $this->getController() . 'Controller',
            "url" => ($this->module ? '/' . $this->module : '' ) . '/'. strtolower(trim(preg_replace("([A-Z])", "-$0", $this->getController()), '-')).'/',
            "ap" => 'read::'.$this->getController(),
            "order" => $last_menu ? $last_menu['order'] + 1 : 1
        ]);
    }