Пример #1
0
/**
 *  describe
 *
 *  Helper alias function for {@see \Cider\Spec\Runner::describe}.
 *
 *  @param string $specDescription
 *  @param callable $specContainer
 *
 *  @return void
 */
function describe(string $specDescription, callable $specContainer)
{
    $spec = new Spec();
    $spec->describe($specDescription);
    Runner::register($spec);
    return Runner::describe($specDescription, $specContainer);
}
Пример #2
0
 public function actionIndex()
 {
     Yii::app()->getModule('aud');
     Yii::app()->getModule('group');
     Yii::app()->getModule('lesson');
     Yii::app()->getModule('sch');
     Yii::app()->getModule('spec');
     Yii::app()->getModule('teacher');
     $schs = Sch::model()->findAll(array('order' => 'modified_time DESC', 'limit' => 100));
     $auds = Aud::model()->findAll(array('order' => 'updated_time DESC', 'limit' => 100));
     $specs = Spec::model()->findAll(array('order' => 'updated_time DESC', 'limit' => 100));
     $groups = Group::model()->findAll(array('order' => 'updated_time DESC', 'limit' => 100));
     $lessons = Lesson::model()->findAll(array('order' => 'updated_time DESC', 'limit' => 100));
     $teachers = Teacher::model()->findAll(array('order' => 'updated_time DESC', 'limit' => 100));
     $entries = $this->addEntries(array($auds, $specs, $groups, $lessons, $teachers));
     foreach ($schs as $value) {
         $entries[] = array('id' => $value->group_id, 'module' => strtolower(get_class($value)), 'time' => $value->modified_time . rand(100000, 999999), 'time' => $value->modified_time, 'user' => $value->modified_by, 'action' => 'update');
     }
     $entriesNew = array();
     foreach ($entries as $value) {
         $entriesNew[$value['time'] . rand(10000, 99999)] = $value;
     }
     krsort($entriesNew);
     $this->render('index', array('entries' => $entriesNew));
 }
Пример #3
0
 /**
  * @see Page::readData
  */
 public function readData()
 {
     parent::readData();
     //echo ".";
     $this->fleetQueue = new FleetQueue(0);
     $this->readTarget();
     $this->specs = Spec::getBySpecType(3);
     $this->fleets = Fleet::getByUserID(WCF::getUser()->userID);
     foreach ($this->fleets as $fleetID => $fleet) {
         $this->fleets[$fleetID]->navalFormation = NavalFormation::getByFleetID($fleetID);
     }
     // backlink
     if (isset($_REQUEST['backlink'])) {
         $this->backlink = StringUtil::trim($_REQUEST['backlink']);
     }
     $array = array();
     preg_match('/^(https?:\\/\\/[^\\/]*\\/)?(.*)$/i', $this->backlink, $array);
     $this->fleetQueue->backlink = $this->backlink = isset($array[2]) ? $array[2] : '';
     //echo ".";
     // TODO: clean this one up
     $sql = "DELETE FROM ugml_galactic_jump_queue\n\t\t\t\tWHERE userID = " . WCF::getUser()->userID;
     WCF::getDB()->registerShutdownUpdate($sql);
     $sql = "INSERT INTO ugml_galactic_jump_queue (userID, startPlanetID, state, time)\n\t\t\t\tVALUES(" . WCF::getUser()->userID . ", " . LWCore::getPlanet()->planetID . ", 1, " . TIME_NOW . ")";
     WCF::getDB()->registerShutdownUpdate($sql);
 }
Пример #4
0
 /**
  * @see FleetStartDirectFireAction::readParametersSpec()
  */
 public function readParametersSpec()
 {
     $system = new System($this->galaxy, $this->system);
     $planet = $system->getPlanet($this->planet, 2);
     $resources = $planet->metal + $planet->crystal;
     $recyclers = min(ceil($resources / 20000), Spec::getSpecObj(self::RECYCLER)->level);
     $this->spec[self::RECYCLER] = $recyclers;
 }
Пример #5
0
 public function run()
 {
     Spec::write("\n", true);
     //xdebug_start_code_coverage(XDEBUG_CC_UNUSED | XDEBUG_CC_DEAD_CODE);
     foreach ($this->files as $file) {
         require $file;
         Spec::setDescribeOutput($this->descriptiveOutput);
         Spec::run();
     }
     //xdebug_get_code_coverage();
     Spec::results();
 }
 /**
  * @see Form::readFormParameters()
  */
 public function readFormParameters()
 {
     parent::readFormParameters();
     $specs = Spec::getBySpecType(3);
     foreach ($specs as $specID => $specObj) {
         $shipCount = LWUtil::checkInt(@$_REQUEST['ship' . $specID], 0, $specObj->level);
         if ($shipCount) {
             $specObj->level = $shipCount;
             $this->specs[$specID] = clone $specObj;
             $this->ships[$specID] = $shipCount;
         }
     }
 }
Пример #7
0
 public function name($module = null, $id = null)
 {
     Yii::app()->getModule('aud');
     Yii::app()->getModule('group');
     Yii::app()->getModule('lesson');
     Yii::app()->getModule('sch');
     Yii::app()->getModule('spec');
     Yii::app()->getModule('teacher');
     $item = '';
     switch ($module) {
         case 'aud':
             if ($aud = Aud::model()->findByPk($id)) {
                 $item = $aud->name . ' (' . Yii::app()->params['aud_types'][$aud->type] . ')';
             }
             break;
         case 'group':
             if ($group = Group::model()->findByPk($id)) {
                 $item = $group->group_spec->code . '-' . $group->year . '-0' . $group->number . ' (' . $group->group_spec->name . ', ' . Yii::app()->sch->course($group->year) . ' курс)';
             }
             break;
         case 'lesson':
             if ($lesson = Lesson::model()->findByPk($id)) {
                 $item = isset($lesson->fullname) ? $lesson->fullname : $lesson->name;
             }
             break;
         case 'sch':
             if ($sch = Sch::model()->findByPk($id)) {
                 $item = $sch->group->groupName() . ' (' . $sch->group->group_spec->name . ', ' . Yii::app()->sch->course($sch->group->year) . ' курс)';
             }
             break;
         case 'spec':
             if ($spec = Spec::model()->findByPk($id)) {
                 $item = $spec->name;
             }
             break;
         case 'teacher':
             if ($teacher = Teacher::model()->findByPk($id)) {
                 $item = $teacher->surname . ' ' . $teacher->initials;
             }
             break;
         default:
             $item = '';
             break;
     }
     return $item;
 }
Пример #8
0
 /**
  * Calculates the capacity which can be used for harvest.
  *
  * @return	float	capacity
  */
 protected function getCapacity()
 {
     $fullCapacity = $otherCapacity = 0;
     foreach ($this->fleet as $specID => $shipCount) {
         if (!$shipCount) {
             continue;
         }
         $shipCapacity = Spec::getSpecVar($specID, 'capacity');
         if ($specID == 209) {
             $fullCapacity += $shipCount * $shipCapacity;
         } else {
             $otherCapacity += $shipCount * $shipCapacity;
         }
     }
     $free = $otherCapacity + $fullCapacity - $this->getRessources('all');
     $capacity = min($fullCapacity, $free);
     return $capacity;
 }
 /**
  * @see AbstractStatGenerator::generateEntries()
  */
 protected function generateEntries()
 {
     $this->generateDummies();
     // user subselect
     $specs = Spec::getByFlag(0x2, true);
     $generated = "";
     foreach ($specs as $specID => $specObj) {
         // planet
         if (!empty($generated)) {
             $generated .= " + ";
         }
         $generated .= "`" . $specObj->colName . "`";
     }
     $user = "******" . $generated . "\n\t\t\t\tFROM ugml_users\n\t\t\t\tWHERE ugml_users.id = ugml_stat_entry.relationalID";
     $sql = "UPDATE ugml_stat_entry,\n\t\t\t\t\tugml_users\n\t\t\t\t\t\tAS checkUser\n\t\t\t\tSET points = (" . $user . ")\n\t\t\t\tWHERE ugml_stat_entry.relationalID = checkUser.id\n\t\t\t\t\tAND ugml_stat_entry.statTypeID = " . $this->statTypeID . "\n\t\t\t\t\tAND checkUser.banned = 0\n\t\t\t\t\tAND checkUser.authlevel = 0";
     // lets go!
     WCF::getDB()->sendQuery($sql);
 }
Пример #10
0
function describe($name, $descriptionFunction)
{
    $oldActual = Spec::getActualExampleGroup();
    if (!$oldActual) {
        $newExampleGroup = \PSpec\ExampleSpec::buildExampleSpec($name);
        $specData = \PSpec\PSpec::getActualSpecData();
        $newExampleGroup->setSpecData($specData);
        Spec::setActualExampleGroup($newExampleGroup);
        $descriptionFunction();
        Spec::emptyActualExampleGroup();
        \PSpec\PSpec::addExampleGroupToActual($newExampleGroup);
    } else {
        $newExampleGroup = \PSpec\ExampleGroup::buildExampleGroup($name);
        $oldActual->addExample($newExampleGroup);
        Spec::setActualExampleGroup($newExampleGroup);
        $descriptionFunction();
        Spec::setActualExampleGroup($oldActual);
    }
}
 /**
  * @see AbstractStatGenerator::generateEntries()
  */
 protected function generateEntries()
 {
     $this->generateDummies();
     // planet subselect
     $specs = Spec::getByFlag(0x8, true);
     $generated = "";
     foreach ($specs as $specID => $specObj) {
         // planet
         if (!empty($generated)) {
             $generated .= " + ";
         }
         $generated .= "`" . $specObj->colName . "`";
     }
     $planet = "SELECT SUM(" . $generated . ")\r\n\t\t\t\tFROM ugml_planets\r\n\t\t\t\tWHERE ugml_planets.id_owner = ugml_stat_entry.relationalID";
     // fleet subselect
     $fleet = "SELECT COALESCE(SUM(shipCount), 0)\r\n\t\t\t\tFROM ugml_fleet\r\n\t\t\t\tLEFT JOIN ugml_fleet_spec\r\n\t\t\t\t\tON ugml_fleet.fleetID = ugml_fleet_spec.fleetID\r\n\t\t\t\tWHERE ugml_fleet.ownerID = ugml_stat_entry.relationalID";
     $sql = "UPDATE ugml_stat_entry,\r\n\t\t\t\t\tugml_users\r\n\t\t\t\t\t\tAS checkUser\r\n\t\t\t\tSET points = (" . $planet . ") + (" . $fleet . ")\r\n\t\t\t\tWHERE ugml_stat_entry.relationalID = checkUser.id\r\n\t\t\t\t\tAND ugml_stat_entry.statTypeID = " . $this->statTypeID . "\r\n\t\t\t\t\tAND checkUser.banned = 0\r\n\t\t\t\t\tAND checkUser.authlevel = 0";
     // lets go!
     WCF::getDB()->sendQuery($sql);
 }
Пример #12
0
    WOT Game is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    WOT Game is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with WOT Game.  If not, see <http://www.gnu.org/licenses/>.
*/
//fleetback.php
/*
define('INSIDE', true);
$ugamela_root_path = '../';
include($ugamela_root_path . 'extension.inc');
include($ugamela_root_path . 'common.'.$phpEx);
if(!check_user()){ header("Location: login.php"); die();}*/
define('WCF_DIR', 'G:\\workspace\\lw\\wcf\\');
require_once '../game/lib/util/LWUtil.class.php';
require_once '../game/lib/system/spec/Spec.class.php';
$a = array(1 => 2);
$b = array(1 => 3);
var_Dump(Spec::diff($a, $b));
var_Dump(array_diff_assoc($b, $a));
$data = '3:1~eJztXW2P3LYR/mwD/Q+LRdHagL0R9a6174o0TgvDeXEbp/lwCBY8ibernFZSKcn2xvBv7R/phw5fpJW00pKK4+aS6IAEu+TMaDgcDoePxku8ttfv4rXxBLMPBfxvGeESL+G7ZbIGb728SQgpnz9bPuHfAhuZBjLZt2C93MdFEWep6DXXS9OQHTkOb/GWNB1ewD4ga72M99BXfv6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WfkW7f8DKKug1RlQ/siA8l2BkyehySqlPxRLViIhdxlKnggkq14tdYFkRQw+gZEVQekERVZE4FMMWWu0PzOErIMGzxDyiIAZQp4h5LsOIY8n5voJ+eTjxcRT07Rj4FQI2feR7ZgrP0Ce4Z/Xtz4dsjqxlWMHHpwQdSBk2/CQEawC10euO4aqT4CROf2U2Nvb2kaI+vvlmO1ON+IRypM9coTuZG8cG8XJnnh2JLpbWh+VtzRQeY1/ItIVKkrkv2R+l6wXxqPFCxoXzZdntb+s+/8Uyvll0Py5RHyMci4RP+X73cP5c4n4KO1cIj5KOJeIzyXic4l4zTKXiM8l4sMsc4n4EMeM6M8l4lL6XCI+BdmfS8TnEvEZ3x+km/H93xi+P5eI/8pLxF0NMHpyibj3y4DKc4n4COVcIn7K97vHlOcS8WHauUR8nHAuEZ9LxOcS8SPHXCI+l4gPscwl4gMcM6B8V+DkuUS8Vn4uET+jzFwi3uObIeQZQh6hnyHk3t9cIj6XiHdsMpeI65eI+xqo/OQScfEr5NNLxOWvkz943t41Kf/R/zUs34cNdf1T5XH6GidxNPgb9vwXzgdA9QcnUm6aiKSiVCL2vZ9Fl5cYiZgirjDqEjQ3nsiV3u09W/l91bnSSCwjeaFRl65zrdGAW1x1rjZqC+q+BLrqXG8kAZLT+vWr7hVHMo6cvpK4kvccCeP0C8qv6suOJKjQezdw1brwaGhIo68KzrwaGH8V0Aqhvee0g2WvqxsWjQFTvqozhOOFSEMz3CXjdyINzV+frA+AXh0vRxrUKCfh6R5+dXpL0hDzcQWJi5IGJrp5AcLuGhma6oagf2HSqBOK25DEVMpLk8Y9sUMsLk4acseXYn9uXZ40RJX3jd3/hwW1+wpxnTuUBunaAutrlNrR5+F9nVva/PXyu69f8YX8ubiZrbmijTcWj85c4nbmqrb3/wO/fPAu';
$array = unserialize(LWUtil::unserialize($data));
var_dump($array);
Пример #13
0
$specs = Spec::getByFlag(0x2, true);
$generated = "";
foreach ($specs as $specID => $specObj) {
    if (!empty($generated)) {
        $generated .= " + ";
    }
    $costs = $specObj->costsMetal + $specObj->costsCrystal + $specObj->costsDeuterium;
    if ($specObj->costsFactor != 1) {
        $generated .= "(" . $costs . " * (1 - POW(" . $specObj->costsFactor . ", `" . $specObj->colName . "`)) / -(" . $specObj->costsFactor . " - 1))";
    } else {
        $generated .= "(" . $costs . " * `" . $specObj->colName . "`)";
    }
}
$sub2 = "SELECT " . $generated . "\r\n\t\tFROM ugml_users\r\n\t\tWHERE ugml_users.id = ugml_stat_entry.relationalID";
// sub3
$specs = Spec::getByFlag(0x8, true);
$generated = "";
foreach ($specs as $specID => $specObj) {
    /*if(!empty($generated)) {
    		$generated .= " + ";
    	}*/
    $costs = $specObj->costsMetal + $specObj->costsCrystal + $specObj->costsDeuterium;
    $generated .= " WHEN " . $specID . " THEN " . $costs;
    /*if($specObj->costsFactor != 1) {
    		$generated .= "(".$costs." * (1 - POW(".$specObj->costsFactor.", `".$specObj->colName."`)) / -(".$specObj->costsFactor." - 1))";
    	}
    	else {
    		$generated .= "(".$costs." * `".$specObj->colName."`)";
    	}*/
}
$sub3 = "SELECT COALESCE(SUM(CASE specID" . $generated . " ELSE 0 END * shipCount), 0)\r\n\t\tFROM ugml_fleet\r\n\t\tLEFT JOIN ugml_fleet_spec\r\n\t\t\tON ugml_fleet.fleetID = ugml_fleet_spec.fleetID\r\n\t\tWHERE ugml_fleet.ownerID = ugml_stat_entry.relationalID";
Пример #14
0
    public function actionAddReviewSpec($id)
    {

        $id = (int)$id;
        $review = Spec::model()->active()->findByPk($id);
        if(!$review)
            Yii::app()->end();
        if(isset($_POST['CommentSpec'])) {

            $model = new CommentSpec;
            $model->scenario = 'subcomment';
            $model->object_pk = $review->id;

            if(!Yii::app()->user->isGuest)
            {
                $model->user_id = Yii::app()->user->id;

            } else {

                 Yii::app()->end();
            }
            $model->setAttribute('status', CommentSpec::STATUS_APPROVED);
            $this->performAjaxValidation($model, 'comments-form');
                $model->attributes=$_POST['CommentSpec'];
            if(empty($model->id_parent))
                $model->id_parent = null;

            

            if($model->validate()){
                
                if($model->save()){
                    if(isset($_POST['type']) && $_POST['type']==1){
                        $this->renderPartial('_comment_super',array('model'=>$model,'supermodel'=>$review));
                    } else{
                        // $this->renderPartial('_comment',array('model'=>$model));
                    }
                    
                } 
                
            } 

        }
        Yii::app()->end();
    }
 function save_product($Product)
 {
     global $Shopp;
     $db = DB::get();
     check_admin_referer('shopp-save-product');
     if (!current_user_can(SHOPP_USERLEVEL)) {
         wp_die(__('You do not have sufficient permissions to access this page.'));
     }
     $this->settings_save();
     // Save workflow setting
     $base = $Shopp->Settings->get('base_operations');
     $taxrate = 0;
     if ($base['vat']) {
         $taxrate = $Shopp->Cart->taxrate();
     }
     if (!$_POST['options']) {
         $Product->options = array();
     } else {
         $_POST['options'] = stripslashes_deep($_POST['options']);
     }
     if (empty($Product->slug)) {
         $Product->slug = sanitize_title_with_dashes($_POST['name']);
     }
     // Check for an existing product slug
     $exclude_product = !empty($Product->id) ? "AND id != {$Product->id}" : "";
     $existing = $db->query("SELECT slug FROM {$Product->_table} WHERE slug='{$Product->slug}' {$exclude_product} LIMIT 1");
     if ($existing) {
         $suffix = 2;
         while ($existing) {
             $altslug = substr($Product->slug, 0, 200 - (strlen($suffix) + 1)) . "-{$suffix}";
             $existing = $db->query("SELECT slug FROM {$Product->_table} WHERE slug='{$altslug}' {$exclude_product} LIMIT 1");
             $suffix++;
         }
         $Product->slug = $altslug;
     }
     if (isset($_POST['content'])) {
         $_POST['description'] = $_POST['content'];
     }
     $Product->updates($_POST, array('categories'));
     $Product->save();
     $Product->save_categories($_POST['categories']);
     $Product->save_tags(explode(",", $_POST['taglist']));
     if (!empty($_POST['price']) && is_array($_POST['price'])) {
         // Delete prices that were marked for removal
         if (!empty($_POST['deletePrices'])) {
             $deletes = array();
             if (strpos($_POST['deletePrices'], ",")) {
                 $deletes = explode(',', $_POST['deletePrices']);
             } else {
                 $deletes = array($_POST['deletePrices']);
             }
             foreach ($deletes as $option) {
                 $Price = new Price($option);
                 $Price->delete();
             }
         }
         // Save prices that there are updates for
         foreach ($_POST['price'] as $i => $option) {
             if (empty($option['id'])) {
                 $Price = new Price();
                 $option['product'] = $Product->id;
             } else {
                 $Price = new Price($option['id']);
             }
             $option['sortorder'] = array_search($i, $_POST['sortorder']) + 1;
             // Remove VAT amount to save in DB
             if ($base['vat'] && $option['tax'] == "on") {
                 $option['price'] = number_format(floatnum($option['price']) / (1 + $taxrate), 2);
                 $option['saleprice'] = number_format(floatnum($option['saleprice']) / (1 + $taxrate), 2);
             }
             $Price->updates($option);
             $Price->save();
             if (!empty($option['download'])) {
                 $Price->attach_download($option['download']);
             }
             if (!empty($option['downloadpath'])) {
                 $basepath = trailingslashit($Shopp->Settings->get('products_path'));
                 $download = $basepath . ltrim($option['downloadpath'], "/");
                 if (file_exists($download)) {
                     $File = new Asset();
                     $File->parent = 0;
                     $File->context = "price";
                     $File->datatype = "download";
                     $File->name = basename($download);
                     $File->value = substr(dirname($download), strlen($basepath));
                     $File->size = filesize($download);
                     $File->properties = array("mimetype" => file_mimetype($download, $File->name));
                     $File->save();
                     $Price->attach_download($File->id);
                 }
             }
         }
         unset($Price);
     }
     // No variation options at all, delete all variation-pricelines
     if (empty($Product->options) && !empty($Product->prices) && is_array($Product->prices)) {
         foreach ($Product->prices as $priceline) {
             // Skip if not tied to variation options
             if ($priceline->optionkey == 0) {
                 continue;
             }
             $Price = new Price($priceline->id);
             $Price->delete();
         }
     }
     if (!empty($_POST['details']) || !empty($_POST['deletedSpecs'])) {
         $deletes = array();
         if (!empty($_POST['deletedSpecs'])) {
             if (strpos($_POST['deletedSpecs'], ",")) {
                 $deletes = explode(',', $_POST['deletedSpecs']);
             } else {
                 $deletes = array($_POST['deletedSpecs']);
             }
             foreach ($deletes as $option) {
                 $Spec = new Spec($option);
                 $Spec->delete();
             }
             unset($Spec);
         }
         if (is_array($_POST['details'])) {
             foreach ($_POST['details'] as $i => $spec) {
                 if (in_array($spec['id'], $deletes)) {
                     continue;
                 }
                 if (isset($spec['new'])) {
                     $Spec = new Spec();
                     $spec['id'] = '';
                     $spec['product'] = $Product->id;
                 } else {
                     $Spec = new Spec($spec['id']);
                 }
                 $spec['sortorder'] = array_search($i, $_POST['details-sortorder']) + 1;
                 $Spec->updates($spec);
                 if (preg_match('/^.*?(\\d+[\\.\\,\\d]*).*$/', $spec['content'])) {
                     $Spec->numeral = preg_replace('/^.*?(\\d+[\\.\\,\\d]*).*$/', '$1', $spec['content']);
                 }
                 $Spec->save();
             }
         }
     }
     if (!empty($_POST['deleteImages'])) {
         $deletes = array();
         if (strpos($_POST['deleteImages'], ",")) {
             $deletes = explode(',', $_POST['deleteImages']);
         } else {
             $deletes = array($_POST['deleteImages']);
         }
         $Product->delete_images($deletes);
     }
     if (!empty($_POST['images']) && is_array($_POST['images'])) {
         $Product->link_images($_POST['images']);
         $Product->save_imageorder($_POST['images']);
         if (!empty($_POST['imagedetails'])) {
             $Product->update_images($_POST['imagedetails']);
         }
     }
     do_action_ref_array('shopp_product_saved', array(&$Product));
     unset($Product);
     return true;
 }
 /**
  * Save Data: Defender Planet (saves the booty and lost ships)
  */
 protected function saveDataPlanet()
 {
     $levelArray = array();
     foreach ($this->lastRoundData['defenderData'][0] as $specID => $shipData) {
         $colName = Spec::getSpecVar($specID, 'colName');
         $count = $shipData['count'];
         if (isset($this->recreatedDefense[$specID])) {
             $count += $this->recreatedDefense[$specID];
         }
         $diff = $this->getTargetPlanet()->{$colName} - $count;
         $diff = -$diff;
         $levelArray[$specID] = $diff;
     }
     $this->getTargetPlanet()->getEditor()->changeLevel($levelArray);
     $this->getTargetPlanet()->getEditor()->changeResources(-$this->booty['metal'], -$this->booty['crystal'], -$this->booty['deuterium']);
 }
Пример #17
0
 /**
  * Changes the ships of a fleet.
  * 
  * @param	array	associative array
  */
 public function updateShips($ships)
 {
     $fleet = $this->fleet;
     $changedShips = Spec::diff($fleet, $ships);
     $inserts = "";
     $deletes = "";
     foreach ($changedShips as $specID => $shipCount) {
         // add/change
         if (!empty($specID)) {
             if ($shipCount > 0) {
                 if (!empty($inserts)) {
                     $inserts .= ",";
                 }
                 $inserts .= "(" . $this->fleetID . ", " . $specID . ", " . $shipCount . ")";
             } else {
                 if (!empty($deletes)) {
                     $deletes .= ",";
                 }
                 $deletes .= "(" . $this->fleetID . ", " . $specID . ")";
             }
         }
         if (!$shipCount) {
             unset($fleet[$specID]);
         } else {
             $fleet[$specID] = $shipCount;
         }
     }
     $this->fleet = $fleet;
     if (!empty($inserts)) {
         $sql = "REPLACE INTO ugml_fleet_spec\n\t\t\t\t\t(fleetID, specID, shipCount)\n\t\t\t\t\tVALUES " . $inserts;
         WCF::getDB()->sendQuery($sql);
     }
     if (!empty($deletes)) {
         $sql = "DELETE FROM ugml_fleet_spec\n\t\t\t\t\tWHERE (fleetID, specID) IN (" . $deletes . ")";
         WCF::getDB()->sendQuery($sql);
     }
     FleetLog::update($this->getObject());
 }
Пример #18
0
/**
 * This one's a bit dubious - it tests that an assertion made by the supplied
 * lambda fails. It primarily exists for self-testing the ztest library, and
 * using it causes the displayed assertion stats to be incorrect.
 */
function assert_fails($lambda, $msg = '')
{
    $caught = false;
    try {
        $lambda();
    } catch (ztest\AssertionFailed $e) {
        $caught = true;
        pass();
    }
    if (!$caught) {
        Spec::assert_fail();
        //throw new ztest\AssertionFailed($msg);
    }
}
Пример #19
0
 /**
  * Handles saving updates from the product editor
  *
  * Saves all product related information which includes core product data
  * and supporting elements such as images, digital downloads, tags,
  * assigned categories, specs and pricing variations.
  *
  * @author Jonathan Davis
  * @since 1.0
  *
  * @param Product $Product
  * @return void
  **/
 public function save(ShoppProduct $Product)
 {
     check_admin_referer('shopp-save-product');
     if (!current_user_can('shopp_products')) {
         wp_die(__('You do not have sufficient permissions to access this page.'));
     }
     ShoppSettings()->saveform();
     // Save workflow setting
     $status = $Product->status;
     // Set publish date
     if ('publish' == $_POST['status']) {
         $publishing = isset($_POST['publish']) ? $_POST['publish'] : array();
         $fields = array('month' => '', 'date' => '', 'year' => '', 'hour' => '', 'minute' => '', 'meridiem' => '');
         $publishdate = join('', array_merge($fields, $publishing));
         if (!empty($publishdate)) {
             $publish =& $_POST['publish'];
             if ($publish['meridiem'] == "PM" && $publish['hour'] < 12) {
                 $publish['hour'] += 12;
             }
             $publish = mktime($publish['hour'], $publish['minute'], 0, $publish['month'], $publish['date'], $publish['year']);
             $Product->status = 'future';
             unset($_POST['status']);
         } else {
             unset($_POST['publish']);
             // Auto set the publish date if not set (or more accurately, if set to an irrelevant timestamp)
             if ($Product->publish <= 86400) {
                 $Product->publish = null;
             }
         }
     } else {
         unset($_POST['publish']);
         $Product->publish = 0;
     }
     // Set a unique product slug
     if (empty($Product->slug)) {
         $Product->slug = sanitize_title($_POST['name']);
     }
     $Product->slug = wp_unique_post_slug($Product->slug, $Product->id, $Product->status, ShoppProduct::posttype(), 0);
     $Product->featured = 'off';
     if (isset($_POST['content'])) {
         $_POST['description'] = $_POST['content'];
     }
     $Product->updates($_POST, array('meta', 'categories', 'prices', 'tags'));
     do_action('shopp_pre_product_save');
     $Product->save();
     // Remove deleted images
     if (!empty($_POST['deleteImages'])) {
         $deletes = array();
         if (strpos($_POST['deleteImages'], ",") !== false) {
             $deletes = explode(',', $_POST['deleteImages']);
         } else {
             $deletes = array($_POST['deleteImages']);
         }
         $Product->delete_images($deletes);
     }
     // Update image data
     if (!empty($_POST['images']) && is_array($_POST['images'])) {
         $Product->link_images($_POST['images']);
         $Product->save_imageorder($_POST['images']);
         if (!empty($_POST['imagedetails'])) {
             $Product->update_images($_POST['imagedetails']);
         }
     }
     // Update Prices
     if (!empty($_POST['price']) && is_array($_POST['price'])) {
         // Delete prices that were marked for removal
         if (!empty($_POST['deletePrices'])) {
             $deletes = array();
             if (strpos($_POST['deletePrices'], ",")) {
                 $deletes = explode(',', $_POST['deletePrices']);
             } else {
                 $deletes = array($_POST['deletePrices']);
             }
             foreach ($deletes as $option) {
                 $Price = new ShoppPrice($option);
                 $Price->delete();
             }
         }
         $Product->resum();
         // Save prices that there are updates for
         foreach ($_POST['price'] as $i => $priceline) {
             if (empty($priceline['id'])) {
                 $Price = new ShoppPrice();
                 $priceline['product'] = $Product->id;
             } else {
                 $Price = new ShoppPrice($priceline['id']);
             }
             $priceline['sortorder'] = array_search($i, $_POST['sortorder']) + 1;
             $priceline['shipfee'] = Shopp::floatval($priceline['shipfee']);
             if (isset($priceline['recurring']['trialprice'])) {
                 $priceline['recurring']['trialprice'] = Shopp::floatval($priceline['recurring']['trialprice']);
             }
             if ($Price->stock != $priceline['stocked']) {
                 $priceline['stock'] = (int) $priceline['stocked'];
                 do_action('shopp_stock_product', $priceline['stock'], $Price, $Price->stock, $Price->stocklevel);
             } else {
                 unset($priceline['stocked']);
             }
             $Price->updates($priceline);
             $Price->save();
             // Save 'price' meta records after saving the price record
             if (isset($priceline['dimensions']) && is_array($priceline['dimensions'])) {
                 $priceline['dimensions'] = array_map(array('Shopp', 'floatval'), $priceline['dimensions']);
             }
             $settings = array('donation', 'recurring', 'membership', 'dimensions');
             $priceline['settings'] = array();
             foreach ($settings as $setting) {
                 if (!isset($priceline[$setting])) {
                     continue;
                 }
                 $priceline['settings'][$setting] = $priceline[$setting];
             }
             if (!empty($priceline['settings'])) {
                 shopp_set_meta($Price->id, 'price', 'settings', $priceline['settings']);
             }
             if (!empty($priceline['options'])) {
                 shopp_set_meta($Price->id, 'price', 'options', $priceline['options']);
             }
             $Product->sumprice($Price);
             if (!empty($priceline['download'])) {
                 $Price->attach_download($priceline['download']);
             }
             if (!empty($priceline['downloadpath'])) {
                 // Attach file specified by URI/path
                 if (!empty($Price->download->id) || empty($Price->download) && $Price->load_download()) {
                     $File = $Price->download;
                 } else {
                     $File = new ProductDownload();
                 }
                 $stored = false;
                 $tmpfile = sanitize_path($priceline['downloadpath']);
                 $File->storage = false;
                 $Engine = $File->engine();
                 // Set engine from storage settings
                 $File->parent = $Price->id;
                 $File->context = "price";
                 $File->type = "download";
                 $File->name = !empty($priceline['downloadfile']) ? $priceline['downloadfile'] : basename($tmpfile);
                 $File->filename = $File->name;
                 if ($File->found($tmpfile)) {
                     $File->uri = $tmpfile;
                     $stored = true;
                 } else {
                     $stored = $File->store($tmpfile, 'file');
                 }
                 if ($stored) {
                     $File->readmeta();
                     $File->save();
                 }
             }
             // END attach file by path/uri
         }
         // END foreach()
         unset($Price);
     }
     // END if (!empty($_POST['price']))
     $Product->load_sold($Product->id);
     // Refresh accurate product sales stats
     $Product->sumup();
     // Update taxonomies after pricing summary is generated
     // Summary table entry is needed for ProductTaxonomy::recount() to
     // count properly based on aggregate product inventory, see #2968
     foreach (get_object_taxonomies(Product::$posttype) as $taxonomy) {
         $tags = '';
         $taxonomy_obj = get_taxonomy($taxonomy);
         if (isset($_POST['tax_input']) && isset($_POST['tax_input'][$taxonomy])) {
             $tags = $_POST['tax_input'][$taxonomy];
             if (is_array($tags)) {
                 // array = hierarchical, string = non-hierarchical.
                 $tags = array_filter($tags);
             }
         }
         if (current_user_can($taxonomy_obj->cap->assign_terms)) {
             wp_set_post_terms($Product->id, $tags, $taxonomy);
         }
     }
     // Ensure taxonomy counts are updated on status changes, see #2968
     if ($status != $_POST['status']) {
         $Post = new StdClass();
         $Post->ID = $Product->id;
         $Post->post_type = ShoppProduct::$posttype;
         wp_transition_post_status($_POST['status'], $Product->status, $Post);
     }
     if (!empty($_POST['meta']['options'])) {
         $_POST['meta']['options'] = stripslashes_deep($_POST['meta']['options']);
     } else {
         $_POST['meta']['options'] = false;
     }
     // No variation options at all, delete all variation-pricelines
     if (!empty($Product->prices) && is_array($Product->prices) && (empty($_POST['meta']['options']['v']) || empty($_POST['meta']['options']['a']))) {
         foreach ($Product->prices as $priceline) {
             // Skip if not tied to variation options
             if ($priceline->optionkey == 0) {
                 continue;
             }
             if (empty($_POST['meta']['options']['v']) && $priceline->context == "variation" || empty($_POST['meta']['options']['a']) && $priceline->context == "addon") {
                 $Price = new ShoppPrice($priceline->id);
                 $Price->delete();
             }
         }
     }
     // Handle product spec/detail data
     if (!empty($_POST['details']) || !empty($_POST['deletedSpecs'])) {
         // Delete specs queued for removal
         $ids = array();
         $deletes = array();
         if (!empty($_POST['deletedSpecs'])) {
             if (strpos($_POST['deleteImages'], ",") !== false) {
                 $deletes = explode(',', $_POST['deleteImages']);
             } else {
                 $deletes = array($_POST['deletedSpecs']);
             }
             $ids = db::escape($_POST['deletedSpecs']);
             $Spec = new Spec();
             db::query("DELETE FROM {$Spec->_table} WHERE id IN ({$ids})");
         }
         if (is_array($_POST['details'])) {
             foreach ($_POST['details'] as $i => $spec) {
                 if (in_array($spec['id'], $deletes)) {
                     continue;
                 }
                 if (isset($spec['new'])) {
                     $Spec = new Spec();
                     $spec['id'] = '';
                     $spec['parent'] = $Product->id;
                 } else {
                     $Spec = new Spec($spec['id']);
                 }
                 $spec['sortorder'] = array_search($i, $_POST['details-sortorder']) + 1;
                 $Spec->updates($spec);
                 $Spec->save();
             }
         }
     }
     // Save any meta data
     if (isset($_POST['meta']) && is_array($_POST['meta'])) {
         foreach ($_POST['meta'] as $name => $value) {
             if (isset($Product->meta[$name])) {
                 $Meta = $Product->meta[$name];
                 if (is_array($Meta)) {
                     $Meta = reset($Product->meta[$name]);
                 }
             } else {
                 $Meta = new ShoppMetaObject(array('parent' => $Product->id, 'context' => 'product', 'type' => 'meta', 'name' => $name));
             }
             $Meta->parent = $Product->id;
             $Meta->name = $name;
             $Meta->value = $value;
             $Meta->save();
         }
     }
     $Product->load_data();
     // Reload data so everything is fresh for shopp_product_saved
     do_action_ref_array('shopp_product_saved', array(&$Product));
     unset($Product);
 }
 function duplicate()
 {
     $db =& DB::get();
     $this->load_data(array('prices', 'specs', 'categories', 'tags', 'images', 'taxes' => 'false'));
     $this->id = '';
     $this->name = $this->name . ' ' . __('copy', 'Shopp');
     $this->slug = sanitize_title_with_dashes($this->name);
     // Check for an existing product slug
     $existing = $db->query("SELECT slug FROM {$this->_table} WHERE slug='{$this->slug}' LIMIT 1");
     if ($existing) {
         $suffix = 2;
         while ($existing) {
             $altslug = substr($this->slug, 0, 200 - (strlen($suffix) + 1)) . "-{$suffix}";
             $existing = $db->query("SELECT slug FROM {$this->_table} WHERE slug='{$altslug}' LIMIT 1");
             $suffix++;
         }
         $this->slug = $altslug;
     }
     $this->created = '';
     $this->modified = '';
     $this->save();
     // Copy prices
     foreach ($this->prices as $price) {
         $Price = new Price();
         $Price->updates($price, array('id', 'product', 'created', 'modified'));
         $Price->product = $this->id;
         $Price->save();
     }
     // Copy sepcs
     foreach ($this->specs as $spec) {
         $Spec = new Spec();
         $Spec->updates($spec, array('id', 'product', 'created', 'modified'));
         $Spec->product = $this->id;
         $Spec->save();
     }
     // Copy categories
     $categories = array();
     foreach ($this->categories as $category) {
         $categories[] = $category->id;
     }
     $this->categories = array();
     $this->save_categories($categories);
     // Copy tags
     $taglist = array();
     foreach ($this->tags as $tag) {
         $taglist[] = $tag->name;
     }
     $this->tags = array();
     $this->save_tags($taglist);
     // // Copy product images
     $template = new Asset();
     $columns = array();
     $values = array();
     foreach ($template->_datatypes as $name => $type) {
         $colname = $name;
         $columns[$colname] = $name;
         if ($name == "id") {
             $name = "''";
         }
         if ($name == "parent") {
             $name = "'{$this->id}'";
         }
         if ($name == "created" || $name == "modified") {
             $name = "now()";
         }
         $values[$colname] = $name;
     }
     $sets = array('image', 'small', 'thumbnail');
     $images = array();
     foreach ($sets as $set) {
         foreach ($this->imagesets[$set] as $image) {
             if (isset($images[$image->src])) {
                 $values['src'] = $images[$image->src];
             }
             $id = $db->query("INSERT {$template->_table} (" . join(',', $columns) . ") SELECT " . join(",", $values) . " FROM {$template->_table} WHERE id={$image->id}");
             if ($set == "image") {
                 $images[$image->id] = $id;
                 $db->query("UPDATE {$template->_table} SET src={$id} WHERE id={$id} LIMIT 1");
             }
         }
     }
 }
Пример #21
0
 /**
  * Builds the data array.
  *
  * @param	Planet	planet
  */
 protected static function getData(Planet $planet)
 {
     Spec::storeData($planet);
     $data = array('specID' => $planet->b_building_id, 'level' => Spec::getSpecObj($planet->b_building_id)->level + 1, 'planetID' => $planet->planetID, 'planetName' => $planet->name, 'coords' => array($planet->galaxy, $planet->system, $planet->planet, $planet->planetKind));
     return $data;
 }
Пример #22
0
 /**
  * Adds the default specification to the Vehicle
  * @param Spec $specification
  */
 public function addDefSpec(Spec $specification)
 {
     $specName = $specification->getNameSpec();
     $isSpecAdded = array_key_exists($specName, $this->defaultSpecs);
     if (!$isSpecAdded) {
         $this->defaultSpecs[$specName] = $specification;
     } else {
         Helper::displayErrorMessage("The specification is already added to the vehicle");
     }
 }
Пример #23
0
 /**
  * Returns the level by a given spec id.
  * 
  * @param	int	specID
  * @param	int	level
  */
 public function getLevel($specID)
 {
     $colName = Spec::getSpecVar($specID, 'colName');
     return $this->{$colName};
 }
Пример #24
0
 /**
  * @see PlanetProduction::getChanges()
  */
 public function getChanges()
 {
     $return = array('b_hangar' => array(1), 'b_hangar_id' => array(1));
     foreach ($this->changes as $specID => $count) {
         $colName = Spec::getSpecVar($specID, 'colName');
         $return[$colName] = array(2, $count);
         unset($this->changes[$specID]);
     }
     //var_dump($return);
     return $return;
 }
Пример #25
0
 /**
  * Calculates the debris of the destroyed fleet
  */
 protected function calculateDebrisOfDestroyedFleet()
 {
     //TODO: dont use game_config
     global $game_config;
     foreach ($this->afterFightFleet as $specID => $shipCount) {
         $this->debris['metal'] += Spec::getSpecVar($specID, 'costsMetal') * $shipCount * $game_config['flota_na_zlom'] / 100;
         $this->debris['crystal'] += Spec::getSpecVar($specID, 'costsCrystal') * $shipCount * $game_config['flota_na_zlom'] / 100;
     }
 }
Пример #26
0
	function duplicate () {
		$db =& DB::get();

		$this->load_data(array('prices','specs','categories','tags','images','taxes'=>'false'));
		$this->id = '';
		$this->name = $this->name.' '.__('copy','Ecart');
		$this->slug = sanitize_title_with_dashes($this->name);

		// Check for an existing product slug
		$existing = $db->query("SELECT slug FROM $this->_table WHERE slug='$this->slug' LIMIT 1");
		if ($existing) {
			$suffix = 2;
			while($existing) {
				$altslug = substr($this->slug, 0, 200-(strlen($suffix)+1)). "-$suffix";
				$existing = $db->query("SELECT slug FROM $this->_table WHERE slug='$altslug' LIMIT 1");
				$suffix++;
			}
			$this->slug = $altslug;
		}
		$this->created = '';
		$this->modified = '';

		$this->save();

		// Copy prices
		foreach ($this->prices as $price) {
			$Price = new Price();
			$Price->updates($price,array('id','product','created','modified'));
			$Price->product = $this->id;
			$Price->save();
		}

		// Copy sepcs
		foreach ($this->specs as $spec) {
			$Spec = new Spec();
			$Spec->updates($spec,array('id','parent','created','modified'));
			$Spec->parent = $this->id;
			$Spec->save();
		}

		// Copy categories
		$categories = array();
		foreach ($this->categories as $category) $categories[] = $category->id;
		$this->categories = array();
		$this->save_categories($categories);

		// Copy tags
		$taglist = array();
		foreach ($this->tags as $tag) $taglist[] = $tag->name;
		$this->tags = array();
		$this->save_tags($taglist);

		// Copy product images
		foreach ($this->images as $ProductImage) {
			$Image = new ProductImage();
			$Image->updates($ProductImage,array('id','parent','created','modified'));
			$Image->parent = $this->id;
			$Image->save();
		}

	}
Пример #27
0
 /**
  * Destroys the espionage sondes if they get destroyed.
  */
 protected function destroy()
 {
     $shipCount = 0;
     Spec::storeData($this->getTargetPlanet(), false);
     $specs = Spec::getBySpecType(3, false);
     foreach ($specs as $specObj) {
         $shipCount += $specObj->level;
     }
     $this->destroyChance = pow($this->getOfiara()->spy_tech / $this->getOwner()->spy_tech, 5) * $this->fleet[210] * pow($shipCount, 0.2) / 10;
     $this->destroyChance = min($this->destroyChance, 100);
     $rand = rand(0, 99);
     if ($this->destroyChance > $rand) {
         $this->fight = true;
         $this->simulate();
         $this->generateReport();
     }
     $this->ereport .= WCF::getLanguage()->get('wot.mission.mission6.impact.owner.defenseChance', array('$defenseChance' => StringUtil::formatNumeric(round($this->destroyChance))));
 }
Пример #28
0
 /**
  * Prepares the data for simulation
  */
 protected function simulate()
 {
     // organize data
     foreach ($this->shipDataArray as $key => $value) {
         if (empty($value)) {
             continue;
         }
         $nfsSlotNo = intval(substr($key, 8, 2));
         $front = strtolower(substr($key, 10, 8));
         $isTech = strlen($key) > 21;
         $arrayName = $front . 'Fleets';
         if ($isTech) {
             $techID = substr($key, -3);
             $this->{$arrayName}[$nfsSlotNo]['tech'][$techID] = intval($value);
         } else {
             $techID = substr($key, -3);
             $this->{$arrayName}[$nfsSlotNo]['fleet'][$techID] = intval($value);
         }
     }
     if (!count($this->attackerFleets) || !count($this->defenderFleets)) {
         return;
     }
     // create objs
     foreach ($this->attackerFleets as $nfsSlotNo => $fleetData) {
         $fleetStr = LWUtil::serialize($fleetData['fleet']);
         $array = array('fleet' => Spec::arrayToStr($fleetData['fleet']), 'galaxy' => 0, 'system' => 0, 'planet' => 0, 'ownerID' => 0, 'targetPlanetID' => 0, 'fleetID' => 0, 'weaponTech' => $fleetData['tech'][109], 'shieldTech' => $fleetData['tech'][110], 'hullPlatingTech' => $fleetData['tech'][111]);
         $this->attackerFleetObjs[$nfsSlotNo] = new PhantomFleet(null, $array);
     }
     $simulatingFleetArray = $array;
     foreach ($this->defenderFleets as $nfsSlotNo => $fleetData) {
         $fleetStr = LWUtil::serialize($fleetData['fleet']);
         $array = array('fleet' => Spec::arrayToStr($fleetData['fleet']), 'galaxy' => 0, 'system' => 0, 'planet' => 0, 'ownerID' => 0, 'targetPlanetID' => 0, 'fleetID' => 0, 'weaponTech' => $fleetData['tech'][109], 'shieldTech' => $fleetData['tech'][110], 'hullPlatingTech' => $fleetData['tech'][111]);
         $this->defenderFleetObjs[$nfsSlotNo] = new PhantomFleet(null, $array);
     }
     // simulate
     set_time_limit(60);
     for ($i = 0; $i < self::SIMULATIONS; ++$i) {
         try {
             ob_start();
             $simulator = new CombatSimulator($this->attackerFleetObjs, $this->defenderFleetObjs, $simulatingFleetArray);
             $simulator->simulate();
             ob_clean();
         } catch (Exception $e) {
             message('Es ist ein fehler bei der Simulation aufgetreten!');
         }
         $this->unitsAttackerArray[$i] = $simulator->units['attacker'];
         $this->unitsDefenderArray[$i] = $simulator->units['defender'];
         $this->debrisMetalArray[$i] = $simulator->debris['metal'];
         $this->debrisCrystalArray[$i] = $simulator->debris['crystal'];
         $this->bootyArray[$i] = $simulator->totalCapacity;
         $this->roundNoArray[$i] = $simulator->roundNo;
         $this->winnerArray[$i] = $simulator->winner;
         // check extrema
         if ($i == 0) {
             //var_dump($simulator);
             $this->minSimulator = $this->maxSimulator = $simulator;
             continue;
         }
         // real best case: difference in attacker units
         $byAttackerUnits = $simulator->units['attacker'] < $this->minSimulator->units['attacker'];
         // unreal best case: no difference in attacker units, but more defender units
         $byDefenderUnits = $simulator->units['attacker'] == $this->minSimulator->units['attacker'] && $simulator->units['defender'] > $this->minSimulator->units['defender'];
         if ($byAttackerUnits || $byDefenderUnits) {
             $this->minSimulator = $simulator;
         }
         // real worst case: difference in attacker units
         $byAttackerUnits = $simulator->units['attacker'] > $this->maxSimulator->units['attacker'];
         // unreal worst case: no difference in attacker units, but less defender units
         $byDefenderUnits = $simulator->units['attacker'] == $this->maxSimulator->units['attacker'] && $simulator->units['defender'] < $this->maxSimulator->units['defender'];
         if ($byAttackerUnits || $byDefenderUnits) {
             $this->maxSimulator = $simulator;
         }
     }
     $simulator->generateReport();
     $report = CombatReport::create(time(), $simulator->report, false, array(WCF::getUser()->userID => WCF::getUser()->userID));
     $this->reportID = $report->reportID;
     // sum up (avg)
     $this->units['attacker'] = array_sum($this->unitsAttackerArray) / self::SIMULATIONS;
     $this->units['defender'] = array_sum($this->unitsDefenderArray) / self::SIMULATIONS;
     $this->debris['metal'] = array_sum($this->debrisMetalArray) / self::SIMULATIONS;
     $this->debris['crystal'] = array_sum($this->debrisCrystalArray) / self::SIMULATIONS;
     $this->booty = array_sum($this->bootyArray) / self::SIMULATIONS;
     $this->roundNo = array_sum($this->roundNoArray) / self::SIMULATIONS;
     // sum up (min)
     $this->minUnits['attacker'] = $this->minSimulator->units['attacker'];
     $this->minUnits['defender'] = $this->minSimulator->units['defender'];
     $this->minDebris['metal'] = $this->minSimulator->debris['metal'];
     $this->minDebris['crystal'] = $this->minSimulator->debris['crystal'];
     $this->minBooty = $this->minSimulator->totalCapacity;
     // sum up (max)
     $this->maxUnits['attacker'] = $this->maxSimulator->units['attacker'];
     $this->maxUnits['defender'] = $this->maxSimulator->units['defender'];
     $this->maxDebris['metal'] = $this->maxSimulator->debris['metal'];
     $this->maxDebris['crystal'] = $this->maxSimulator->debris['crystal'];
     $this->maxBooty = $this->maxSimulator->totalCapacity;
     $this->winner = array_count_values($this->winnerArray);
 }
Пример #29
0
 public static function results()
 {
     $passed = self::$total_results['pass'];
     $failure = self::$total_results['fail'];
     $total = self::$total_results['total'];
     $pending = self::$total_results['pending'];
     echo "\n";
     foreach (self::$pending_messages as $k => $message) {
         self::write("\n Peding: " . $message, true, "yellow");
     }
     self::write("\n\nPass: {$passed}, Failure: " . Spec::$colors['red'] . "{$failure}" . Spec::$colors['green'] . ", Pending: {$pending}, Test: {$total}\n", true);
     self::$total_results['pass'] = 0;
     self::$total_results['failure'] = 0;
     self::$total_results['pass'] = 0;
     self::$total_results['pending'] = 0;
     self::$pending_messages = array();
 }
Пример #30
0
	/**
	 * Handles saving updates from the product editor
	 *
	 * Saves all product related information which includes core product data
	 * and supporting elements such as images, digital downloads, tags,
	 * assigned categories, specs and pricing variations.
	 *	 
	 * @return void
	 **/
	function save_product ($Product) {
		$db = DB::get();
		$Settings = &EcartSettings();
		check_admin_referer('ecart-save-product');

		if ( !(is_ecart_userlevel() || current_user_can('ecart_products')) )
			wp_die(__('You do not have sufficient permissions to access this page.'));

		$Settings->saveform(); // Save workflow setting

		$base = $Settings->get('base_operations');
		$taxrate = 0;
		if ($base['vat']) $taxrate = ecart_taxrate(null,true,$Product);

		if (empty($_POST['options'])) $Product->options = array();
		else $_POST['options'] = stripslashes_deep($_POST['options']);

		if (empty($Product->slug)) $Product->slug = sanitize_title_with_dashes($_POST['name']);

		// Check for an existing product slug
		$exclude_product = !empty($Product->id)?"AND id != $Product->id":"";
		$existing = $db->query("SELECT slug FROM $Product->_table WHERE slug='$Product->slug' $exclude_product LIMIT 1");
		if ($existing) {
			$suffix = 2;
			while($existing) {
				$altslug = substr($Product->slug, 0, 200-(strlen($suffix)+1)). "-".$suffix++;
				$existing = $db->query("SELECT slug FROM $Product->_table WHERE slug='$altslug' $exclude_product LIMIT 1");
			}
			$Product->slug = $altslug;
		}

		if ($_POST['status'] == "publish") {
			$publishfields = array('month' => '','date' => '','year' => '','hour'=>'','minute'=>'','meridiem'=>'');
			$publishdate = join('',array_merge($publishfields,$_POST['publish']));
			if (!empty($publishdate)) {
				if ($_POST['publish']['meridiem'] == "PM" && $_POST['publish']['hour'] < 12)
					$_POST['publish']['hour'] += 12;
				$_POST['publish'] = mktime($_POST['publish']['hour'],$_POST['publish']['minute'],0,$_POST['publish']['month'],$_POST['publish']['date'],$_POST['publish']['year']);
			} else {
				unset($_POST['publish']);
				// Auto set the publish date if not set (or more accurately, if set to an irrelevant timestamp)
				if ($Product->publish <= 86400) $Product->publish = time();
			}
		} else {
			unset($_POST['publish']);
			$Product->publish = 0;
		}

		if (isset($_POST['content'])) $_POST['description'] = $_POST['content'];

		$Product->updates($_POST,array('categories','prices'));
		$Product->save();

		$Product->save_categories($_POST['categories']);
		$Product->save_tags(explode(",",$_POST['taglist']));

		if (!empty($_POST['price']) && is_array($_POST['price'])) {

			// Delete prices that were marked for removal
			if (!empty($_POST['deletePrices'])) {
				$deletes = array();
				if (strpos($_POST['deletePrices'],","))	$deletes = explode(',',$_POST['deletePrices']);
				else $deletes = array($_POST['deletePrices']);

				foreach($deletes as $option) {
					$Price = new Price($option);
					$Price->delete();
				}
			}

			// Save prices that there are updates for
			foreach($_POST['price'] as $i => $option) {
				if (empty($option['id'])) {
					$Price = new Price();
					$option['product'] = $Product->id;
				} else $Price = new Price($option['id']);
				$option['sortorder'] = array_search($i,$_POST['sortorder'])+1;

				// Remove VAT amount to save in DB
				if ($base['vat'] && isset($option['tax']) && $option['tax'] == "on") {
					$option['price'] = (floatvalue($option['price'])/(1+$taxrate));
					$option['saleprice'] = (floatvalue($option['saleprice'])/(1+$taxrate));
				}
				$option['shipfee'] = floatvalue($option['shipfee']);

				$option['weight'] = floatvalue($option['weight']);
				if (isset($options['dimensions']) && is_array($options['dimensions']))
					foreach ($option['dimensions'] as &$dimension)
						$dimension = floatvalue($dimension);

				$Price->updates($option);
				$Price->save();

				if (!empty($option['download'])) $Price->attach_download($option['download']);

				if (!empty($option['downloadpath'])) { // Attach file specified by URI/path
					if (!empty($Price->download->id) || (empty($Price->download) && $Price->load_download())) {
						$File = $Price->download;
					} else $File = new ProductDownload();

					$stored = false;
					$tmpfile = sanitize_path($option['downloadpath']);

					$File->storage = false;
					$Engine = $File->_engine(); // Set engine from storage settings

					$File->parent = $Price->id;
					$File->context = "price";
					$File->type = "download";
					$File->name = !empty($option['downloadfile'])?$option['downloadfile']:basename($tmpfile);
					$File->filename = $File->name;

					if ($File->found($tmpfile)) {
						$File->uri = $tmpfile;
						$stored = true;
					} else $stored = $File->store($tmpfile,'file');

					if ($stored) {
						$File->readmeta();
						$File->save();
					}

				} // END attach file by path/uri
			}
			unset($Price);
		}

		// No variation options at all, delete all variation-pricelines
		if (!empty($Product->prices) && is_array($Product->prices)
				&& (empty($_POST['options']['v']) || empty($_POST['options']['a']))) {
			foreach ($Product->prices as $priceline) {
				// Skip if not tied to variation options
				if ($priceline->optionkey == 0) continue;
				if ((empty($_POST['options']['v']) && $priceline->context == "variation")
					|| (empty($_POST['options']['a']) && $priceline->context == "addon")) {
						$Price = new Price($priceline->id);
						$Price->delete();
				}
			}
		}

		if (!empty($_POST['details']) || !empty($_POST['deletedSpecs'])) {
			$deletes = array();
			if (!empty($_POST['deletedSpecs'])) {
				if (strpos($_POST['deletedSpecs'],","))	$deletes = explode(',',$_POST['deletedSpecs']);
				else $deletes = array($_POST['deletedSpecs']);
				foreach($deletes as $option) {
					$Spec = new Spec($option);
					$Spec->delete();
				}
				unset($Spec);
			}

			if (is_array($_POST['details'])) {
				foreach ($_POST['details'] as $i => $spec) {
					if (in_array($spec['id'],$deletes)) continue;
					if (isset($spec['new'])) {
						$Spec = new Spec();
						$spec['id'] = '';
						$spec['parent'] = $Product->id;
					} else $Spec = new Spec($spec['id']);
					$spec['sortorder'] = array_search($i,$_POST['details-sortorder'])+1;

					$Spec->updates($spec);
					$Spec->save();
				}
			}
		}

		if (!empty($_POST['deleteImages'])) {
			$deletes = array();
			if (strpos($_POST['deleteImages'],","))	$deletes = explode(',',$_POST['deleteImages']);
			else $deletes = array($_POST['deleteImages']);
			$Product->delete_images($deletes);
		}

		if (!empty($_POST['images']) && is_array($_POST['images'])) {
			$Product->link_images($_POST['images']);
			$Product->save_imageorder($_POST['images']);
			if (!empty($_POST['imagedetails']))
				$Product->update_images($_POST['imagedetails']);
		}

		do_action_ref_array('ecart_product_saved',array(&$Product));

		unset($Product);
		return true;
	}