Esempio n. 1
0
 function test_find()
 {
     $item = "POGs";
     $item2 = "Pokemon Cards";
     $test_item = new Inventory($item);
     $test_item->save();
     $test_item2 = new Inventory($item2);
     $test_item2->save();
     $search_item = $test_item->getItem();
     $result = Inventory::find($search_item);
     $this->assertEquals($test_item, $result);
 }
Esempio n. 2
0
 function test_find()
 {
     $description = "Blue candy";
     $description2 = "Light blue candy";
     $test_Inventory = new Inventory($description);
     $test_Inventory->save();
     $test_Inventory2 = new Inventory($description2);
     //Act
     $id = $test_Inventory->getId();
     $result = Inventory::find($id);
     //Assert
     $this->assertEquals($test_Inventory, $result);
 }
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new Inventory();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['Inventory'])) {
         $model->attributes = $_POST['Inventory'];
         if ($model->save()) {
             $this->redirect(array('view', 'id' => $model->id));
         }
     }
     $this->render('create', array('model' => $model));
 }
 public function actionCreate()
 {
     $model = new Inventory();
     if (isset($_POST['Inventory'])) {
         $model->setAttributes($_POST['Inventory']);
         if ($model->save()) {
             if (Yii::app()->getRequest()->getIsAjaxRequest()) {
                 Yii::app()->end();
             } else {
                 $this->redirect(array('view', 'id' => $model->inventory_id));
             }
         }
     }
     $this->render('create', array('model' => $model));
 }
Esempio n. 5
0
 function test_find()
 {
     //Arrange
     $item = "Antique Toothpick Holders";
     $item2 = "Ornamental Mouse Traps";
     $test_Inventory = new Inventory($item);
     $test_Inventory->save();
     $test_Inventory2 = new Inventory($item2);
     $test_Inventory2->save();
     //Act
     $id = $test_Inventory->getId();
     $result = Inventory::find($id);
     //Assert
     $this->assertEquals($test_Inventory, $result);
 }
Esempio n. 6
0
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function store()
 {
     if (Input::hasFile('image')) {
         $inventory = new Inventory();
         $inventory->title = Input::get('title');
         $inventory->description = Input::get('description');
         $inventory->users_id = Input::get('users_id');
         $inventory->collection_id = Input::get('collection');
         $md5 = md5_file(Input::file('image'));
         if (Input::file('image')->move(public_path() . '/uploads/', $md5)) {
             $inventory->file_name = $md5;
             $inventory->save();
         }
         return Redirect::route('inventory.index');
     }
 }
Esempio n. 7
0
 function remove_item()
 {
     $invoice_id = $this->input->post("invoice_id");
     $inventory_id = $this->input->post("inventory_id");
     $inventoryObject = new Inventory($inventory_id);
     $inventoryObject->invoice_id = NULL;
     $inventoryObject->status = 1;
     // In Stock
     $inventoryObject->save();
     $invoiceObject = new Invoice($invoice_id);
     $invoiceObject->total -= $inventoryObject->sale_price;
     $invoiceObject->save();
     $data["total"] = $invoiceObject->total;
     $data["tbody_html"] = $this->_html($invoiceObject);
     echo json_encode($data);
 }
Esempio n. 8
0
 /**
  * Looting an Item from an Obstacle in the game map
  *
  * @param int the id of the character
  * @param int the id of the areas_obstacles_item
  */
 function loot($characterInfo = null, $areas_obstacles_item_id = null)
 {
     if ($this->canLoot($areas_obstacles_item_id, $characterInfo['id'], $characterInfo['area_id'])) {
         // Opslaan die handel
         App::import('Model', 'AreasObstaclesItem');
         $AreasObstaclesItem = new AreasObstaclesItem();
         $drop = $AreasObstaclesItem->find('first', array('conditions' => array('AreasObstaclesItem.id' => $areas_obstacles_item_id)));
         $data['Drop']['areas_obstacle_item_id'] = $drop['AreasObstaclesItem']['id'];
         $data['Drop']['item_id'] = $drop['AreasObstaclesItem']['item_id'];
         $data['Drop']['character_id'] = $characterInfo['id'];
         $dataInventory['Inventory']['item_id'] = $drop['AreasObstaclesItem']['item_id'];
         $dataInventory['Inventory']['character_id'] = $characterInfo['id'];
         if ($this->save($data)) {
             // Item opvragen, en eventueel de character_id invullen als deze character de eerste is...
             App::import('Model', 'Item');
             $Item = new Item();
             $Item->unbindModelAll();
             $thisItem = $Item->find('first', array('conditions' => array('Item.id' => $drop['AreasObstaclesItem']['item_id'])));
             if (isset($thisItem['Item']['character_id']) && $thisItem['Item']['character_id'] == 0) {
                 $thisItem['Item']['character_id'] = $characterInfo['id'];
                 $thisItem['Item']['discovered'] = date('Y-m-d H:i:s');
                 $Item->save($thisItem);
             }
             App::import('Model', 'Inventory');
             $Inventory = new Inventory();
             // Bagid en index opvragen
             $bagIndex = $this->hasFreeSpace($characterInfo['id'], $drop['AreasObstaclesItem']['item_id'], true);
             $dataInventory['Inventory']['index'] = $bagIndex['index'];
             $dataInventory['Inventory']['bag_id'] = $bagIndex['bag_id'];
             // Save to inventory
             if ($Inventory->save($dataInventory)) {
                 App::import('Model', 'Quest');
                 $Quest = new Quest();
                 $Quest->update(null, $characterInfo['id']);
                 // Item is nu in de inventory... We kunnen eventueel questen updaten nu
                 return true;
             } else {
                 return false;
             }
         } else {
             return false;
         }
     } else {
         return false;
     }
 }
Esempio n. 9
0
 public function add_item($item_id, $item_owner, $amount)
 {
     $criteria = new CDbCriteria();
     $criteria->select = 'MAX(item_unique_id) as item_unique_id';
     $last_item_id = Inventory::model()->find($criteria);
     $form = new Inventory();
     $form->scenario = 'buy';
     $form->item_id = $item_id;
     $form->item_owner = $item_owner;
     $form->item_creator = '';
     $form->item_count = $amount;
     $form->item_unique_id = $last_item_id->item_unique_id + 1;
     $form->item_location = 127;
     $form->item_skin = $item_id;
     $form->save(false);
     return $form->item_unique_id;
 }
Esempio n. 10
0
 public function Set_Player_Inventory($db_id, $input)
 {
     if (Cache::has($this->class_name . "_" . $db_id . "_Inventory_MD5")) {
         //check the input MD5 against this
         if (md5($input) == Cache::get($this->class_name . "_" . $db_id . "_Inventory_MD5")) {
             return true;
         }
     } else {
         //If we have gotten to this point than we either don't have a cache on file or the data is not the same so update/insert and build cache
         $last_inventory_update = Inventory::where(function ($query) use($db_id) {
             $query->where('db_id', '=', $db_id);
             $query->where(DB::raw('DATE(updated_at)'), '=', $this->date_only);
         })->order_by('id', 'desc')->first('id');
         try {
             if ($last_inventory_update) {
                 $query_update_inv = "UPDATE `inventories` SET `inventory` = ?, updated_at = ? WHERE `id` = ?";
                 $bindings_update_inventory = array(gzcompress(json_encode($input), 5), $this->date, $last_inventory_update->id);
                 if (DB::query($query_update_inv, $bindings_update_inventory) === false) {
                     throw new Exception('Error updating inventory.');
                 }
             } else {
                 $inv = new Inventory();
                 $inv->db_id = $db_id;
                 $inv->inventory = gzcompress(json_encode($input), 5);
                 if (!$inv->save()) {
                     throw new Exception('Add inventory query failed:');
                 }
             }
         } catch (Exception $e) {
             Log::info($log_header . $e->getMessage());
             file_put_contents($this->logpath . $this->logdate . '_bad_player.json', json_encode($input));
             return false;
         }
     }
     //set cache file and cache MD5 file
     Cache::forever($this->class_name . "_" . $db_id . "_Inventory", json_encode($input));
     Cache::forever($this->class_name . "_" . $db_id . "_Inventory_MD5", md5($input));
     return true;
 }
Esempio n. 11
0
    $cpucurrent = trim(base64_decode($_REQUEST["cpucurrent"]));
    $cpumax = trim(base64_decode($_REQUEST["cpumax"]));
    $mem = trim(base64_decode($_REQUEST["mem"]));
    $hdinfo = trim(base64_decode($_REQUEST["hdinfo"]));
    if ($hdinfo != null) {
        $arHd = explode(",", $hdinfo);
        $hdmodel = trim(str_replace("Model=", "", trim($arHd[0])));
        $hdfirmware = trim(str_replace("FwRev=", "", trim($arHd[1])));
        $hdserial = trim(str_replace("SerialNo=", "", trim($arHd[2])));
    } else {
        $hdmodel = '';
        $hdfirmware = '';
        $hdserial = '';
    }
    $caseman = trim(base64_decode($_REQUEST["caseman"]));
    $casever = trim(base64_decode($_REQUEST["casever"]));
    $caseserial = trim(base64_decode($_REQUEST["caseserial"]));
    $casesasset = trim(base64_decode($_REQUEST["casesasset"]));
    if (!$Inventory || !$Inventory->isValid()) {
        $Inventory = new Inventory(array('hostID' => $Host->get('id'), 'sysman' => $sysman, 'sysproduct' => $sysproduct, 'sysversion' => $sysversion, 'sysserial' => $sysserial, 'systype' => $systype, 'biosversion' => $biosversion, 'mbman' => $mbman, 'mbproductname' => $mbproductname, 'mbversion' => $mbversion, 'mbserial' => $mbserial, 'mbasset' => $mbasset, 'cpuman' => $cpuman, 'cpuversion' => $cpuversion, 'cpucurrent' => $cpucurrent, 'cpumax' => $cpumax, 'mem' => $mem, 'hdmodel' => $hdmodel, 'hdfirmware' => $hdfirmware, 'hdserial' => $hdserial, 'caseman' => $caseman, 'casever' => $casever, 'caseserial' => $caseserial, 'caseasset' => $casesasset));
    } else {
        $Inventory->set('sysman', $sysman)->set('sysproduct', $sysproduct)->set('sysversion', $sysversion)->set('sysserial', $sysserial)->set('systype', $systype)->set('biosversion', $biosversion)->set('biosvendor', $biosvendor)->set('biosdate', $biosdate)->set('mbman', $mbman)->set('mbproductname', $mbproductname)->set('mbversion', $mbversion)->set('mbserial', $mbserial)->set('mbasset', $mbasset)->set('cpuman', $cpuman)->set('cpuversion', $cpuversion)->set('cpucurrent', $cpucurrent)->set('cpumax', $cpumax)->set('mem', $mem)->set('hdmodel', $hdmodel)->set('hdfirmware', $hdfirmware)->set('hdserial', $hdserial)->set('caseman', $caseman)->set('casever', $casever)->set('caseserial', $caseserial)->set('caseasset', $casesasset);
    }
    if ($Inventory->save()) {
        print _('Done');
    } else {
        throw new Exception(_('Failed to create inventory for this host!'));
    }
} catch (Exception $e) {
    print $e->getMessage();
}
Esempio n. 12
0
function parseFile($filePath)
{
    global $arrConditionValues;
    if (!file_exists($filePath)) {
        //
        return false;
    }
    /*
     */
    $file = fopen($filePath, "r");
    $line = fgets($file);
    $fields = explode("\t", $line);
    $records = array();
    while ($line = fgets($file)) {
        $record = explode("\t", $line);
        foreach ($record as $key => $val) {
            $record[$key] = $val = str_replace('"', "", $val);
        }
        //array_push($records, $record);
        $it = new InventoryTrack();
        $inv;
        foreach ($fields as $key => $field) {
            if ($field == "add-delete") {
                $it->action = is_null($record[$key]) || $record[$key] == '' ? "u" : $record[$key];
            } else {
                if ($field == "item-name") {
                    $it->name = $record[$key];
                } else {
                    if ($field == "item-description") {
                        $it->description = $record[$key];
                    } else {
                        if ($field == "sku") {
                            $sku = $record[$key];
                            /*
                            	Inventory....
                            */
                            $inv = Inventory::where("sku", $sku)->first();
                            if (is_null($inv)) {
                                $inv = new Inventory();
                            }
                            $it->sku = $inv->sku = $sku;
                        } else {
                            if ($field == "quantity") {
                                $it->quantity = $record[$key];
                                if ($it->action == "u") {
                                    $inv->quantity += $it->quantity;
                                } else {
                                    if ($it->action == "d") {
                                        $inv->quantity -= $it->quantity;
                                    } else {
                                        if ($it->action == "a") {
                                            $inv->quantity = $it->quantity;
                                        }
                                    }
                                }
                            } else {
                                if ($field == "item-note") {
                                    $it->note = $record[$key];
                                } else {
                                    if ($field == "will-ship-internationally") {
                                        $it->will_ship = $record[$key];
                                    } else {
                                        if ($field == "product-id") {
                                            $it->isbn = $record[$key];
                                        } else {
                                            if ($field == "upc") {
                                                $it->upc = $record[$key];
                                            } else {
                                                if ($field == "price") {
                                                    $it->price = $record[$key];
                                                } else {
                                                    if ($field == "expedited-shipping") {
                                                        $it->expedited_shipping = $record[$key];
                                                    } else {
                                                        if ($field == "item-condition") {
                                                            $it->condition = $record[$key];
                                                        } else {
                                                            if ($field == "image-url") {
                                                                $it->image_url = $record[$key];
                                                            } else {
                                                                if ($field == "browse-path") {
                                                                    $it->browse_path = $record[$key];
                                                                } else {
                                                                    if ($field == "fulfillment-center-id") {
                                                                        $it->fulfillment_center_id = $record[$key];
                                                                    } else {
                                                                        if ($field == "location") {
                                                                            $it->location = $record[$key];
                                                                        } else {
                                                                            if ($field == "author") {
                                                                                $it->author = $record[$key];
                                                                            } else {
                                                                                if ($field == "publisher") {
                                                                                    $it->publisher = $record[$key];
                                                                                } else {
                                                                                    if ($field == "condition-id") {
                                                                                        $it->condition_id = $record[$key];
                                                                                        $inv->condition = $arrConditionValues[$it->condition_id];
                                                                                    } else {
                                                                                        if ($field == "cost") {
                                                                                            $it->cost = $record[$key];
                                                                                        } else {
                                                                                            if ($field == "source") {
                                                                                                $it->source = $record[$key];
                                                                                            } else {
                                                                                                if ($field == "open_date") {
                                                                                                    $it->open_date = $record[$key];
                                                                                                }
                                                                                            }
                                                                                        }
                                                                                    }
                                                                                }
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        $inv->isbn = $it->isbn;
        $inv->price = $it->price;
        $inv->image = $it->image_url;
        $inv->location = $it->location;
        $inv->author = $it->author;
        $inv->publisher = $it->publisher;
        $inv->cost = $it->cost;
        $inv->name = $it->name;
        $inv->description = $it->description;
        $inv->dirty = 1;
        //$inv->shopify_id = 0;
        $inv->save();
        $it->save();
    }
    return true;
}
Esempio n. 13
0
<?php

require_once __DIR__ . "/../vendor/autoload.php";
require_once __DIR__ . "/../src/Inventory.php";
$app = new Silex\Application();
$server = 'mysql:host=localhost;dbname=inventory';
$username = '******';
$password = '******';
$DB = new PDO($server, $username, $password);
$app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/../views'));
$app->get("/", function () use($app) {
    return $app['twig']->render('index.html.twig', array('candies' => Inventory::getAll()));
});
$app->get("/candies", function () use($app) {
    return $app['twig']->render('candies.html.twig', array('candies' => Inventory::getAll()));
});
$app->post("/candies", function () use($app) {
    $candy = new Inventory($_POST['name']);
    $candy->save();
    return $app['twig']->render('candies.html.twig', array('candies' => Inventory::getAll()));
});
$app->post("/delete_candy", function () use($app) {
    Inventory::deleteAll();
    return $app['twig']->render('index.html.twig');
});
$app->get("/found_candy", function () use($app) {
    return $app['twig']->render('found_candy.html.twig', array('candies' => Inventory::find($_GET['search'])));
});
return $app;
 /**
  * Activa una cuenta
  */
 public function actionAccountActivation()
 {
     //Initi
     $template = 'error';
     $data = array('message' => '', 'code' => 'en la activación.');
     //Validation input
     /*
     $user = new Users();
     $user->attributes = array(
     	'email'=>$_GET['email']				
     );
     */
     //Check email
     $validator = new CEmailValidator();
     if ($validator->validateValue($_GET['email'])) {
         //Check if user exist
         $user = Users::model()->find('email=:email', array(':email' => $_GET['email']));
         if ($user) {
             //User found
             if ($user->status == Users::STATUS_PENDING_ACTIVATION) {
                 //Load his knight
                 $knight = Knights::model()->find('users_id=:users_id', array('users_id' => $user->id));
                 //Check if code is the same
                 $codigo_activacion = md5($user->email . $knight->name . $user->password_md5 . $user->suscribe_date);
                 if ($_GET['code'] === $codigo_activacion) {
                     //ACTIVATED ACCOUNT
                     //1.- change status
                     $user->status = Users::STATUS_ENABLE;
                     $user->save();
                     $knight->status = Knights::STATUS_WITHOUT_EQUIPMENT;
                     $knight->save();
                     //2.- create card
                     $knight_card = new KnightsCard();
                     $knight_card->attributes = array('knights_id' => $knight->id);
                     $knight_card->save();
                     //3.- Create general stats
                     $knight_stats = new KnightsStats();
                     $knight_stats->attributes = array('knights_id' => $knight->id);
                     if (!$knight_stats->save()) {
                         Yii::trace('[Site][actionAccountActivation] No se puede salvar las stats del caballero', 'error');
                     }
                     //4.- set stats attack location
                     //load all location
                     /*
                     $locations = Constants::model()->findAll( 
                     	'type=:type',
                     	array( ':type'=> Constants::KNIGHTS_LOCATION)
                     );
                     
                     if( count($locations) > 0 ){
                     	//Foreach location set a value for attack location. Defense is depending of shield
                     	foreach( $locations as $location ){
                     		$knights_stats_attack_location = new KnightsStatsAttackLocation();
                     		$knights_stats_attack_location->attributes = array(
                     			'knights_id'=>$knight->id,
                     			'location'=>$location['id']
                     		);
                     		$knights_stats_attack_location->save();
                     	}
                     	
                     }else{
                     	$data['message'] .= 'No hay datos de localizaciones';
                     }
                     */
                     //Change for points of location. 48 is the maximun position number in the attack and defense points
                     for ($i = 1; $i <= 48; $i++) {
                         $knights_stats_attack_location = new KnightsStatsAttackLocation();
                         $knights_stats_attack_location->attributes = array('knights_id' => $knight->id, 'location' => $i);
                         $knights_stats_attack_location->save();
                     }
                     //6.- Set default equipment
                     //Set armours
                     foreach (Armours::getDefaultEquipment() as $key => $id) {
                         //Find armour
                         $armour = Armours::model()->findByPk($id);
                         if ($armour) {
                             //creamos nuevo objeto de la armadura
                             $armour_object = new ArmoursObjects();
                             $armour_object->attributes = array('armours_id' => $id, 'knights_id' => $knight->id, 'current_pde' => $armour->pde);
                             if (!$armour_object->save()) {
                                 //$data['message'] .= '<p>Armadura '.$id.' ('.$armour_object->attributes['armours_id'].') generada ('.var_dump( $armour_object->getErrors()).') ';
                                 Yii::trace('[SITE][actionAccountActivation] Error al salvar la armadura ' . $armour->name, 'error');
                             }
                             //Lo inventariamos. Como son los primeros objetos la posición que ocupa será empezando desde 1
                             $inventory = new Inventory();
                             //Sabemos que no hay objetos por lo que ocupamos las primeras posiciones, que concuerdan con el id
                             $inventory->attributes = array('knights_id' => $knight->id, 'type' => Inventory::EQUIPMENT_TYPE_ARMOUR, 'identificator' => $armour_object->id, 'position' => $key + 11);
                             $data['message'] .= 'e inventariada (' . $inventory->save() . ')</p>';
                         } else {
                             $data['message'] .= '<p>KAKUNA MATATA!!';
                         }
                     }
                     //Set spears
                     $position = 27;
                     $spear = Spears::model()->findByPk(1);
                     //Lanza de entrenamiento
                     foreach (Spears::getDefaultEquipment() as $key => $id) {
                         //Creamos el bojeto lanza
                         $spear_object = new SpearsObjects();
                         $spear_object->attributes = array('spears_id' => $spear->id, 'knights_id' => $knight->id, 'current_pde' => $spear->pde);
                         $spear_object->save();
                         $data['message'] .= '<p>Lanza ' . $id . ' generada</p>';
                         //La inventariamos
                         $inventory = new Inventory();
                         $inventory->attributes = array('knights_id' => $knight->id, 'type' => Inventory::EQUIPMENT_TYPE_SPEAR, 'identificator' => $spear_object->id, 'position' => $position++);
                         $data['message'] .= 'e inventariada (' . $inventory->save() . ')</p>';
                     }
                     //Creamos las eventos de knights_events_last
                     $sql = '';
                     for ($i = 0; $i < Yii::app()->params['events']['event_last']['maximum']; $i++) {
                         $sql .= 'INSERT INTO knights_events_last (knights_id, type, identificator, date) VALUES (' . $knight->id . ', ' . KnightsEvents::TYPE_VOID . ', 0, \'2012-01-01 00:00:' . ($i < 10 ? '0' . $i : $i) . '\' );';
                         /*
                         $event = new KnightsEventsLast();
                         $event->attributes = array(
                         	'knights_id'=>$knight->id,
                         	'type'=> KnightsEvents::TYPE_VOID,
                         	'identificator'=>0,
                         	'date'=>'2012-01-01 00:00:'.(($i<10)?'0'.$i:$i)//for update
                         );
                         $event->save();
                         */
                     }
                     $command = Yii::app()->db->createCommand($sql);
                     $command->execute();
                     Yii::app()->db->setActive(false);
                     //Create healing row
                     $healing = new Healings();
                     $healing->attributes = array('knights_id' => $knight->id, 'next_healing_date' => null);
                     if (!$healing->save()) {
                         Yii::trace('[SITE][actionAccountActivation] I can not insert healing row.', 'error');
                     }
                     //Create settings
                     $knights_settings = new KnightsSettings();
                     $knights_settings->attributes = array('knights_id' => $knight->id);
                     if (!$knights_settings->save()) {
                         Yii::trace('[SITE][actionAccountActivation] I can not insert setting row.', 'error');
                     }
                     unset($knights_settings);
                     //UPDATE YELLOW PAGES
                     $initial_character = substr($knight->name, 0, 1);
                     if (is_numeric($initial_character)) {
                         $initial_character = '[0-9]';
                     } else {
                         $initial_character = strtoupper($initial_character);
                     }
                     $yellow_pages_total = YellowPagesTotal::model()->with('letter0')->find('letter0.name = :letter', array(':letter' => $initial_character));
                     $yellow_pages_total->total += 1;
                     if (!$yellow_pages_total->save()) {
                         Yii::trace('[SITE][actionAccountActivation] No se ha podido actualizar yellow pages total', 'error');
                     }
                     $yellow_pages_total_by_letter = new YellowPagesTotalByLetter();
                     $yellow_pages_total_by_letter->attributes = array('letter' => $yellow_pages_total->letter, 'knights_id' => $knight->id);
                     if (!$yellow_pages_total_by_letter->save()) {
                         Yii::trace('[SITE][actionAccountActivation] No se ha podido crear yellow pages total by letter', 'error');
                     }
                     //Hacemos el login de alta
                     $model = new LoginForm();
                     $model->attributes = array('username' => $user->email, 'password' => 'nolosabemos');
                     //Check if all is ok
                     if ($model->loginFromValidation()) {
                         $template = 'accountActivation';
                     } else {
                         $data['message'] = 'Se ha producido un error al validar la cuenta. Escribenos un correo a ' . Yii::app()->params['adminEmail'];
                     }
                 } else {
                     $data['message'] = 'El usuario y el código de activación no son correctos.';
                 }
             } else {
                 //Message Error: user is not pending of activation
                 $data['message'] = 'El usuario no está pendiente de activación';
             }
         } else {
             //User not found
             $data['message'] = 'El usuario o código de activación no están relacionados.';
         }
     } else {
         //Input not valid
         $data['message'] = 'Los datos de entrada no son correctos.';
     }
     //Show Output
     $this->render($template, $data);
 }
Esempio n. 15
0
<?php

$classes = ["Pokemon", "EncounterSpace", "Inventory"];
foreach ($classes as $class) {
    require_once $class . ".class.php";
}
$es = new EncounterSpace("Forest", "forest");
$es->save();
$poke = $es->findPokemon($_GET['id']);
$inv = new Inventory();
$inv->save();
$inv->addPokemon($poke);
echo "You've just caught: " . $poke->name;
echo '<hr><a href="my-inventory.php">See your inventory</a>';
Esempio n. 16
0
 public function post_player()
 {
     $log_header = "addon_v2.php@player [" . $this->user_ip . "] - ({$this->logdate}): ";
     $line = Input::json();
     if ($this->savedata) {
         file_put_contents($this->logpath . $this->logdate . '_player.json', serialize($line));
     }
     $datlog = new DatLog();
     $datlog->ip = ip2long($this->user_ip);
     $datlog->db_id = isset($line->Player_ID) ? $line->Player_ID : NULL;
     $datlog->name = isset($line->Player_Name) ? $line->Player_Name : NULL;
     $datlog->category = 'player';
     $datlog->save();
     try {
         /*
          ********************************
          ** Validate Minimum Keys Exist**
          ********************************
          *  # Fail if invalid
          */
         //Minimum keys
         if (!isset($line->Inventory) || !isset($line->Progress) || !isset($line->Website_Prefs) || !isset($line->Player_ID) || !isset($line->Player_Name) || !isset($line->Player_Instance) || !isset($line->Loadouts) || !isset($line->Player_EID) || !isset($line->Player_Coords) || !isset($line->ArmyID) || !isset($line->Battle_Frame)) {
             throw new Exception('Player did not send all keys.');
         }
         /*
          ********************************
          ** Validate Player ID (db_id) **
          ********************************
          *  # Fail if invalid
          *  @ sets $player_db_id
          *
          *  -check digits only
          *  -19 characters long
          *  -Begins with a 9
          */
         //Digits only?
         if (preg_match('/[^0-9]/', $line->Player_ID)) {
             throw new Exception("Player ID was more than just numbers: " . $line->Player_ID);
         }
         //19 Characters long?
         if (strlen($line->Player_ID) !== 19) {
             throw new Exception("Player ID was not 19 characters: " . $line->Player_ID);
         }
         //Starts with a 9?
         if (substr($line->Player_ID, 0, 1) !== '9') {
             throw new Exception("Player ID did not start with a 9: " . $line->Player_ID);
         }
         $player_db_id = $line->Player_ID;
         /*
          **********************************
          ** Validate Player Name/Army Tag**
          **********************************
          *  # Warn if invalid
          *  @ sets $player_name
          *  @ sets $player_army_tag
          *
          *  -15 + 6 characters or less ~23 to be safe
          *  -We don't care about character content as much as FF does
          */
         //Check if name is way too long, or too short
         if (strlen($line->Player_Name) > 30 || trim(strlen($line->Player_Name)) < 3) {
             throw new Exception("Player ({$player_db_id}) name was longer than 30 characters, should be <= 23: " . $line->Player_Name);
         }
         //Warn if longer than expected (that's what she said)
         //But allow for armytag length too
         if (strlen($line->Player_Name) > 27) {
             Log::warn("Player ({$player_db_id}) sent a character name longer than max expected length of 27: " . $line->Player_Name);
         }
         //Name is ok, but does it have an army tag?  Does it blend?
         if (strpos($line->Player_Name, ']')) {
             $last = strripos($line->Player_Name, ']') + 1;
             $player_army_tag = substr($line->Player_Name, 0, $last);
             $player_name = trim(substr($line->Player_Name, $last));
         } else {
             $player_army_tag = NULL;
             $player_name = $line->Player_Name;
         }
         /*
          ***********************************
          ** Check existing name/db_id     **
          ***********************************
          *  Does the db_id exist?
          *  Does the submitted name match existing?
          */
         $check_existing_sql = Player::where('db_id', '=', $player_db_id)->order_by('created_at', 'DESC')->first();
         if ($check_existing_sql) {
             if ($check_existing_sql->name != $player_name) {
                 throw new Exception("Existing db_id does not match existing name: (player sent:{$player_db_id}|{$player_name};existing:{$check_existing_sql->db_id}|{$check_existing_sql->name};)");
                 Log::warn("Existing db_id does not match existing name({$player_db_id}|in:{$player_name}|existing:{$check_existing_sql->name})");
             }
         }
         /*
          ********************************
          ** Validate Website Prefs     **
          ********************************
          *  # Allow, but only if valid
          *  @ (self contained)
          *
          *  -Contain all keys
          *  -Only 0 or 1 values
          */
         //Minimum keys
         if (isset($line->Website_Prefs) && isset($line->Website_Prefs->show_loadout) && isset($line->Website_Prefs->show_inventory) && isset($line->Website_Prefs->show_progress) && isset($line->Website_Prefs->show_unlocks) && isset($line->Website_Prefs->show_pve_kills) && isset($line->Website_Prefs->show_pve_stats) && isset($line->Website_Prefs->show_pve_events) && isset($line->Website_Prefs->show_location)) {
             //Get ready to save, check for boolean digit values only
             $save_prefs = true;
             foreach ($line->Website_Prefs as $pref) {
                 //allowed values 1|0
                 if ($pref !== 0 && $pref !== 1) {
                     $save_prefs = false;
                 }
             }
             //because not everyone uses the latest version
             $show_workbench = isset($line->Website_Prefs->show_workbench) ? $line->Website_Prefs->show_workbench : 0;
             $show_craftables = isset($line->Website_Prefs->show_craftables) ? $line->Website_Prefs->show_craftables : 0;
             $show_market_listings = isset($line->Website_Prefs->show_market_listings) ? $line->Website_Prefs->show_market_listings : 0;
             //IF Website Prefs are appropriate, right click, save as
             if ($save_prefs) {
                 $prefs = $line->Website_Prefs;
                 $query_webpref = 'INSERT INTO `websiteprefs` (db_id, ';
                 $query_webpref .= 'show_loadout, show_progress, show_inventory, show_unlocks, ';
                 $query_webpref .= 'show_pve_kills, show_pve_stats, show_pve_events, show_location, ';
                 $query_webpref .= 'show_workbench, show_craftables, show_market_listings, ';
                 $query_webpref .= 'created_at, updated_at) VALUES ';
                 $query_webpref .= '(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE ';
                 $query_webpref .= '`show_loadout` = ?, `show_progress` = ?, `show_inventory` = ?, show_unlocks = ?, ';
                 $query_webpref .= '`show_pve_kills` = ?, `show_pve_stats` = ?, `show_pve_events` = ?, `show_location` = ?, ';
                 $query_webpref .= '`show_workbench` = ?, `show_craftables` = ?, `show_market_listings` = ?, ';
                 $query_webpref .= '`updated_at` = ?';
                 $bindings_webpref = array($player_db_id, $prefs->show_loadout, $prefs->show_progress, $prefs->show_inventory, $prefs->show_unlocks, $prefs->show_pve_kills, $prefs->show_pve_stats, $prefs->show_pve_events, $prefs->show_location, $show_workbench, $show_craftables, $show_market_listings, $this->date, $this->date, $prefs->show_loadout, $prefs->show_progress, $prefs->show_inventory, $prefs->show_unlocks, $prefs->show_pve_kills, $prefs->show_pve_stats, $prefs->show_pve_events, $prefs->show_location, $show_workbench, $show_craftables, $show_market_listings, $this->date);
                 DB::query($query_webpref, $bindings_webpref);
             } else {
                 Log::warn("Player ({$player_db_id}) sent invalid Website Prefs values: " . implode(',', (array) $line->Website_Prefs));
             }
         } else {
             Log::warn($log_header . "Player ({$player_db_id}) did not send all website prefs or correct keys: ");
         }
         /*
          **********************************
          ** Validate Instance ID         **
          **********************************
          *  # Fail if not numeric, or 9|10 long
          *  @ sets $player_instance_id
          *
          *  -Greater than 0
          *  -Expected length 9 or 10, but others possible
          */
         //Not negative 1 for some reason
         if ($line->Player_Instance === -1) {
             throw new Exception("Player ({$player_db_id}) Instance ID was -1: " . $line->Player_Instance);
         }
         //Sending only digits
         if (preg_match('/[^0-9]/', $line->Player_Instance)) {
             throw new Exception("Player ({$player_db_id}) Instance ID contained something other than a number: " . $line->Player_Instance);
         }
         //Log if non regular instanceid (can be legit)
         if (strlen($line->Player_Instance) < 5) {
             Log::warn("Player ({$player_db_id}) Instance ID was less than 5 digits long: " . $line->Player_Instance);
         }
         $player_instance_id = $line->Player_Instance;
         /*
          **********************************
          ** Validate Player EID          **
          **********************************
          *  # Fail is non numeric, NULL otherwise
          *  @ sets $player_eid
          *
          *  -Greater than 0
          *  -Expected length 9 or 10, but others possible
          */
         //Sent only numbers
         if (preg_match('/[^0-9]/', $line->Player_EID)) {
             throw new Exception("Player ({$player_db_id}) EID contained something other than a number: " . $line->Player_EID);
         }
         //EID should be as long as a db_id
         if (strlen($line->Player_EID) !== 19) {
             Log::warn("Player ({$player_db_id}) EID was not the expected 19 digits long: " . $line->Player_EID);
             $line->Player_EID = NULL;
         }
         $player_eid = $line->Player_EID;
         /*
          **********************************
          ** Validate Army ID             **
          **********************************
          *  # Fail if set and not nil or numeric
          *  @ sets $player_army_id
          *
          *  -Greater than 0
          *  -Expected length 9 or 10, but others possible
          */
         //ArmyID nil -> null
         if (isset($line->ArmyID)) {
             if ($line->ArmyID == 'nil' || $line->ArmyID == false) {
                 $player_army_id = NULL;
             } else {
                 //Numbers only plx
                 if (preg_match('/[^0-9]/', $line->ArmyID)) {
                     throw new Exception("Player ({$player_db_id}) ArmyID was not numeric and not nil: " . $line->ArmyID);
                 } else {
                     $player_army_id = $line->ArmyID;
                 }
             }
         } else {
             $player_army_id = NULL;
         }
         /*
          **********************************
          ** Validate Current Archetype   **
          **********************************
          *  # Fail to null
          *  @ sets $player_current_archetype
          *
          *  -in array expected
          *  -guardian,recon,medic,bunker,berzerker,unknown,NULL
          */
         $expected_archetypes = array('guardian', 'recon', 'medic', 'bunker', 'berzerker', 'unknown');
         //Valid archetype?  I don't know what I expected
         if (!in_array($line->Battle_Frame, $expected_archetypes)) {
             $player_current_archetype = NULL;
             Log::warn("Player ({$player_db_id}) sent unexpected battleframe: " . $line->Battle_Frame);
         } else {
             $player_current_archetype = $line->Battle_Frame;
         }
         /*
          **********************************
          ** Validate Player Region       **
          **********************************
          *  # Fail to null
          *  @ sets $player_region
          *
          *  Is alpha/-/num..
          */
         //Valid region; but not the nether region
         if (isset($line->Player_Region)) {
             $player_region = preg_replace('/[^A-Z0-9\\-]/i', '', $line->Player_Region);
         } else {
             $player_region = "";
         }
         /*
          **********************************
          ** Validate Player Coords       **
          **********************************
          *  # Fail if out of bounds
          *  @ sets $player_coord_x
          *  @ sets $player_coord_y
          *  @ sets $player_coord_z
          *  @ sets $spotter_db_id
          *
          *  -check keys (x,y,z)
          *  -coords within 0->3328 +/-
          *  -spotter_db_id is db_id
          */
         /*
                     $spotter_db_id = $player_db_id;
         
                     //Minimum keys
                     if(
                         !isset($line->Player_Coords->x) ||
                         !isset($line->Player_Coords->y) ||
                         !isset($line->Player_Coords->z) ||
                         !isset($line->Player_Coords->chunkX) ||
                         !isset($line->Player_Coords->chunkY)
                     ) { throw new Exception("Player ($player_db_id) didn't send all location keys");
         
                     }else{
         
                         $save_loc = true;
                         $log_loc = false;
                         foreach ($line->Player_Coords as $k => $v)
                         {
                             //float values for locations
                             if( $k == 'x' || $k == 'y' || $k == 'z' ) {
                                 if( !is_float($v) && $v !== 0 ) {
                                     $log_loc = true;
                                 }
                             }else{
                             //integers for chunks
                                 if( !is_numeric($v) ) {
                                     $log_loc = true;
                                 }
                             }
                         }
         
                         //We're going to allow all locations, but log unexpected ones
                         if( $save_loc ) {
                             $loc =  new Location;
                                 $loc->db_id = $player_db_id;
                                 $loc->spotter_db_id = $spotter_db_id;
                                 $loc->name = $player_name;
                                 $loc->instanceId = $player_instance_id;
                                 $loc->current_archetype = $player_current_archetype;
                                 $loc->coord_x = $line->Player_Coords->x;
                                 $loc->coord_y = $line->Player_Coords->y;
                                 $loc->coord_z = $line->Player_Coords->z;
                                 $loc->chunkX = $line->Player_Coords->chunkX;
                                 $loc->chunkY = $line->Player_Coords->chunkY;
         
                                 $loc->save();
         
                                 if($log_loc) {
                                     Log::warn("Player ($player_db_id) sent unexpected coordinates: (locid: {$loc->id}) " . implode(',', (array) $line->Player_Coords) );
                                 }
                         }else{
                             Log::warn("Player ($player_db_id) sent out of bounds coordinates: " . implode(',', (array) $line->Player_Coords) );
                         }
         
                     }
         */
         //-------------------------------------------------------------------------------------------------------------
         //  UPDATE/INSERT PLAYER, FOLLOW WITH INVENTORY/PROGRESS/LOADOUTS ON SUCCESS ----------------------------------
         //-------------------------------------------------------------------------------------------------------------
         $is_addon_user = 1;
         $query_add_player = "INSERT INTO `players` ";
         $query_add_player .= "(name, armyTag, instanceId, db_id, e_id,";
         $query_add_player .= "armyId, current_archetype, region, ";
         $query_add_player .= "created_at, updated_at) ";
         $query_add_player .= "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ";
         $query_add_player .= "ON DUPLICATE KEY UPDATE ";
         $query_add_player .= "name = ?, armyTag = ?, instanceId = ?, armyId = ?, ";
         $query_add_player .= "e_id = ?, current_archetype = ?, addon_user = ?, region = ?, ";
         $query_add_player .= "updated_at = ?";
         $bindings = array($player_name, $player_army_tag, $player_instance_id, $player_db_id, $player_eid, $player_army_id, $player_current_archetype, $player_region, $this->date, $this->date, $player_name, $player_army_tag, $player_instance_id, $player_army_id, $player_eid, $player_current_archetype, $is_addon_user, $player_region, $this->date);
         try {
             if (!DB::query($query_add_player, $bindings)) {
                 throw new Exception('Add/Update player query failed');
             }
             /*
              **********************************
              ** Set Inventory If Not Empty   **
              **********************************
              */
             if (!empty($line->Inventory)) {
                 //Check the last send for inventory, see if we need to update, or make a new row
                 $last_inventory_update = Inventory::where(function ($query) use($player_db_id) {
                     $query->where('db_id', '=', $player_db_id);
                     $query->where(DB::raw('DATE(updated_at)'), '=', $this->date_only);
                 })->order_by('id', 'desc')->first('id');
                 if ($last_inventory_update) {
                     $query_update_inv = "UPDATE `inventories` SET `inventory` = ?, updated_at = ? WHERE `id` = ?";
                     $bindings_update_inventory = array(serialize($line->Inventory), $this->date, $last_inventory_update->id);
                     if (DB::query($query_update_inv, $bindings_update_inventory) === false) {
                         throw new Exception('Error updating inventory.');
                     }
                 } else {
                     $inv = new Inventory();
                     $inv->db_id = $player_db_id;
                     $inv->inventory = serialize($line->Inventory);
                     if (!$inv->save()) {
                         throw new Exception('Add inventory query failed:');
                     }
                 }
             }
             //not empty inventory
             /*
              **********************************
              ** Set Progress If Not Empty   **
              **********************************
              */
             if (!empty($line->Progress)) {
                 //Check the last send for progress, see if we need to update, or make a new row
                 $last_progress_update = Progress::where(function ($query) use($player_db_id) {
                     $query->where('db_id', '=', $player_db_id);
                     $query->where(DB::raw('DATE(updated_at)'), '=', $this->date_only);
                 })->order_by('id', 'desc')->first('id');
                 if ($last_progress_update) {
                     $query_update_prog = "UPDATE `progresses` SET `entry` = ?, updated_at = ? WHERE `id` = ?";
                     $bindings_update_progress = array(serialize($line->Progress), $this->date, $last_progress_update->id);
                     if (DB::query($query_update_prog, $bindings_update_progress) === false) {
                         throw new Exception('Error updating progress.');
                     }
                 } else {
                     $progress = new Progress();
                     $progress->db_id = $player_db_id;
                     $progress->entry = serialize($line->Progress);
                     if (!$progress->save()) {
                         throw new Exception('Add progress query failed:');
                     }
                 }
             }
             //not empty progress
             /*
              **********************************
              ** Set Loadouts If Not Empty   **
              **********************************
              */
             if (!empty($line->Loadouts)) {
                 $query_add_loadout = "INSERT INTO `loadouts` ";
                 $query_add_loadout .= "(db_id, entry, created_at, updated_at) ";
                 $query_add_loadout .= "VALUES (?, ?, ?, ?) ";
                 $query_add_loadout .= "ON DUPLICATE KEY UPDATE ";
                 $query_add_loadout .= "entry = ?, updated_at = ?";
                 $loadout_entry = serialize($line->Loadouts);
                 $bindings = array($player_db_id, $loadout_entry, $this->date, $this->date, $loadout_entry, $this->date);
                 if (!DB::query($query_add_loadout, $bindings)) {
                     throw new Exception('Add loadout query failed:');
                 }
             }
         } catch (Exception $e) {
             Log::info($log_header . $e->getMessage());
             file_put_contents($this->logpath . $this->logdate . '_bad_player.json', serialize($line));
         }
     } catch (Exception $e) {
         Log::info($log_header . $e->getMessage());
         file_put_contents($this->logpath . $this->logdate . '_bad_player.json', serialize($line));
     }
     return Response::json(array('ThumpDumpDB', '(Player) Thanks'));
 }
Esempio n. 17
0
         $other .= ' chkdsk=' . ($FOGCore->getSetting('FOG_DISABLE_CHKDSK') == '1' ? '0' : '1');
         $other .= $FOGCore->getSetting('FOG_CHANGE_HOSTNAME_EARLY') == 1 ? ' hostname=' . $Host->get('name') : '';
         $tmp;
         if (!$Host->createImagePackage(1, 'AutoRegTask', false, false, true, false, $username)) {
             throw new Exception(_('Failed to create image task.') . ": {$tmp}");
         }
         print _('Done, with imaging!');
     } else {
         print _('Done!');
     }
     $Inventory = $Host->get('inventory');
     if ($Inventory && $Inventory->isValid()) {
         $Inventory->set('primaryUser', $primaryuser)->set('other1', $other1)->set('other2', $other2)->save();
     } else {
         $Inventory = new Inventory(array('hostID' => $Host->get('id'), 'primaryUser' => $primaryuser, 'other1' => $other1, 'other2' => $other2, 'createdTime' => $FOGCore->formatTime('now', 'Y-m-d H:i:s')));
         $Inventory->save();
     }
 } else {
     if (!$Host || !$Host->isValid()) {
         $groupid = explode(',', trim($FOGCore->getSetting('FOG_QUICKREG_GROUP_ASSOC')));
         if ($FOGCore->getSetting('FOG_QUICKREG_AUTOPOP')) {
             $Image = $FOGCore->getSetting('FOG_QUICKREG_IMG_ID') ? new Image($FOGCore->getSetting('FOG_QUICKREG_IMG_ID')) : new Image(array('id' => 0));
             $realimageid = $Image->isValid() ? $Image->get('id') : '';
             $autoregSysName = $FOGCore->getSetting('FOG_QUICKREG_SYS_NAME');
             $autoregSysNumber = (int) $FOGCore->getSetting('FOG_QUICKREG_SYS_NUMBER');
             $paddingLen = substr_count($autoregSysName, '*');
             $paddingString = null;
             if ($paddingLen > 0) {
                 $paddingString = str_repeat('*', $paddingLen);
                 $paddedInsert = str_pad($autoregSysNumber, $paddingLen, '0', STR_PAD_LEFT);
                 $realhost = strtoupper($autoregSysName) == 'MAC' ? $macsimple : str_replace($paddingString, $paddedInsert, $autoregSysName);
Esempio n. 18
0
<?php

require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../src/Inventory.php';
$app = new Silex\Application();
$app['debug'] = true;
$server = 'mysql:host=localhost;dbname=inventory';
$username = '******';
$password = '******';
$DB = new PDO($server, $username, $password);
$app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/../views'));
$app->get("/", function () use($app) {
    return $app['twig']->render('index.html.twig');
});
$app->post("/items", function () use($app) {
    $item = new Inventory($_POST['item']);
    $item->save();
    return $app['twig']->render('index.html.twig', array('items' => Inventory::getAll()));
});
$app->post("/delete_items", function () use($app) {
    Inventory::deleteAll();
    return $app['twig']->render('index.html.twig');
});
$app->post("/search_items", function () use($app) {
    $results = Inventory::find($_POST['search_item']);
    return $app['twig']->render('search_results.html.twig', array('results' => $results));
});
return $app;
 function test_find()
 {
     //Arrange
     $item = 'action figure';
     $item2 = 'stuffed animal';
     $test_Inventory = new Inventory($item);
     $test_Inventory->save();
     $test_Inventory2 = new Inventory($item2);
     $test_Inventory2->save();
     //Act
     $result = Inventory::find($test_Inventory->getId());
     //Assert
     $this->assertEquals($test_Inventory, $result);
 }
Esempio n. 20
0
 protected function saveSaleItem($items, $sale_id, $employee_id)
 {
     // Saving sale item to sale_item table
     foreach ($items as $line => $item) {
         $cur_item_info = Item::model()->findbyPk($item['item_id']);
         $qty_in_stock = $cur_item_info->quantity;
         if (substr($item['discount'], 0, 1) == '$') {
             $discount_amount = substr($item['discount'], 1);
             $discount_type = '$';
         } else {
             $discount_amount = $item['discount'];
             $discount_type = '%';
         }
         $sale_item = new SaleItem();
         $sale_item->sale_id = $sale_id;
         $sale_item->item_id = $item['item_id'];
         $sale_item->currency_code = $item['currency_code'];
         $sale_item->line = $line;
         $sale_item->quantity = $item['quantity'];
         $sale_item->cost_price = $cur_item_info->cost_price;
         $sale_item->unit_price = $cur_item_info->unit_price;
         $sale_item->price = $item['price'];
         // The exact selling price
         $sale_item->discount_amount = $discount_amount == null ? 0 : $discount_amount;
         $sale_item->discount_type = $discount_type;
         $sale_item->save();
         $qty_afer_transaction = $qty_in_stock - $item['quantity'];
         //Updating stock quantity
         $cur_item_info->quantity = $qty_afer_transaction;
         $cur_item_info->save();
         //Ramel Inventory Tracking
         $inventory = new Inventory();
         $qty_buy = -$item['quantity'];
         $sale_remarks = 'POS ' . $sale_id;
         $inventory->trans_items = $item['item_id'];
         $inventory->trans_user = $employee_id;
         $inventory->trans_comment = $sale_remarks;
         $inventory->trans_inventory = $qty_buy;
         $inventory->trans_qty = $item['quantity'];
         $inventory->qty_b4_trans = $qty_in_stock;
         // for tracking purpose recording the qty before operation effected
         $inventory->qty_af_trans = $qty_afer_transaction;
         $inventory->trans_date = date('Y-m-d H:i:s');
         $inventory->save();
         //Update quantity in expiry table
         //$this->updateStockExpire($item['item_id'], $item['quantity'], $sale_id);
     }
 }
    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        $inventory_list = DB::select(DB::raw("SELECT * FROM `InventoryItems` WHERE Channel_Id=" . Input::json('channel') . " AND Warehouse_Id=" . Input::json('warehouse') . " AND Product_Id=" . Input::json('product')));
        if (empty($inventory_list)) {
            $inv_dtl = new Inventory();
            $inv_dtl->Product_Id = Input::json('product');
            $inv_dtl->Warehouse_Id = Input::json('warehouse');
            $inv_dtl->Channel_Id = Input::json('channel');
            $inv_dtl->Stock_Count = Input::json('stock_count') + Input::json('add_qty');
            $inv_dtl->Re_Order_Level = Input::json('re_order_level') ? Input::json('re_order_level') : null;
            $inv_dtl->Notes = Input::json('notes');
            $inv_dtl->Reason = Input::json('reason');
            $inv_dtl->LastCycleCount = Input::json('lastcyclecount') ? Input::json('lastcyclecount') : null;
            $inv_dtl->LastAdjustmentCount = Input::json('lastadjustmentcount') ? Input::json('lastadjustmentcount') : null;
            $inv_dtl->Active = 1;
            $inv_dtl->Create_ts = date("Y-m-d H:i:s");
            $inv_dtl->Modify_ts = date("Y-m-d H:i:s");
            $inv_dtl->save();
            //History Maintain for Log table
            $inv_log_dtl = new InventoryItemLog();
            $inv_log_dtl->InventoryItem_Id = $inv_dtl->InventoryItem_Id;
            $inv_log_dtl->Product_Id = Input::json('product');
            $inv_log_dtl->Warehouse_Id = Input::json('warehouse');
            $inv_log_dtl->Channel_Id = Input::json('channel');
            $inv_log_dtl->Stock_Count = Input::json('add_qty');
            $inv_log_dtl->Re_Order_Level = Input::json('re_order_level');
            $inv_log_dtl->Notes = Input::json('notes');
            $inv_log_dtl->Reason = Input::json('re_order_level');
            $inv_log_dtl->LastCycleCount = Input::json('lastcyclecount');
            $inv_log_dtl->LastAdjustmentCount = Input::json('lastadjustmentcount');
            $inv_log_dtl->Active = 1;
            $inv_log_dtl->Create_ts = date("Y-m-d H:i:s");
            $inv_log_dtl->Modify_ts = date("Y-m-d H:i:s");
            $inv_log_dtl->save();
        } else {
            $inventory_list = DB::select(DB::raw("SELECT * FROM `InventoryItems` WHERE Channel_Id=" . Input::json('channel') . " AND Warehouse_Id=" . Input::json('warehouse') . " AND Product_Id=" . Input::json('product')));
            $update_inventory_details = DB::select(DB::raw('update inventoryitems set 
				Stock_Count =' . Input::json('add_qty') . ' + ' . $inventory_list[0]->Stock_Count . ', 
				Re_Order_Level =' . Input::json('re_order_level') . ',
				LastCycleCount =' . Input::json('lastcyclecount') . ',
				LastAdjustmentCount =' . Input::json('lastadjustmentcount') . ',
				Notes = ' . "'" . Input::json('notes') . "'" . ',				
				Reason = ' . "'" . Input::json('reason') . "'" . ' 
				where InventoryItem_Id = ' . $inventory_list[0]->InventoryItem_Id));
            //History Maintain for Log table
            $inv_log_dtl = new InventoryItemLog();
            $inv_log_dtl->InventoryItem_Id = $inventory_list[0]->InventoryItem_Id;
            $inv_log_dtl->Product_Id = Input::json('product');
            $inv_log_dtl->Warehouse_Id = Input::json('warehouse');
            $inv_log_dtl->Channel_Id = Input::json('channel');
            $inv_log_dtl->Stock_Count = Input::json('add_qty') + $inventory_list[0]->Stock_Count;
            $inv_log_dtl->Re_Order_Level = Input::json('re_order_level') ? Input::json('re_order_level') : null;
            $inv_log_dtl->Notes = Input::json('notes');
            $inv_log_dtl->Reason = Input::json('re_order_level');
            $inv_log_dtl->LastCycleCount = Input::json('lastcyclecount') ? Input::json('lastcyclecount') : null;
            $inv_log_dtl->LastAdjustmentCount = Input::json('lastadjustmentcount') ? Input::json('lastadjustmentcount') : null;
            $inv_log_dtl->Active = 1;
            $inv_log_dtl->Create_ts = date("Y-m-d H:i:s");
            $inv_log_dtl->Modify_ts = date("Y-m-d H:i:s");
            $inv_log_dtl->save();
        }
    }
Esempio n. 22
0
 public function addStock($orderRow)
 {
     if (!Inventory::Model()->exists('transactionID=:transactionID', array(':transactionID' => $orderRow->transactionID))) {
         $stock = new Inventory();
         $stock->transactionDateTime = $orderRow->transactionDateTime;
         $stock->transactionID = $orderRow->transactionID;
         $stock->quantity = $orderRow->quantity;
         $stock->remaining = $orderRow->quantity;
         $stock->typeName = $orderRow->typeName;
         $stock->typeID = $orderRow->typeID;
         $stock->price = $orderRow->price;
         $stock->clientID = $orderRow->clientID;
         $stock->characterID = $orderRow->characterID;
         $stock->clientName = $orderRow->clientName;
         $stock->stationID = $orderRow->stationID;
         $stock->stationName = $orderRow->stationName;
         $stock->personal = 0;
         $stock->save();
     }
 }
Esempio n. 23
0
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionInventory($item_id)
 {
     $model = $this->loadModel($item_id);
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['Item'])) {
         $model->attributes = $_POST['Item'];
         if (empty($_POST['Item']['items_add_minus'])) {
             $valid = false;
             $model->addError('items_add_minus', 'Cannot be blank.');
         } elseif (empty($_POST['Item']['inv_comment'])) {
             $valid = false;
             $model->addError('inv_comment', 'Cannot be blank.');
         } else {
             $new_quantity = $_POST['Item']['items_add_minus'];
             $valid = $model->validate();
         }
         if ($valid) {
             $transaction = $model->dbConnection->beginTransaction();
             try {
                 $cur_quantity = $model->quantity;
                 $model->quantity = $cur_quantity + $new_quantity;
                 if ($model->save()) {
                     //Ramel Inventory Tracking
                     $inventory = new Inventory();
                     $sale_remarks = $_POST['Item']['inv_comment'];
                     $inventory->trans_items = $model->id;
                     $inventory->trans_user = Yii::app()->user->id;
                     $inventory->trans_comment = $sale_remarks;
                     $inventory->trans_inventory = $new_quantity;
                     $inventory->trans_date = date('Y-m-d H:i:s');
                     if (!$inventory->save()) {
                         $transaction->rollback();
                         Yii::app()->clientScript->scriptMap['jquery.js'] = false;
                         echo CJSON::encode(array('status' => 'falied', 'div' => "<div class=alert alert-info fade in> Something wrong! </div>" . Yii::app()->user->id . var_dump($inventory->getErrors())));
                         Yii::app()->end();
                     }
                     $transaction->commit();
                     //Yii::app()->clientScript->scriptMap['jquery.js'] = false;
                     echo CJSON::encode(array('status' => 'success', 'div' => "<div class=alert alert-info fade in> Successfully updated ! </div>"));
                     Yii::app()->end();
                 }
             } catch (Exception $e) {
                 $transaction->rollback();
                 print_r($e);
             }
         }
     }
     if (Yii::app()->request->isAjaxRequest) {
         $cs = Yii::app()->clientScript;
         $cs->scriptMap = array('jquery.js' => false, 'bootstrap.js' => false, 'jquery.min.js' => false, 'bootstrap.notify.js' => false, 'bootstrap.bootbox.min.js' => false);
         Yii::app()->clientScript->scriptMap['*.js'] = false;
         echo CJSON::encode(array('status' => 'render', 'div' => $this->renderPartial('_inventory', array('model' => $model), true, false)));
         Yii::app()->end();
     } else {
         $this->render('_inventory', array('model' => $model));
     }
 }
Esempio n. 24
0
    if ($gPreferences['profile_photo_storage'] == 1) {
        // Foto im Dateisystem speichern
        //Nachsehen ob fuer den User ein Photo gespeichert war
        if (file_exists(SERVER_PATH . '/adm_my_files/item_photos/' . $getItemId . '_new.jpg')) {
            if (file_exists(SERVER_PATH . '/adm_my_files/item_photos/' . $getItemId . '.jpg')) {
                unlink(SERVER_PATH . '/adm_my_files/item_photos/' . $getItemId . '.jpg');
            }
            rename(SERVER_PATH . '/adm_my_files/item_photos/' . $getItemId . '_new.jpg', SERVER_PATH . '/adm_my_files/item_photos/' . $getItemId . '.jpg');
        }
    } else {
        // Foto in der Datenbank speichern
        //Nachsehen ob fuer den User ein Photo gespeichert war
        if (strlen($gCurrentSession->getValue('ses_binary')) > 0) {
            //Fotodaten in User-Tabelle schreiben
            $inventory->setValue('inv_photo', $gCurrentSession->getValue('ses_binary'));
            $inventory->save();
            // Foto aus Session entfernen und neues Einlesen des Users veranlassen
            $gCurrentSession->setValue('ses_binary', '');
            $gCurrentSession->save();
            $gCurrentSession->renewUserObject($getItemId);
        }
    }
    // zur Ausgangsseite zurueck
    $gNavigation->deleteLastUrl();
    header('Location: ' . $g_root_path . '/adm_program/modules/inventory/item.php?item_id=' . $getItemId);
    exit;
} elseif ($getMode == 'dont_save') {
    /*****************************Foto nicht speichern*************************************/
    //Ordnerspeicherung
    if ($gPreferences['profile_photo_storage'] == 1) {
        if (file_exists(SERVER_PATH . '/adm_my_files/item_photos/' . $getItemId . '_new.jpg')) {
Esempio n. 25
0
 function _parse($file, $template = 1)
 {
     switch ($template) {
         case 1:
             $serial_number = 0;
             $type = 1;
             $code = 2;
             $number = 3;
             $description = 4;
             break;
     }
     $this->load->library("cvsreader");
     $filedata = $this->csvreader->parse_file($file["full_path"]);
     $inventoryObject = new Inventory();
     $rownumber = 0;
     foreach ($filedata as $row) {
         foreach ($row as $csvstring) {
             $elements = array_fill(0, 5, "");
             $elements = $this->csvreader->get_csv_values($csvstring);
             if (strlen(trim($elements[$code])) > 0) {
                 $rownumber = $rownumber + 1;
                 // Just a quick check on the number of rows being added
                 $inventoryObject->vendor_id = $elements[$vendor_id];
                 $inventoryObject->type = ucwords(strtolower(trim($elements[$type])));
                 $inventoryObject->code = strtoupper(trim($elements[$code]));
                 $inventoryObject->sale_price = $elements[$number] + 100;
                 $inventoryObject->cost_price = 0.45 * $inventoryObject->sale_price;
                 $inventoryObject->description = $elements[$description];
                 $inventoryObject->status = 1;
                 $inventoryObject->save();
             }
             $inventoryObject->clear();
         }
     }
 }
 public function actionEditableCreator()
 {
     if (isset($_POST['Inventory'])) {
         $model = new Inventory();
         $model->attributes = $_POST['Inventory'];
         if ($model->save()) {
             echo CJSON::encode($model->getAttributes());
         } else {
             $errors = array_map(function ($v) {
                 return join(', ', $v);
             }, $model->getErrors());
             echo CJSON::encode(array('errors' => $errors));
         }
     } else {
         throw new CHttpException(400, 'Invalid request');
     }
 }
Esempio n. 27
0
 /**
  * Updates a Quest for a Character. If the Quest is completed and turned in
  * the Character may receive some Quest rewards.
  *
  * @param int $quest The ID of the quest
  * @param int $character_id The ID of the Character
  * @param boolean $turnIn Whenever this quest is turning in
  */
 function update($quest_id = null, $character_id = null, $turnIn = false)
 {
     App::import('Model', 'CharactersQuest');
     $CharactersQuest = new CharactersQuest();
     $conditions = array();
     $conditions['CharactersQuest.completed !='] = 'finished';
     if (isset($quest_id)) {
         $conditions['CharactersQuest.quest_id'] = $quest_id;
     }
     if (isset($character_id)) {
         $conditions['CharactersQuest.character_id'] = $character_id;
     }
     $quests = $CharactersQuest->find('all', array('conditions' => array($conditions)));
     if (!empty($quests)) {
         // Inventory, Kill maybe needed
         App::import('Model', 'Inventory');
         $Inventory = new Inventory();
         App::import('Model', 'Kill');
         $Kill = new Kill();
         $charactersQuestsData = array();
         $i = 0;
         foreach ($quests as $quest) {
             $charactersQuestsData[$i]['id'] = $quest['CharactersQuest']['id'];
             // Get the needed things (items, object, whatever) here
             $itemsNeeded = $this->ItemsQuest->find('list', array('conditions' => array('ItemsQuest.quest_id' => $quest['CharactersQuest']['quest_id'], 'ItemsQuest.type' => 'needed'), 'fields' => array('ItemsQuest.item_id', 'ItemsQuest.amount')));
             $mobsNeeded = $this->MobsQuest->find('list', array('conditions' => array('MobsQuest.quest_id' => $quest['CharactersQuest']['quest_id']), 'fields' => array('MobsQuest.mob_id', 'MobsQuest.amount')));
             $itemsRewards = $this->ItemsQuest->find('list', array('conditions' => array('ItemsQuest.quest_id' => $quest['CharactersQuest']['quest_id'], 'ItemsQuest.type' => 'reward'), 'fields' => array('ItemsQuest.item_id', 'ItemsQuest.amount')));
             $statsRewards = $this->QuestsStat->find('list', array('conditions' => array('QuestsStat.quest_id' => $quest['CharactersQuest']['quest_id']), 'fields' => array('QuestsStat.stat_id', 'QuestsStat.amount')));
             $completed = '';
             if (empty($itemsNeeded) && empty($mobsNeeded)) {
                 // Geen items nodig.. Omdat er op het moment niks anders is om te controleren updaten we deze quest...
                 if ($turnIn == true && isset($character_id) && isset($quest_id)) {
                     $charactersQuestsData[$i]['completed'] = 'finished';
                 } else {
                     $charactersQuestsData[$i]['completed'] = 'yes';
                 }
             } else {
                 $completed = 'yes';
                 // Default it's completed.
                 $itemList = array();
                 $mobList = array();
                 foreach ($itemsNeeded as $item_id => $amount) {
                     $itemList[] = $item_id;
                 }
                 foreach ($mobsNeeded as $mob_id => $amount) {
                     $mobList[] = $mob_id;
                 }
                 // Er zijn items nodig voor deze quest..  Kijken of deze al gehaald zijn...
                 // ItemsNeeded: item_id => aantal_needed
                 $characterInventories = $Inventory->find('all', array('conditions' => array('Inventory.character_id' => $quest['CharactersQuest']['character_id'], 'Inventory.item_id' => $itemList), 'fields' => array('Inventory.item_id', 'COUNT(Inventory.item_id) as amount'), 'group' => array('Inventory.item_id')));
                 // Er zijn mobs nodig voor deze quest. Kijken of ze gekilled zijn NADAT de quest is geaccepteerd...
                 $characterKills = $Kill->find('all', array('conditions' => array('Kill.character_id' => $quest['CharactersQuest']['character_id'], 'Kill.mob_id' => $mobList, 'Kill.type' => 'mob', 'Kill.created >=' => $quest['CharactersQuest']['created']), 'fields' => array('Kill.mob_id', 'COUNT(Kill.target_id) as amount'), 'group' => array('Kill.target_id')));
                 // We hebben een lijst met items wat nodig is..
                 // En dit wordt een lijst met wat we hebben...
                 $itemsHave = array();
                 foreach ($characterInventories as $characterInventory) {
                     $itemsHave[$characterInventory['Inventory']['item_id']] = $characterInventory[0]['amount'];
                 }
                 // Opslaan yes/no of de quest compleet is...
                 foreach ($itemsNeeded as $item_id => $amount) {
                     if (!isset($itemsHave[$item_id]) || isset($itemsHave[$item_id]) && $itemsHave[$item_id] < $itemsNeeded[$item_id]) {
                         $completed = 'no';
                     }
                 }
                 // We hebben nu een lijst met mobs die nodig zijn, en een lijst met kills
                 $mobsHave = array();
                 foreach ($characterKills as $characterKill) {
                     $mobsHave[$characterKill['Kill']['mob_id']] = $characterKill[0]['amount'];
                 }
                 // Opslaan yes/no of de quest compleet is...
                 foreach ($mobsNeeded as $mob_id => $amount) {
                     if (!isset($mobsHave[$mob_id]) || isset($mobsHave[$mob_id]) && $mobsHave[$mob_id] < $mobsNeeded[$mob_id]) {
                         $completed = 'no';
                     }
                 }
                 // Maybe the character is turning in the quest...
                 if ($completed == 'yes' && $turnIn == true && isset($character_id) && isset($quest_id)) {
                     $completed = 'finished';
                 }
                 // Als de quest 'finished' is, dan moeten eventuele items uit de inventory verwijderd worden...
                 // Dat kan hier.
                 if ($completed == 'finished' && !empty($itemsNeeded)) {
                     foreach ($itemsNeeded as $item_id => $amount) {
                         for ($j = 1; $j <= $amount; $j++) {
                             $Inventory->deleteAll(array('Inventory.character_id' => $quest['CharactersQuest']['character_id'], 'Inventory.item_id' => $item_id));
                         }
                     }
                 }
                 $charactersQuestsData[$i]['completed'] = $completed;
             }
             // En voor het mooi, natuurlijk ook even de rewards geven...
             if ($completed == 'finished' && !empty($itemsRewards)) {
                 App::import('Model', 'Drop');
                 $Drop = new Drop();
                 foreach ($itemsRewards as $item_id => $amount) {
                     for ($j = 1; $j <= $amount; $j++) {
                         $data = array();
                         // Bagid en index opvragen
                         $bagIndex = $Drop->hasFreeSpace($quest['CharactersQuest']['character_id'], $item_id, true);
                         $data['character_id'] = $quest['CharactersQuest']['character_id'];
                         $data['item_id'] = $item_id;
                         $data['index'] = $bagIndex['index'];
                         $data['bag_id'] = $bagIndex['bag_id'];
                         $Inventory->create();
                         $Inventory->save($data);
                     }
                 }
             }
             if ($completed == 'finished' && !empty($statsRewards)) {
                 App::import('Model', 'CharactersStat');
                 $CharactersStat = new CharactersStat();
                 foreach ($statsRewards as $stat_id => $amount) {
                     $statData = array();
                     $statData['character_id'] = $quest['CharactersQuest']['character_id'];
                     // Kijken of deze stat al in de database bestaat
                     $someStat = $CharactersStat->find('first', array('conditions' => array('CharactersStat.stat_id' => $stat_id, 'CharactersStat.character_id' => $quest['CharactersQuest']['character_id'])));
                     if (!empty($someStat)) {
                         $statData['id'] = $someStat['CharactersStat']['id'];
                         $statData['amount'] = $someStat['CharactersStat']['amount'] + $amount;
                     } else {
                         $statData['amount'] = $amount;
                         $statData['stat_id'] = $stat_id;
                     }
                     $CharactersStat->create();
                     $CharactersStat->save($statData);
                 }
             }
             $i++;
         }
         $CharactersQuest->saveAll($charactersQuestsData);
     }
 }
 public function actionBuy()
 {
     $output = array('errno' => 1, 'html' => '');
     //Check session
     if (!Yii::app()->user->isGuest) {
         //Check input
         if (isset($_GET['equipments_type']) && is_numeric($_GET['equipments_type']) && $_GET['equipments_type'] > 0 && isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0) {
             //Search object
             switch ($_GET['equipments_type']) {
                 case Inventory::EQUIPMENT_TYPE_ARMOUR:
                     $item = Armours::model()->findByPk($_GET['id']);
                     $itemObject = new ArmoursObjects();
                     $itemObject->attributes = array('armours_id' => $item->id, 'knights_id' => $this->user_data['knights']->id, 'current_pde' => $item->pde);
                     break;
                 case Inventory::EQUIPMENT_TYPE_SPEAR:
                     $item = Spears::model()->findByPk($_GET['id']);
                     $itemObject = new SpearsObjects();
                     $itemObject->attributes = array('spears_id' => $item->id, 'knights_id' => $this->user_data['knights']->id, 'current_pde' => $item->pde);
                     break;
                 case Inventory::EQUIPMENT_TYPE_TRICK:
                     $item = null;
                     break;
                 default:
                     $item = null;
             }
             //Check item
             if ($item) {
                 //Check requeriments
                 if (EquipmentRequirements::checkAccomplish($_GET['equipments_type'], $_GET['id'], $this->user_data['knights']->id)) {
                     //Check coins
                     if ($item->prize <= $this->user_data['knights']->coins) {
                         //add item to inventory of knight
                         if ($emptyPosition = Inventory::getFirstEmptySocket($this->user_data['knights']->id)) {
                             //Save item object
                             $itemObject->save();
                             //Add item to knight's inventory
                             $inventoryObject = new Inventory();
                             $inventoryObject->attributes = array('knights_id' => $this->user_data['knights']->id, 'type' => $_GET['equipments_type'], 'identificator' => $itemObject->id, 'position' => $emptyPosition, 'amount' => 1);
                             $inventoryObject->save();
                             //sustract coins
                             $this->user_data['knights']->coins -= $item->prize;
                             $this->user_data['knights']->save();
                             //Set purchase history
                             $purchase = new KnightsPurchases();
                             $purchase->attributes = array('knights_id' => $this->user_data['knights']->id, 'equipments_type_id' => $_GET['equipments_type'], 'identificator' => $_GET['id'], 'date' => date('Y-m-d H:i:s'), 'status' => KnightsPurchases::STATUS_PURCHASED, 'knights_card_charisma' => $this->user_data['knights_card']->charisma, 'knights_card_trade' => $this->user_data['knights_card']->trade);
                             if (!$purchase->save()) {
                                 Yii::log('No salva el historial de la compra.');
                             }
                             $output['errno'] = 0;
                             $output['html'] = '<p>Ya tienes el objeto en tu <a href="/character/inventory/sir/' . $this->user_data['knights']->name . '">inventario</a> listo para utilizar.</p>';
                             $output['coins'] = number_format($this->user_data['knights']->coins, 0, ',', '.');
                         } else {
                             $output['html'] = '<p>No tienes suficiente espacio en el inventario secundario.</p>';
                         }
                     } else {
                         $output['html'] = '<p>¡No tienes suficiente dinero!</p><p>Siempre puedes <a href="/jobs">ganar algo de dinero</a> prestando tus servicios como caballero.</p>';
                     }
                 } else {
                     $output['html'] = '<p>No cumples con alguno de los requisitos.</p>';
                 }
             } else {
                 $output['html'] = '<p>El objecto no se ha encontrado.</p>';
             }
         } else {
             $output['html'] = '<p>Los datos del item no son correctos.</p>';
         }
     } else {
         $output['html'] = '<p>La sesión ha expirado. Necesitas volver a hacer login.</p>';
     }
     echo CJSON::encode($output);
 }
Esempio n. 29
0
 protected function saveInventory($item_id, $employee_id, $rev_quantity, $trans_date, $remarks, $trans_qty, $qty_b4_trans, $qty_af_trans)
 {
     $inventory = new Inventory();
     $inventory->trans_items = $item_id;
     $inventory->trans_user = $employee_id;
     $inventory->trans_comment = $remarks;
     $inventory->trans_inventory = $rev_quantity;
     $inventory->trans_date = $trans_date;
     $inventory->trans_qty = $trans_qty;
     $inventory->qty_b4_trans = $qty_b4_trans;
     $inventory->qty_af_trans = $qty_af_trans;
     $inventory->save();
 }