I'm trying to check does something exists in my database. Basicly I want to add device for user if it does not exists, and I'm trying to do it like so:
public static function checkDevice($userId, $tokenId){
$devices = UserDevices::where('user_id', $userId)->get();
$notExists = '';
foreach ($devices as $key => $d) {
if(!$d->ip_address === SecureAgent::getIP() && $d->mac_address === SecureAgent::getMAC() && $d->device === SecureAgent::getDevice() ){
$notExists = 'User device not found!';
}
}
}
So I need to check is does this IP, Mac and Device are already added in database, if any of them is not similar like any else I will need them to add in database like:
if($notExists === 'User device not found'){
self::addDevice() // I'm calling another function to do that job
}
Any suggestions?
I did it like so:
try {
UserDevices::where('user_id', $userId)->where('ip_address', SecureAgent::getIP())->where('mac_address', SecureAgent::getMac())->where('browser', SecureAgent::getSurfer())->firstOrFail();
} catch (\Exception $e) {
self::addDevice($userId, $tokenId);
}
Related
I have a controller working like this'
public function indexAction() {
// some stuff cut out
$openEntries = $this->checkOpenEntries($position);
if($openEntries === 0) {
//do some stuff
}
elseif ($openEntries === -1) {
//Sends email to notify about the problem
$body = 'Tried to create position log entry but found more than 1 open log entry for position ' . $position->getName() . ' in ' . $position->getACRGroup()->getName() . ' this should not be possible, there appears to be corrupt data in the database.';
$this->email($body);
return new response($body . ' An automatic email has been sent to it#domain.se to notify of the problem, manual inspection is required.');
} else {
//do some other stuff
}
}
private function checkOpenEntries($position) {
//Get all open entries for position
$repository = $this->getDoctrine()->getRepository('PoslogBundle:Entry');
$query = $repository->createQueryBuilder('e')
->where('e.stop is NULL and e.position = :position')
->setParameter('position', $position)
->getQuery();
$results = $query->getResult();
if(!isset($results[0])) {
return 0; //tells caller that there are no open entries
} else {
if (count($results) === 1) {
return $results[0]; //if exactly one open entry, return that object to caller
} else {
return -1; //if more than one open entry, null will signify to caller that we have a problem.
}
}
}
But I would like to put that response-returning-business already in the private function to clean up my indexAction, but that is not possible, the indexAction will keep going past the point of
$openEntries = $this->checkOpenEntries($position);
even if checkOpenEntries attempts to return a HTTP response.
Ideally I would like it to look like this, is there a way to accomplish that:
public function indexAction() {
// some stuff cut out
$openEntries = $this->checkOpenEntries($position);
if($openEntries === 0) {
//do some stuff
} else {
//do some other stuff
}
}
private function checkOpenEntries($position) {
//Get all open entries for position
$repository = $this->getDoctrine()->getRepository('PoslogBundle:Entry');
$query = $repository->createQueryBuilder('e')
->where('e.stop is NULL and e.position = :position')
->setParameter('position', $position)
->getQuery();
$results = $query->getResult();
if(!isset($results[0])) {
return 0; //tells caller that there are no open entries
} else {
if (count($results) === 1) {
return $results[0]; //if exactly one open entry, return that object to caller
} else {
//Sends email to notify about the problem
$body = 'Tried to create position log entry but found more than 1 open log entry for position ' . $position->getName() . ' in ' . $position->getACRGroup()->getName() . ' this should not be possible, there appears to be corrupt data in the database.';
$this->email($body);
return new response($body . ' An automatic email has been sent to it#domain.se to notify of the problem, manual inspection is required.');
}
}
}
IMHO, it is not clean the way you mix up the type of method. However, you could do something like this, to make it work.
In addition, I think it would be better if functions and parameters have type, it would be easier to read.
public function indexAction() {
// some stuff cut out
$openEntries = $this->checkOpenEntries($position);
if ($openEntries instanceOf Response) return $openEntries;
if($openEntries === 0) {
//do some stuff
} else {
//do some other stuff
}
// you might also want to add some response here!
return new Response('...');
}
I am really new at php and i came across this code.
Right now it checks for the hwid of a user and grants permission to a zip file if the hwid is in the valid users.
How can i make so the non valid users gets another zipfile to download?
Code:
`
$VALID_USERS = [
'BB12313-25DC-5132-BCEA-B23123123123',
''
];
$IS_REQUEST_ALLOWED = false;
if(!isset($_POST['hwid']) && !isset($_GET['hwid'])) { die(); }
$USER_HWID = '0';
if(isset($_POST['hwid'])) {
$USER_HWID = $_POST['hwid'];
} else {
$USER_HWID = $_GET['hwid'];
}
$USER_HWID = trim($USER_HWID);
$USER_HWID = strtoupper($USER_HWID);
foreach($VALID_USERS as $USER) {
$USER = strtolower($USER);
$HWID = strtolower($USER_HWID);
if($HWID === $USER) {
readfile('./ZIPFILE.zip'); die();
}
}
`
Assuming other code functions properly, your if clause at the end should look like this:
if($HWID === $USER) {
readfile('./ZIPFILE.zip'); die();
} else {
readfile('OtherFile.zip'); die();
}
After you compare $HWID === $USER, offer a different file in the ELSE added below.
foreach($VALID_USERS as $USER) {
$USER = strtolower($USER);
$HWID = strtolower($USER_HWID);
if($HWID === $USER) {
readfile('./ZIPFILE.zip'); die();
} else { //not a valid user
readfile("./invalid_file.zip");die();
}
}
Note that this will give "invalid_file.zip" to anyone who doesn't meet the criteria ($HWID===$USER) (maybe, see below).
Also, die() is rather a nasty way to exit (it doesn't even tell the user why it's leaving ...).
Please also take a look at your $VALID_USERS array. Surely you don't mean to have a null value in there?
Finally, what about the case of someone else who isn't null or "BB12313-25DC-5132-BCEA-B23123123123"?
You might wish to reconsider the use of this code.
Replace your entire foreach loop with this one if block. Since you are keeping your VALID_USERS in an array, you can use in_array() to quickly check if you user is there, the loop is unnecessary.
This:
foreach($VALID_USERS as $USER) {
$USER = strtolower($USER);
$HWID = strtolower($USER_HWID);
if($HWID === $USER) {
readfile('./ZIPFILE.zip'); die();
}
}
Becomes:
if (in_array($USER_HWID, $VALID_USERS, true)) {
readfile('./ZIPFILE.zip'); die();
} else {
readfile('./SomeOtherZIPFILE.zip'); die();
}
You will also notice that the 3rd paramter to in_array() has been set true in this example. This enables strict type comparison, to match the original codes '===' check.
I am trying to check whether a generated string is in my database table or not.
If there is no duplicate I want to return and save it.
If there is a duplicate I want to generate a new string and save it
currently this function does not return me the generated token:
public function checkForHashDuplicate($string)
{
$newToken = '';
$inquiries = DB::table('inquiries')->get();
foreach($inquiries as $inquiryKey => $inquiryValue)
{
while($inquiryValue->android_device_token == $string)
{
$newToken = generateAlphanumericString();
if($newToken != $inquiryValue->android_device_token)
{
return $newToken;
}
}
}
}
$inquiry->android_device_token = $this->checkForHashDuplicate($hash);
A simplified version of your code is:
public function checkForHashDuplicate($string)
{
do {
// generate token
$newToken = generateAlphanumericString();
// find token in a DB
$duplicate = DB::table('inquiries')
->where('android_device_token', '=', $newToken)->first();
// if token is FOUND `$duplicate` has truthy value
// and `do-while` keeps running
// else `$duplicate` is falsy and `do-while` breaks
} while ($duplicate);
return $newToken;
}
Instead of using:
$inquiries = DB::table('inquiries')->get();
and loop, use where like:
$inquiries = DB::table('inquiries')->where('android_device_token', '=', $string)->get();
if( count($inquiries ) == 1 )
{
// found
}
else
{
// Not found, generate new one
}
You can check like this:
public function checkDuplicate($string){
$count = DB::table('inquiries')->where('android_device_token',$string)->count();
if($count==0){
// $string exists
return generateAlphanumericString();
}else{
// $string doesn't exists
return $string;
}
}
Now, use this function to assign value of $string or new token as
$inquiry->android_device_token = $this->checkForHashDuplicate($hash);
Hope you understand.
I have this code to retrieve some countervalues of a copymachine.
foreach($sett as $key => $value){
if (intval(str_replace("INTEGER: ","",snmpget($ip, "public", $base.$value["MIB"])))) {
$c = intval(str_replace("INTEGER: ","",snmpget($ip, "public", $base.$value["MIB"])));
$error = false;
}
else {
$c = 0;
$error = true;
}
$counters = array_push_assoc($counters,ucwords($key),array("total" => $c, "code" => $value["code"]));
}
everything works like a charm but the only thing that is the problem is when a machine is down en the code cannot make an SNMPGET, the whole script fails.
First I want to check if the connection to the device is alive and then retrieve the counters with SNMPGET
Is there any solution you guys can offer me?
thx
The snmpget() function returns FALSE if it fails to retrieve the object.
See docs: http://www.php.net/manual/en/function.snmpget.php
You should do a check for this within your code, for example:
try
{
foreach($sett as $key => $value){
$sntpReturn = snmpget($ip, "public", $base.$value["MIB"]);
if ($sntpReturn === false)
{
// Do something to handle failed SNTP request.
throw new Exception("Failed to execute the SNTP request to the machine.");
}
else
{
if (intval(str_replace("INTEGER: ","", $sntpReturn))) {
$c = intval(str_replace("INTEGER: ","",snmpget($ip, "public", $base.$value["MIB"])));
$error = false;
}
else {
$c = 0;
$error = true;
}
$counters = array_push_assoc($counters,ucwords($key),array("total" => $c, "code" => $value["code"]));
}
}
catch (Exception $e)
{
// Handle the exception, maybe kill the script because it failed?
}
I am working with SilverStripe, and I am working on making a newspage.
I use the DataObjectAsPage Module( http://www.ssbits.com/tutorials/2012/dataobject-as-pages-the-module/ ), I got it working when I use the admin to publish newsitems.
Now I want to use the DataObjectManager Module instead of the admin module to manage my news items. But this is where the problem exists. Everything works fine in draft mode, I can make a new newsitem and it shows up in draft. But when I want to publish a newsitem, it won't show up in the live or published mode.
I'm using the following tables:
-Dataobjectaspage table,
-Dataobjectaspage_live table,
-NewsArticle table,
-NewsArticle_Live table
The Articles have been inserted while publishing in the Dataobjectaspage table and in the NewsArticle table... But not in the _Live tables...
Seems the doPublish() function hasn't been used while 'Publishing'.
So I'm trying the use the following:
function onAfterWrite() {
parent::onAfterWrite();
DataObjectAsPage::doPublish();
}
But when I use this, it gets an error:
here is this picture
It seems to be in a loop....
I've got the NewsArticle.php file where I use this function:
function onAfterWrite() {
parent::onAfterWrite();
DataObjectAsPage::doPublish();
}
This function calls the DataObjectAsPage.php file and uses this code:
function doPublish() {
if (!$this->canPublish()) return false;
$original = Versioned::get_one_by_stage("DataObjectAsPage", "Live", "\"DataObjectAsPage\".\"ID\" = $this->ID");
if(!$original) $original = new DataObjectAsPage();
// Handle activities undertaken by decorators
$this->invokeWithExtensions('onBeforePublish', $original);
$this->Status = "Published";
//$this->PublishedByID = Member::currentUser()->ID;
$this->write();
$this->publish("Stage", "Live");
// Handle activities undertaken by decorators
$this->invokeWithExtensions('onAfterPublish', $original);
return true;
}
And then it goes to DataObject.php file and uses the write function ():
public function write($showDebug = false, $forceInsert = false, $forceWrite = false, $writeComponents = false) {
$firstWrite = false;
$this->brokenOnWrite = true;
$isNewRecord = false;
if(self::get_validation_enabled()) {
$valid = $this->validate();
if(!$valid->valid()) {
// Used by DODs to clean up after themselves, eg, Versioned
$this->extend('onAfterSkippedWrite');
throw new ValidationException($valid, "Validation error writing a $this->class object: " . $valid->message() . ". Object not written.", E_USER_WARNING);
return false;
}
}
$this->onBeforeWrite();
if($this->brokenOnWrite) {
user_error("$this->class has a broken onBeforeWrite() function. Make sure that you call parent::onBeforeWrite().", E_USER_ERROR);
}
// New record = everything has changed
if(($this->ID && is_numeric($this->ID)) && !$forceInsert) {
$dbCommand = 'update';
// Update the changed array with references to changed obj-fields
foreach($this->record as $k => $v) {
if(is_object($v) && method_exists($v, 'isChanged') && $v->isChanged()) {
$this->changed[$k] = true;
}
}
} else{
$dbCommand = 'insert';
$this->changed = array();
foreach($this->record as $k => $v) {
$this->changed[$k] = 2;
}
$firstWrite = true;
}
// No changes made
if($this->changed) {
foreach($this->getClassAncestry() as $ancestor) {
if(self::has_own_table($ancestor))
$ancestry[] = $ancestor;
}
// Look for some changes to make
if(!$forceInsert) unset($this->changed['ID']);
$hasChanges = false;
foreach($this->changed as $fieldName => $changed) {
if($changed) {
$hasChanges = true;
break;
}
}
if($hasChanges || $forceWrite || !$this->record['ID']) {
// New records have their insert into the base data table done first, so that they can pass the
// generated primary key on to the rest of the manipulation
$baseTable = $ancestry[0];
if((!isset($this->record['ID']) || !$this->record['ID']) && isset($ancestry[0])) {
DB::query("INSERT INTO \"{$baseTable}\" (\"Created\") VALUES (" . DB::getConn()->now() . ")");
$this->record['ID'] = DB::getGeneratedID($baseTable);
$this->changed['ID'] = 2;
$isNewRecord = true;
}
// Divvy up field saving into a number of database manipulations
$manipulation = array();
if(isset($ancestry) && is_array($ancestry)) {
foreach($ancestry as $idx => $class) {
$classSingleton = singleton($class);
foreach($this->record as $fieldName => $fieldValue) {
if(isset($this->changed[$fieldName]) && $this->changed[$fieldName] && $fieldType = $classSingleton->hasOwnTableDatabaseField($fieldName)) {
$fieldObj = $this->dbObject($fieldName);
if(!isset($manipulation[$class])) $manipulation[$class] = array();
// if database column doesn't correlate to a DBField instance...
if(!$fieldObj) {
$fieldObj = DBField::create('Varchar', $this->record[$fieldName], $fieldName);
}
// Both CompositeDBFields and regular fields need to be repopulated
$fieldObj->setValue($this->record[$fieldName], $this->record);
if($class != $baseTable || $fieldName!='ID')
$fieldObj->writeToManipulation($manipulation[$class]);
}
}
// Add the class name to the base object
if($idx == 0) {
$manipulation[$class]['fields']["LastEdited"] = "'".SS_Datetime::now()->Rfc2822()."'";
if($dbCommand == 'insert') {
$manipulation[$class]['fields']["Created"] = "'".SS_Datetime::now()->Rfc2822()."'";
//echo "<li>$this->class - " .get_class($this);
$manipulation[$class]['fields']["ClassName"] = "'$this->class'";
}
}
// In cases where there are no fields, this 'stub' will get picked up on
if(self::has_own_table($class)) {
$manipulation[$class]['command'] = $dbCommand;
$manipulation[$class]['id'] = $this->record['ID'];
} else {
unset($manipulation[$class]);
}
}
}
$this->extend('augmentWrite', $manipulation);
// New records have their insert into the base data table done first, so that they can pass the
// generated ID on to the rest of the manipulation
if(isset($isNewRecord) && $isNewRecord && isset($manipulation[$baseTable])) {
$manipulation[$baseTable]['command'] = 'update';
}
DB::manipulate($manipulation);
if(isset($isNewRecord) && $isNewRecord) {
DataObjectLog::addedObject($this);
} else {
DataObjectLog::changedObject($this);
}
$this->onAfterWrite();
$this->changed = null;
} elseif ( $showDebug ) {
echo "<b>Debug:</b> no changes for DataObject<br />";
// Used by DODs to clean up after themselves, eg, Versioned
$this->extend('onAfterSkippedWrite');
}
// Clears the cache for this object so get_one returns the correct object.
$this->flushCache();
if(!isset($this->record['Created'])) {
$this->record['Created'] = SS_Datetime::now()->Rfc2822();
}
$this->record['LastEdited'] = SS_Datetime::now()->Rfc2822();
} else {
// Used by DODs to clean up after themselves, eg, Versioned
$this->extend('onAfterSkippedWrite');
}
// Write ComponentSets as necessary
if($writeComponents) {
$this->writeComponents(true);
}
return $this->record['ID'];
}
Look at the $this->onAfterWrite();
It probably goes to my own function on NewsArticle.php and there starts the loop! I'm not sure though, so i could need some help!!
Does anyone knows how to use the doPublish() function?
The reason that is happening is that in the DataObjectAsPage::publish() method, it is calling ->write() - line 11 of your 3rd code sample.
So what happens is it calls ->write(), at the end of ->write() your onAfterWrite() method is called, which calls publish(), which calls write() again.
If you remove the onAfterWrite() function that you've added, it should work as expected.
The doPublish() method on DataObjectAsPage will take care of publishing from Stage to Live for you.