different environments in CakePHP? - development-environment

I wanna have many environments in my CakePHP application,
and have a core.php file for each environment, i.e.,
core-production.php and core-development.php. How to manage it?

If I understand correctly, you are looking to load different configurations for each location. The best way to manage this is to establish custom configurations based on the location of the server.
So to do this, you can create a custom.php configuration that checks the server name.
$domain = strtolower(#$_SERVER['SERVER_NAME']);
switch (true) {
default:
case 'production.domain.com' == $domain:
Configure::write('MyDomain.environment', 'production');
break;
case 'staging.domain.com' == $domain:
Configure::write('MyDomain.environment', 'staging');
break;
case 'local.domain.com' == $domain:
case 'mybox.com' == $domain:
Configure::write('MyDomain.environment', 'local');
break;
}
Now, in the core, you can configure the settings based on your environment:
switch (Configure::read('MyDomain.environment')) {
default: // for security; wouldn't want any confusion revealing sensitive information
case 'production':
Configure::write('debug', 0);
break;
case 'staging':
case 'local':
Configure::write('debug', 2);
break;
}
Now you can configure everything anywhere using Configure::write('MyDomain.environment', x) without having to modify the way the CakePHP core reads the files.
Happy coding!

Related

C#-like case when in kotlin?

I come from a C# background and one really nice thing they offer is a way to add conditionals to a switch statement
switch(type)
{
case "edit":
// do something...
break;
case "delete" when user.isAdmin:
// do something...
break;
}
I'm curious if Kotlin has such an ability with their equivalent when? I'm not seeing that it's possible but I'm also still getting the hang of Kotlin so maybe there is a way.
I figured it out, guess I should have just asked Android studio XD
for those wondering, heres how:
when {
type == "edit" -> {
// do sometihng...
}
type == "delete" && user.isAdmin -> {
// do sometihng...
}
}
hope this helped someone else.

Detect a user logout on macOS

I am currently tryting to detect a user logout in macOS 10.14 (Mojave). I found this, which was working in the past:
Catching Logoff (not power off) event on MAC using objective C
The code I use is:
NSAppleEventManager* m = [NSAppleEventManager sharedAppleEventManager];
NSAppleEventDescriptor* desc = [m currentAppleEvent];
switch ([[desc attributeDescriptorForKeyword:kAEQuitReason] int32Value])
{
case kAELogOut:
case kAEReallyLogOut:
// log out
break;
case kAEShowRestartDialog:
case kAERestart:
// system restart
break;
case kAEShowShutdownDialog:
case kAEShutDown:
// system shutdown
break;
default:
// ordinary quit
break;
}
But the value I get is always zero (0).
Did something change in Mojave or is there another mechanism? This code is called in the applicationShouldTerminate function in my AppDelegate.
It's still available and it works (just tested on macOS Big Sur), but the value is in the enumCodeValue property.
func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
let reason = NSAppleEventManager.shared()
.currentAppleEvent?
.attributeDescriptor(forKeyword: kAEQuitReason)
switch reason?.enumCodeValue {
case kAELogOut, kAEReallyLogOut:
print("Logout")
return .terminateNow
case kAERestart, kAEShowRestartDialog:
print("Restart")
return .terminateNow
case kAEShutDown, kAEShowShutdownDialog:
print("Shutdown")
return .terminateNow
case 0:
// `enumCodeValue` docs:
//
// The contents of the descriptor, as an enumeration type,
// or 0 if an error occurs.
print("We don't know")
return .terminateNow
default:
print("Cmd-Q, Quit menu item, ...")
return .terminateNow
}
}

Bypassing functions that do not exist

how would it be possible to bypass functions that are not existing in DM
such that the main code would still run? Try/catch does not seem to work, e..g
image doSomething(number a,number b)
{
try
{
whateverfunction(a,b)
}
catch
{
continue
}
}
number a,b
doSomething(a,b)
Also conditioning wont work, e.g..
image doSomething(number a,number b)
{
if(doesfunctionexist("whateverfunction"))
{
whateverfunction(a,b)
}
}
number a,b
doSomething(a,b)
thanks in advance!
As "unknown" commands are caught by the script-interpreter, there is no easy way to do this. However, you can construct a workaround by using ExecuteScriptCommand().
There is an example tutorial to be found in this e-book, but in short, you want to do something like the following:
String scriptCallStr = "beep();\n"
scriptCallStr = "MyUnsaveFunctionCall();\n"
number exitVal
Try { exitVal = ExecuteScriptString(scriptCallStr ); }
Catch { exitVal = -1; break; }
if ( -1 == exitVal )
{
OKDialog("Sorry, couldn't do:\n" + scriptCallStr )
}
else
{
OKDialog( "All worked. Exit value: " + exitVal )
}
This works nicely and easy for simple commands and if your task is only to "verify" that a script could run.
It becomes clumsy, when you need to pass around parameters. But even then there are ways to do so. (The 'outer' script could create an object and pass the object-ID per string. Similarly, the 'inner' script can do the same and return the script-object ID as exit-value.)
Note: You can of course also put doesfunctionexist inside the test-script, if you do only want to have a "safe test", but don't actually want to execute the command.
Depending on what you need there might also be another workaround solution: Wrapper-functions in a library. This can be useful if you want to run the same script on different PCs with some of which having the functionality - most likely some microscope - while others don't.
You can make your main-script use wrapper methods and then you install different versions of the wrapper method script scripts as libraries.
void My_SpecialFunction( )
{
SpecialFunction() // use this line on PCs which have the SpecialFunction()
DoNothing() // use alternative line on PCs which don't have the SpecialFunction()
}
My_SpecialFunction( )
I have used this in the past where the same functionality (-stage movement-) required different commands on different machines.

Location authorization error even though I've asked for authorization in iOS 8 using swift

I have an app using the location services. If the app first starts, it ask the user for permission.
For some reason, if I tap on "Allow" I'll get this message:
Trying to start MapKit location updates without prompting for location authorization.
I know what this means, but I've set breakpoints all over my code and I am SURE that nothing tries to read the user location before it is allowed to do so.
Anyway, I seem to be missing something.
1) Is there a "common mistake" which one could do, something within the storyboard or so?
2) Will Apple reject an app that has such an error?
Thing is that the app works perfectly well, The only thing is that I see this message within the console. I don't know whether Apple will see this message too and if this would be a reason to reject an app..
if ([self.locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]) { // iOS8+
// Sending a message to avoid compile time error
[[UIApplication sharedApplication] sendAction:#selector(requestWhenInUseAuthorization)
to:self.locationManager
from:self
forEvent:nil];
} else {
[self.locationManager startUpdatingLocation];
}
}
I think you may need to include something like this for the requestWhenInUseAuthorization
Assume that you are using CLLocationManager. So did you make a strong reference to your locationManager object?
It seems to be a case when you requested location in local scope (variable) inside a function. Then trying to use MapKit, but locationManager object is already deallocated.
To solve that case, you should declare...
var locationManager = CLLocationManager()
... as an instance variable, then request authorization, and then using location services.
The problem was I have asked for authorization to use location services if the app is in use and I have determined the authorization like this:
func locationManager(manager: CLLocationManager!,
didChangeAuthorizationStatus status: CLAuthorizationStatus) {
switch status {
case CLAuthorizationStatus.Restricted:
locationStatus = GpsStatus.restricted
break
case CLAuthorizationStatus.Denied:
locationStatus = GpsStatus.denied
break
case CLAuthorizationStatus.NotDetermined:
locationStatus = GpsStatus.notDeterminded
break
default:
locationStatus = GpsStatus.allowed
break
}
}
This seems to be wrong, the error is gone if I explicitly check for CLAuthorizationStatus.AuthorizedWhenInUse:
func locationManager(manager: CLLocationManager!,
didChangeAuthorizationStatus status: CLAuthorizationStatus) {
switch status {
case CLAuthorizationStatus.Restricted:
locationStatus = GpsStatus.restricted
break
case CLAuthorizationStatus.Denied:
locationStatus = GpsStatus.denied
break
case CLAuthorizationStatus.NotDetermined:
locationStatus = GpsStatus.notDeterminded
break
case CLAuthorizationStatus.AuthorizedWhenInUse:
locationStatus = GpsStatus.allowed
default:
locationStatus = GpsStatus.notDeterminded
break
}
}
EDIT:
Seems like it's also a problem to add a TrackingLocationButton before I have the permission to use location services.
So do this
var userTrackingButton = MKUserTrackingBarButtonItem(mapView: self.mapView);
self.toolBar.items?.insert(userTrackingButton, atIndex: 0)
only if you have the permission
For iOS 8 you need to define the "Privacy - Location Usage Description" in the Info.plist.
Eg. NSLocationWhenInUseUsageDescription = "Use your location to show near by stores".
or
NSLocationAlwaysUsageDescription = "Use your location to show near by stores".
This key specifies the reason for accessing the user’s location information.

Change Authorization Dialog shown by AuthorizationCreate()

Looking through Apples BetterAuthorizationSample and further Derivatives( http://www.stevestreeting.com/2011/11/25/escalating-privileges-on-mac-os-x-securely-and-without-using-deprecated-methods/ )
I am trying to make a small change to the application and gain better understanding of the whole Security & ServiceManagement framework.. Therefore I proceeded to add an a button which removes the installed Job through the inverse of SMJobBless - SMJobRemove(). Straightforward however the AuthorizationCreate() call displays a dialog that states and requests permission to install a helper and not remove it.
That's the dialog I get (by using kSMRightModifySystemDaemons). As you can see it says that my app tries to add a new helper tool. Which will confuse my users because the app actually tries to remove the installed helper tool.
I'm seeking to find knowledge on how this dialog is changed to reflect my actual action (Job Removal), There are also several other apps which seem to completely customize the dialog - showing their own Custom Label and Buttons..
BOOL doRemoveSystemTool(NSString* label, NSError** error)
{
BOOL result = NO;
AuthorizationItem authItem = { kSMRightModifySystemDaemons, 0, NULL, 0 };
AuthorizationRights authRights = { 1, &authItem };
AuthorizationFlags flags = kAuthorizationFlagDefaults |
kAuthorizationFlagInteractionAllowed |
kAuthorizationFlagPreAuthorize |
kAuthorizationFlagExtendRights;
AuthorizationRef authRef = NULL;
//Obtain authorization
OSStatus status = AuthorizationCreate(&authRights, kAuthorizationEmptyEnvironment, flags, &authRef);
if (status != errAuthorizationSuccess)
{
NSLog(#"Failed to create AuthorizationRef, return code %ld", (long)status);
} else
{
//We have authorization so proceed with removing the Job via SMJobRemove
result = SMJobRemove(kSMDomainSystemLaunchd, (CFStringRef)label, authRef, YES, (CFErrorRef *)error);
}
AuthorizationFree(authRef, kAuthorizationFlagDefaults);
return result;
}
I have experimented with the authItem changing to kSMRightModifySystemDaemons from kSMRightBlessPrivilegedHelper but all this did was change the dialogue to display 'Add' instead of 'Install'
Would greatly appreciate some assistance here...
I haven't used this before but found your question interesting so I did a little reading of Apple's documentation and based on that I wonder if setting up the environment with a kAuthorizationEnvironmentPrompt would do what you want?
From AuthorizationTags.h:
The name of the AuthorizationItem that should be passed into the environment
when specifying a invocation specific additional text. The value should be a
localized UTF8 string.
You'd create an AuthorizationItem with this and then an AuthorizationItemSet containing that, and then pass the set into the AuthorizationCreate call for the environment: parameter.
I'd try that.
The other idea I had reading the documentation was to have a command line tool that does the remove and authorize the execution of the command line tool ("SomethingSomethingHelper") which might be less confusing to the user (so using AuthorizationExecuteWithPrivileges or kAuthorizationRightExecute or whatever).