public function getStats()
 {
     App::import('model', 'Dane.Dataobject');
     $Dataobject = new Dataobject();
     $data = $Dataobject->find('all', array('conditions' => array('dataset' => 'poslowie_biura_wydatki')));
     return array('biura' => $data);
 }
 /**
  * @return FieldList
  */
 public function getCMSFields()
 {
     $fields = parent::getCMSFields();
     $opsMember = array();
     foreach (Group::get() as $group) {
         if ($group->Permissions()->filter("Code", "INCIDENTS.STAFF")->count()) {
             foreach ($group->Members() as $member) {
                 $opsMember[$member->ID] = $member->FirstName . ' ' . $member->Surname . ' <' . $member->Email . '>';
             }
         }
     }
     $assignable = new DropdownField('AssigneeID', 'Assigned to', $opsMember);
     $fields->replaceField('AssigneeID', $assignable);
     $startTime = new DatetimeField('StartTime', 'Start time');
     $startTime->getDateField()->setConfig('showcalendar', 1);
     $fields->replaceField('StartTime', $startTime);
     $endTime = new DatetimeField('EndTime', 'End time');
     $endTime->getDateField()->setConfig('showcalendar', 1);
     $fields->replaceField('EndTime', $endTime);
     $interimReportLink = new TextField('InterimReportLink', 'Interim report link');
     $fields->replaceField('InterimReportLink', $interimReportLink);
     $interimSent = new CheckboxField('InterimReportSent', 'Interim report sent?');
     $fields->insertAfter($interimSent, 'InterimReportLink');
     $finalReportLink = new TextField('FinalReportLink', 'Final report link');
     $fields->replaceField('FinalReportLink', $finalReportLink);
     $interimSent = new CheckboxField('FinalReportSent', 'Final report sent?');
     $fields->insertAfter($interimSent, 'FinalReportLink');
     return $fields;
 }
Beispiel #3
0
 public function __unset($name)
 {
     if ($name == 'content' || $name == 'text') {
         $name = '*';
     }
     parent::__unset($name);
 }
 /**
  * CMS Fields
  * @return array
  */
 public function getCMSFields()
 {
     $fields = parent::getCMSFields();
     $fields->addFieldsToTab("Root.Main", array(UploadField::create('Image')->setFolderName('Person'), TextField::create('Name'), TextField::create('Title'), TextField::create('Email'), TextField::create('Phone'), TextField::create('Mobile'), HTMLEditorField::create('Description')));
     $this->extend('updateCMSFields', $fields);
     return $fields;
 }
 /**
  * Test import with manual column mapping and custom column names
  */
 function testLoadWithCustomHeaderAndRelation()
 {
     $loader = new CsvBulkLoader('CsvBulkLoaderTest_Player');
     $filepath = Director::baseFolder() . '/sapphire/tests/dev/CsvBulkLoaderTest_PlayersWithCustomHeaderAndRelation.csv';
     $file = fopen($filepath, 'r');
     $compareCount = $this->getLineCount($file);
     fgetcsv($file);
     // pop header row
     $compareRow = fgetcsv($file);
     $loader->columnMap = array('first name' => 'FirstName', 'bio' => 'Biography', 'bday' => 'Birthday', 'teamtitle' => 'Team.Title', 'teamsize' => 'Team.TeamSize', 'salary' => 'Contract.Amount');
     $loader->hasHeaderRow = true;
     $loader->relationCallbacks = array('Team.Title' => array('relationname' => 'Team', 'callback' => 'getTeamByTitle'));
     $results = $loader->load($filepath);
     // Test that right amount of columns was imported
     $this->assertEquals(1, $results->Count(), 'Test correct count of imported data');
     // Test of augumenting existing relation (created by fixture)
     $testTeam = DataObject::get_one('CsvBulkLoaderTest_Team', null, null, 'Created DESC');
     $this->assertEquals('20', $testTeam->TeamSize, 'Augumenting existing has_one relation works');
     // Test of creating relation
     $testContract = DataObject::get_one('CsvBulkLoaderTest_PlayerContract');
     $testPlayer = Dataobject::get_one("CsvBulkLoaderTest_Player", "FirstName = 'John'");
     $this->assertEquals($testPlayer->ContractID, $testContract->ID, 'Creating new has_one relation works');
     // Test nested setting of relation properties
     $contractAmount = DBField::create('Currency', $compareRow[5])->RAW();
     $this->assertEquals($testPlayer->Contract()->Amount, $contractAmount, 'Setting nested values in a relation works');
     fclose($file);
 }
 /**
  * standard SS method
  *
  */
 function updateCMSFields(FieldSet &$fields)
 {
     if ($brands = Dataobject::get("Brand")) {
         $fields->removeFieldFromTab("Root.Content.Main", "Model");
         $fields->addFieldToTab('Root.Content.Main', new DropdownField('BrandID', 'Please choose an brand', $brands->map("ID", "Title", "Please Select")), "FeaturedProduct");
     }
 }
 function AbsoluteLink($master = false)
 {
     $page = $master ? Dataobject::get_by_id("SiteTree", $this->MasterPageID) : Dataobject::get_by_id("SiteTree", $this->RelatedPageID);
     if (!$page) {
         return;
     }
     $url = $page->AbsoluteLink();
 }
 public function index($query)
 {
     App::import('model', 'Dane.Dataobject');
     $dataobject = new Dataobject();
     $data = array();
     if (!isset($query['page']) || !is_numeric($query['page'])) {
         $query['page'] = 1;
     }
     $conditions = isset($query['conditions']) ? $query['conditions'] : array();
     $facets = isset($query['facets']) ? $query['facets'] : array();
     $order = isset($query['order']) ? $query['order'] : '_date desc';
     $objects = $dataobject->find('all', array('conditions' => $conditions, 'order' => $order, 'limit' => 20, 'page' => $query['page']));
     foreach ($objects as $object) {
         $object = $object['Dataobject'];
         $data[] = array('type' => 'blog_post', 'date' => $object->getData('data_wejscia_w_zycie'), 'title' => $object->getData('typ_nazwa'), 'content' => '<a href="/dane/prawo/' . $object->getId() . '">' . $object->getTitle() . '</a>');
     }
     return $data;
 }
Beispiel #9
0
 function __construct($core, $title, $body = NULL)
 {
     if (is_string($title)) {
         // not a data array
         $title = array('title' => $title, 'body' => $body);
     }
     if (isset($title['imageinfo']) && is_array($title['imageinfo'])) {
         $title = array_merge($title, $title['imageinfo']);
         unset($title['imageinfo']);
     }
     parent::__construct($core, $title);
 }
Beispiel #10
0
 public function __isset($name)
 {
     if ($name == 'redirect') {
         return true;
     }
     // emulated property
     if ($name == 'new') {
         return true;
     }
     // emulated property
     if ($name == 'content') {
         $name = 'text';
     }
     return parent::__isset($name);
 }
 function getCMSFields()
 {
     $fields = new FieldList();
     $fields->add(new TextField('Name', 'Name'));
     $fields->add(new HtmlEditorField('Description', 'Description'));
     $fields->add(new DropdownField('Status', 'Status', $this->dbObject('Status')->enumValues()));
     $fields->add($ddl_program = new CheckboxsetField('Program', 'Program', InteropProgramType::get()->filter('HasCapabilities', true)->sort('Order')->map("ID", "ShortName")));
     $fields->add($ddl_version = new CheckboxsetField('Version', 'Version', InteropProgramVersion::get()->map("ID", "Name")));
     $fields->add($ddl_type = new DropdownField('TypeID', 'Type', Dataobject::get("InteropCapabilityType")->map("ID", "Name", "Please Select")));
     if ($this->ID > 0) {
         $ddl_program->setValue('ID', $this->Program());
         $ddl_version->setValue('ID', $this->Version());
         $ddl_type->setValue($this->TypeID);
     }
     return $fields;
 }
 /**
  * Get the Category name to add into the CategorySections array drop-down list
  *
  * @return array $aCategorySections An array of mapped IDs and values
  */
 public function FormCategorySections()
 {
     // Set an empty return array
     $aCategorySections = array();
     // Get all Categorys
     $oCategorySections = Dataobject::get('FormCategory');
     if ($oCategorySections) {
         // Loop through each Category
         foreach ($oCategorySections as $category) {
             // Add it into the Categorys array
             $aCategorySections[$category->ID] = $category->Title;
         }
         // Return the Categorys array
         return $aCategorySections;
     }
 }
 /**
  * Provides a GUI for the insert embed content popup
  * @return Form
  **/
 public function EmbedContentForm()
 {
     if (!Permission::check('CMS_ACCESS_CMSMain')) {
         return;
     }
     $contenttype = $this->request->requestVar('EmbedContentType');
     $allContentTypes = array('Container' => 'Empty Block', 'Page' => 'Pages in the Site Tree', 'DataObject' => 'Other Data Object in the site', 'External' => 'External site content');
     $headerField = CompositeField::create(LiteralField::create('Heading', sprintf('<h3 class="htmleditorfield-embedcontentform-heading insert">%s</h3>', "Insert Content")))->addExtraClass('CompositeField composite cms-content-header nolabel');
     $fields = array(DropdownField::create('EmbedContentType', 'Embed Content Type', $allContentTypes, $contenttype)->setHasEmptyDefault(true)->addExtraClass('reloadFormOnSelect'));
     if ($contenttype) {
         if ($contenttype == 'External') {
             $fields[] = TextField::create('ExternalURL', 'External URL', $this->request->requestVar('ExternalURL'));
         } elseif ($contenttype == 'DataObject' || $contenttype == 'Page') {
             $allDataObjectClasses = ClassInfo::subclassesFor($contenttype);
             $dataobjecttype = $this->request->requestVar('EmbedContentDataObjectType');
             $fields[] = DropdownField::create('EmbedContentDataObjectType', 'Data Object Type', $allDataObjectClasses, $dataobjecttype)->setHasEmptyDefault(true)->addExtraClass('reloadFormOnSelect');
             if ($dataobjecttype) {
                 $fields[] = DropdownField::create('EmbedContentDataObjectID', 'Please choose an object', Dataobject::get($dataobjecttype)->map("ID", "Title"), $this->request->requestVar('EmbedContentDataObjectID'))->setHasEmptyDefault(true);
             }
         }
         if ($contenttype != 'Container') {
             $fields[] = DropdownField::create('EmbedTemplate', 'Please choose an View', self::getTemplates($contenttype), $this->request->requestVar('EmbedTemplate'))->setHasEmptyDefault(false);
         }
         if (!self::isInlineTemplate($contenttype, $this->request->requestVar('EmbedTemplate')) || $contenttype == 'Container') {
             $widthField = new FieldGroup(TextField::create('EmbedWidth', 'Value', $this->request->requestVar('EmbedWidth')), DropdownField::create('EmbedWidthUnit', 'Unit', array('px' => 'Pixel', 'em' => 'Font Size', '%' => 'Percent'), $this->request->requestVar('EmbedWidthUnit')));
             $widthField->setTitle("Width");
             $fields[] = $widthField;
             $heightField = new FieldGroup(TextField::create('EmbedHeight', 'Value', $this->request->requestVar('EmbedHeight'))->addExtraClass('clear'), DropdownField::create('EmbedHeightUnit', 'Unit', array('px' => 'Pixel', 'em' => 'Font Size', '%' => 'Percent'), $this->request->requestVar('EmbedHeightUnit')));
             $heightField->setTitle("Height");
             $fields[] = $heightField;
             $fields[] = DropdownField::create('EmbedFloat', 'Align(Float)', array(' ' => 'None', 'left' => 'Left', 'right' => 'Right'), $this->request->requestVar('EmbedFloat'));
         }
         if (self::hasCSSClasses()) {
             $fields[] = DropdownField::create('EmbedCSSClass', 'CSS Class', self::getCSSClasses(), $this->request->requestVar('EmbedCSSClass'));
         }
     }
     // essential fields
     $fields = FieldList::create(array($headerField, CompositeField::create($fields)->addExtraClass('ss-embedcontent-fields')));
     $ActionName = "Insert/Update Content";
     // actions
     $actions = FieldList::create(array(FormAction::create('insert', _t('Embedcontent.BUTTONINSERTSHORTCODE', $ActionName))->addExtraClass('ss-ui-action-constructive')->setAttribute('data-icon', 'accept')->setUseButtonTag(true)));
     // form
     $form = Form::create($this, "EmbedContentForm", $fields, $actions)->loadDataFrom($this)->addExtraClass('htmleditorfield-form htmleditorfield-embedcontent cms-dialog-content');
     return $form;
 }
 public function getHTMLFragments($gridField)
 {
     Requirements::css(FindManyManyDropdown_PATH . '/css/FindManyManyDropdown.css');
     Requirements::javascript(FindManyManyDropdown_PATH . '/javascript/FindManyManyDropdownForm.js');
     $targetFragment = 'before';
     if ($gridField->getConfig()->getComponentByType('GridFieldButtonRow')) {
         $targetFragment = 'buttons-before-right';
     }
     $dataClass = $gridField->list->dataClass;
     $dropdownOptions = new DropdownField('gridfield_relationdropdown', 'Please choose an object', Dataobject::get($dataClass)->map("ID", "Title"));
     $dropdownOptions->setEmptyString('Select:');
     $addAction = new GridField_FormAction($gridField, 'gridfield_relationadd', _t('GridField.LinkExisting', "Link Existing"), 'addDDto', 'addDDto');
     $addAction->setAttribute('data-icon', 'chain--plus');
     $forTemplate = new ArrayData(array());
     $forTemplate->Fields = new ArrayList();
     $forTemplate->Fields->push($dropdownOptions);
     $forTemplate->Fields->push($addAction);
     return array($targetFragment => $forTemplate->renderWith('FindManyManyDropdownForm'));
 }
Beispiel #15
0
 function testDbDatetimeDifference()
 {
     if ($this->supportDbDatetime) {
         $query = 'SELECT ' . $this->adapter->datetimeDifferenceClause('1974-10-14 10:30:00', '1973-10-14 10:30:00');
         $result = DB::query($query)->value();
         $this->matchesRoughly($result / 86400, 365, '1974 - 1973 = 365 * 86400 sec');
         $query = 'SELECT ' . $this->adapter->datetimeDifferenceClause(date('Y-m-d H:i:s', strtotime('-15 seconds')), 'now');
         $result = DB::query($query)->value();
         $this->matchesRoughly($result, -15, '15 seconds ago - now');
         $query = 'SELECT ' . $this->adapter->datetimeDifferenceClause('now', $this->adapter->datetimeIntervalClause('now', '+45 Minutes'));
         $result = DB::query($query)->value();
         $this->matchesRoughly($result, -45 * 60, 'now - 45 minutes ahead');
         $query = 'SELECT ' . $this->adapter->datetimeDifferenceClause('"LastEdited"', '"Created"') . ' AS "test" FROM "SiteTree" WHERE "URLSegment" = \'home\'';
         $result = DB::query($query)->value();
         $lastedited = Dataobject::get_one('SiteTree', "\"URLSegment\" = 'home'")->LastEdited;
         $created = Dataobject::get_one('SiteTree', "\"URLSegment\" = 'home'")->Created;
         $this->matchesRoughly($result, strtotime($lastedited) - strtotime($created), 'age of HomePage record in seconds since unix epoc');
     }
 }
 public function doc2object($doc)
 {
     $dataset = $doc['fields']['dataset'][0];
     $id = $doc['fields']['id'][0];
     if ($dataset == null or $id == null) {
         throw new InternalErrorException("Empty dataset or id: " . $dataset . ' ' . $id);
     }
     $output = array('id' => $id, 'dataset' => $dataset, 'url' => Dataobject::apiUrl($dataset, $id), 'mp_url' => Dataobject::mpUrl($dataset, $id), 'schema_url' => Dataobject::schemaUrl($dataset), 'global_id' => $doc['_id'], 'slug' => $doc['fields']['slug'][0], 'score' => $doc['_score'], 'data' => $doc['fields']['source'][0]['data']);
     if (@$doc['inner_hits']['collection']['hits']['total'] && @$doc['inner_hits']['collection']['hits']['hits'][0]['_source']) {
         $output['collection'] = $doc['inner_hits']['collection']['hits']['hits'][0]['_source'];
         $output['collection']['id'] = (int) $doc['inner_hits']['collection']['hits']['hits'][0]['_id'];
     }
     if (isset($doc['fields']['source'][0]['static']) && !empty($doc['fields']['source'][0]['static'])) {
         $output['static'] = $doc['fields']['source'][0]['static'];
     }
     if (isset($doc['fields']['source'][0]['contexts']) && !empty($doc['fields']['source'][0]['contexts'])) {
         $force_context = false;
         if (@$doc['inner_hits']['alert-data']['hits']['total'] && isset($doc['inner_hits']['alert-data']['hits']['hits'][0]['fields']['context'][0])) {
             $force_context = $doc['inner_hits']['alert-data']['hits']['hits'][0]['fields']['context'][0];
         }
         $context = array();
         foreach ($doc['fields']['source'][0]['contexts'] as $key => $value) {
             if (!$force_context || $force_context && strpos($key, $force_context) !== false) {
                 $key_parts = explode('.', $key);
                 $value_parts = explode("\n\r", $value);
                 $context[] = array('creator' => array('dataset' => $key_parts[0], 'id' => $key_parts[1], 'global_id' => $value_parts[0], 'name' => $value_parts[1], 'slug' => $value_parts[2], 'url' => @$value_parts[5]), 'action' => $key_parts[2], 'label' => $value_parts[3], 'sentence' => $value_parts[4]);
             }
         }
         $output['contexts'] = $context;
     }
     if (isset($doc['highlight']['text']) && is_array($doc['highlight']['text']) && isset($doc['highlight']['text'][0])) {
         $output['highlight'] = array($doc['highlight']['text']);
     }
     if (isset($doc['inner_hits']) && isset($doc['inner_hits']['inner']) && isset($doc['inner_hits']['inner']['hits']) && isset($doc['inner_hits']['inner']['hits']['hits'])) {
         foreach ($doc['inner_hits']['inner']['hits']['hits'] as $hit) {
             $output['inner_hits'][] = array('id' => $hit['_id'], 'title' => @$hit['fields']['title'][0]);
         }
     }
     return $output;
 }
Beispiel #17
0
 function testDbDatetimeDifference()
 {
     if ($this->supportDbDatetime) {
         $clause = $this->adapter->datetimeDifferenceClause('1974-10-14 10:30:00', '1973-10-14 10:30:00');
         $result = DB::query('SELECT ' . $clause)->value();
         $this->matchesRoughly($result / 86400, 365, '1974 - 1973 = 365 * 86400 sec');
         $clause = $this->adapter->datetimeDifferenceClause(date('Y-m-d H:i:s', strtotime('-15 seconds')), 'now');
         $result = DB::query('SELECT ' . $clause)->value();
         $this->matchesRoughly($result, -15, '15 seconds ago - now');
         $clause = $this->adapter->datetimeDifferenceClause('now', $this->adapter->datetimeIntervalClause('now', '+45 Minutes'));
         $result = DB::query('SELECT ' . $clause)->value();
         $this->matchesRoughly($result, -45 * 60, 'now - 45 minutes ahead');
         $query = new SQLQuery();
         $query->select($this->adapter->datetimeDifferenceClause('"LastEdited"', '"Created"') . ' AS "test"')->from('"DbDateTimeTest_Team"')->limit(1);
         $result = $query->execute()->value();
         $lastedited = Dataobject::get_one('DbDateTimeTest_Team')->LastEdited;
         $created = Dataobject::get_one('DbDateTimeTest_Team')->Created;
         $this->matchesRoughly($result, strtotime($lastedited) - strtotime($created), 'age of HomePage record in seconds since unix epoc');
     }
 }
/**
* Zwraca obiekt GeoJson FeatureCollection zawierający wszystkie gminy tego województwa (właściwości są keszowane także)
*/
App::import('model', 'MPCache');
App::uses('Model', 'Dane.Dataobject');
// Try cache
$cacheKey = 'geojson/agg/gminy/wojewodztwo/' . $id;
$cache = new MPCache();
$cacheClient = $cache->getDataSource()->getRedisClient();
if ($cacheClient->exists($cacheKey)) {
    return json_decode($cacheClient->get($cacheKey));
} else {
    // Build geojson feature collection
    $gminy_ids = $this->DB->selectValues("SELECT id FROM epf.pl_gminy WHERE w_id = {$id} AND akcept = '1'");
    if (!$gminy_ids) {
        throw new Exception("Nie znaleziono gmin dla w_id = {$id}");
    }
    $gminy = array();
    foreach ($gminy_ids as $gid) {
        $d = new Dataobject();
        $g = $d->getObjectLayer('gminy', $gid, 'geojson_simplified', $params = array());
        unset($g['crs']);
        $gminy[] = $g;
    }
    $featc = array("type" => "FeatureCollection", "features" => $gminy);
    MpUtils::geoStampCRS($featc);
    // Put in cache
    $cacheClient->set($cacheKey, json_encode($featc));
    return $featc;
}
 /**
  * CMS Fields
  * @return array
  */
 public function getCMSFields()
 {
     $fields = parent::getCMSFields();
     $fields->addFieldsToTab("Root.Main", array(UploadField::create('Image'), TextField::create('Name'), TextField::create('Title'), TextField::create('Email'), TextField::create('Phone'), TextField::create('Mobile'), HTMLEditorField::create('Description')));
     return $fields;
 }
 function RecentEvents()
 {
     $now = date('Y-m-d H:i:s');
     if ($allpastEvents = Dataobject::get('CleanUpGroup', "(FromDate < '{$now}')", "FromDate ASC", '', 30)) {
         return $allpastEvents;
     } else {
         return false;
     }
 }
/**
* Zwraca obiekt GeoJson FeatureCollection zawierający wszystkie gminy tego powiatu (właściwości są keszowane także)
*/
App::import('model', 'MPCache');
App::uses('Model', 'Dane.Dataobject');
// Try cache
$cacheKey = 'geojson/agg/powiaty/wojewodztwo/' . $id;
$cache = new MPCache();
$cacheClient = $cache->getDataSource()->getRedisClient();
if ($cacheClient->exists($cacheKey)) {
    return json_decode($cacheClient->get($cacheKey));
} else {
    // Build geojson feature collection
    $powiaty_ids = $this->DB->selectValues("SELECT id FROM epf.pl_powiaty WHERE w_id = {$id} AND akcept = '1'");
    if (!$powiaty_ids) {
        throw new Exception("Nie znaleziono powiatów dla w_id = {$id}");
    }
    $powiaty = array();
    foreach ($powiaty_ids as $pid) {
        $d = new Dataobject();
        $p = $d->getObjectLayer('powiaty', $pid, 'geojson', $params = array());
        unset($p['crs']);
        $powiaty[] = $p;
    }
    $featc = array("type" => "FeatureCollection", "features" => $powiaty);
    MpUtils::geoStampCRS($featc);
    // Put in cache
    $cacheClient->set($cacheKey, json_encode($featc));
    return $featc;
}
 public function series()
 {
     $metric_id = @$this->request->query['metric_id'];
     $slice = @$this->request->query['slice'];
     $time_range = @$this->request->query['time_range'];
     $wojewodztwo_id = @$this->request->query['wojewodztwo_id'];
     $powiat_id = @$this->request->query['powiat_id'];
     $gmina_id = @$this->request->query['gmina_id'];
     $meta = @$this->request->query['meta'];
     if ($metric_id === null) {
         throw new BadRequestException('Query parameter is required: metric_id');
     }
     $metric = $this->Dataobject->find('first', array('conditions' => array('bdl_wskazniki.okres' => 'R', 'dataset' => 'bdl_wskazniki', 'id' => $metric_id)));
     if (!$metric) {
         throw new ApiException(API_BDL_INVALID_INPUT, array('param' => 'metric_id'));
     }
     $metric_depths = array('0' => 'pl', '2' => 'wojewodztwo', '4' => 'powiat', '5' => 'gmina');
     $dims = $this->Dataobject->getObjectLayer('bdl_wskazniki', $metric_id, 'dimennsions');
     // check if slices match metrics
     if ($slice != null) {
         $slice = preg_replace('/\\s+/', '', $slice);
         if (!preg_match('/^\\[((\\d+|\\*)(,(\\d+|\\*))*)\\]$/', $slice, $slices)) {
             throw new ApiException(API_BDL_INVALID_INPUT, array('param' => 'slice'));
         }
         $slices = explode(',', $slices[1]);
         if (count($slices) != count($dims)) {
             throw new ApiException(API_BDL_MISMATCHED_DIMS_COUNT, array('expected' => count($dims), 'was' => count($slices)));
         }
     } else {
         $slices = array_fill(0, count($dims), '*');
     }
     $w = array(0 => 0, 1 => 0, 2 => 0, 3 => 0, 4 => 0);
     for ($i = 0; $i < count($slices); $i++) {
         $dim_slices = array_map(function ($el) {
             return $el['id'];
         }, $dims[$i]['options']);
         if ($slices[$i] == '*') {
             $w[$i] = $dim_slices;
         } elseif (!in_array($slices[$i], $dim_slices)) {
             throw new ApiException(API_BDL_INVALID_SLICE, $slices[$i]);
         } else {
             $w[$i] = $slices[$i];
         }
     }
     if (($wojewodztwo_id != null) + ($powiat_id != null) + ($gmina_id != null) > 1) {
         throw new ApiException(API_BDL_INVALID_INPUT, array('param' => array('wojewodztwo_id', 'powiat_id', 'gmina_id')), 'Only one of these parameters can be specified');
     }
     $conditions = array();
     $fields = array('w1', 'w2', 'w3', 'w4', 'w5', 'rocznik', 'v', 'kombinacja_id');
     // choose datasource
     $region = null;
     if ($wojewodztwo_id != null) {
         $model = 'DataWojewodztwa';
         $fields[] = 'wojewodztwo_id';
         if ($metric['data']['bdl_wskazniki.poziom_id'] < 2) {
             throw new ApiException(API_BDL_LEVEL_DATA_NOTAVAILABLE, array('requested' => $metric_depths[2], 'available_till' => $metric_depths[$metric['data']['poziom_id']]), 'Data at this regional level is not available');
         }
         if ($wojewodztwo_id != '*') {
             if (!preg_match('/^\\d+$/', $wojewodztwo_id)) {
                 throw new ApiException(API_BDL_INVALID_INPUT, array('param' => 'wojewodztwo_id'));
             }
             $wojewodztwo_id = intval($wojewodztwo_id);
             $region = $this->Dataobject->find('first', array('conditions' => array('dataset' => 'wojewodztwa', 'id' => $wojewodztwo_id)));
             if (!$region) {
                 throw new ApiException(API_BDL_INVALID_INPUT, array('param' => 'wojewodztwo_id'));
             }
             $conditions["wojewodztwo_id"] = $wojewodztwo_id;
         }
     } else {
         if ($powiat_id != null) {
             $model = 'DataPowiaty';
             $fields[] = 'powiat_id';
             if ($metric['data']['bdl_wskazniki.poziom_id'] < 4) {
                 throw new ApiException(API_BDL_LEVEL_DATA_NOTAVAILABLE, array('requested' => $metric_depths[4], 'available_till' => $metric_depths[$metric['data']['bdl_wskazniki.poziom_id']]), 'Data at this regional level is not available');
             }
             if ($powiat_id != '*') {
                 if (!preg_match('/^\\d+$/', $powiat_id)) {
                     throw new ApiException(API_BDL_INVALID_INPUT, array('param' => 'powiat_id'));
                 }
                 $powiat_id = intval($powiat_id);
                 $region = $this->Dataobject->find('first', array('conditions' => array('dataset' => 'powiaty', 'id' => $powiat_id)));
                 if (!$region) {
                     throw new ApiException(API_BDL_INVALID_INPUT, array('param' => 'powiat_id'));
                 }
                 $conditions["powiat_id"] = $powiat_id;
             }
         } else {
             if ($gmina_id != null) {
                 $model = 'DataGminy';
                 $fields[] = 'gmina_id';
                 if ($metric['data']['bdl_wskazniki.poziom_id'] < 5) {
                     throw new ApiException(API_BDL_LEVEL_DATA_NOTAVAILABLE, array('requested' => $metric_depths[5], 'available_till' => $metric_depths[$metric['data']['bdl_wskazniki.poziom_id']]), 'Data at this regional level is not available');
                 }
                 if ($gmina_id != '*') {
                     if (!preg_match('/^\\d+$/', $gmina_id)) {
                         throw new ApiException(API_BDL_INVALID_INPUT, array('param' => 'gmina_id'));
                     }
                     $gmina_id = intval($gmina_id);
                     $region = $this->Dataobject->find('first', array('conditions' => array('dataset' => 'gminy', 'id' => $gmina_id)));
                     if (!$region) {
                         throw new ApiException(API_BDL_INVALID_INPUT, array('param' => 'gmina_id'));
                     }
                     $conditions["gmina_id"] = $gmina_id;
                 }
             } else {
                 $model = 'DataPl';
             }
         }
     }
     // choose time range
     if ($time_range != null) {
         if (!preg_match('/^(\\d{4}):(\\d{4})$/', $time_range, $time_ranges)) {
             throw new ApiException(API_BDL_INVALID_INPUT, array('param' => 'time_range', 'value' => $time_range, 'expected_format' => 'year_start:year_end'));
         }
         if ($time_ranges[0] <= $time_ranges[1]) {
             $conditions['rocznik >='] = intval($time_ranges[0]);
             $conditions['rocznik <='] = intval($time_ranges[1]);
         } else {
             $conditions['rocznik >='] = intval($time_ranges[1]);
             $conditions['rocznik <='] = intval($time_ranges[2]);
         }
     }
     // choose series
     $series_ids = $this->WymiaryKombinacje->find('all', array('conditions' => array('podgrupa_id' => $metric_id, 'w1' => $w[0], 'w2' => $w[1], 'w3' => $w[2], 'w4' => $w[3], 'w5' => $w[4]), 'fields' => array('id', 'jednostka')));
     $units = array();
     foreach ($series_ids as $s) {
         $units[$s['WymiaryKombinacje']['id']] = trim($s['WymiaryKombinacje']['jednostka'], '[]');
     }
     $conditions['kombinacja_id'] = array_keys($units);
     $conditions['deleted'] = 0;
     $data_count = $this->{$model}->find('count', array('conditions' => $conditions, 'fields' => $fields));
     if ($data_count > DATA_POINTS_LIMIT) {
         throw new ApiException(API_BDL_TOO_MANY_POINTS, array('limit' => DATA_POINTS_LIMIT, 'found' => $data_count));
     }
     $order = array('kombinacja_id', 'rocznik');
     if ($wojewodztwo_id != null) {
         array_splice($order, 1, 0, 'wojewodztwo_id');
     }
     if ($powiat_id != null) {
         array_splice($order, 1, 0, 'powiat_id');
     }
     if ($gmina_id != null) {
         array_splice($order, 1, 0, 'gmina_id');
     }
     $data = $this->{$model}->find('all', array('conditions' => $conditions, 'fields' => $fields, 'order' => $order));
     $slice_parts = array_slice(array('w1' => 0, 'w2' => 0, 'w3' => 0, 'w4' => 0, 'w5' => 0), 0, count($slices));
     $response = MpUtils::maptable2tree($data, array(array('name' => 'slices', 'key' => function ($r) use($model) {
         return $r[$model]['kombinacja_id'] . '-' . @$r[$model]['wojewodztwo_id'] . @$r[$model]['powiat_id'] . @$r[$model]['gmina_id'];
     }, 'content' => function ($r) use($model, $slice_parts, $units) {
         $legend = array('slice' => array_values(array_intersect_key($r[$model], $slice_parts)), 'units' => $units[$r[$model]['kombinacja_id']]);
         if (@$r[$model]['wojewodztwo_id']) {
             $legend['wojewodztwo_id'] = $r[$model]['wojewodztwo_id'];
         }
         if (@$r[$model]['powiat_id']) {
             $legend['powiat_id'] = $r[$model]['powiat_id'];
         }
         if (@$r[$model]['gmina_id']) {
             $legend['gmina_id'] = $r[$model]['gmina_id'];
         }
         return $legend;
     }), array('content' => function ($r) use($model) {
         return array('year' => intval($r[$model]['rocznik']), 'value' => $r[$model]['v']);
     })), 'series');
     if ($meta !== '0') {
         // include meta by default
         $response['meta'] = array('metric_id' => Dataobject::apiUrl($metric['dataset'], $metric['id']), 'metric_name' => $metric['data']['bdl_wskazniki.tytul'], 'metric_depth' => $metric_depths[$metric['data']['bdl_wskazniki.poziom_id']], 'metric_mpurl' => Dataobject::mpUrl($metric['dataset'], $metric['id']), 'group_name' => $metric['data']['bdl_wskazniki.grupa_tytul'], 'category_name' => $metric['data']['bdl_wskazniki.kategoria_tytul'], 'dimensions' => $dims);
     }
     if (empty($response)) {
         $response = new object();
     }
     $this->setSerialized('response', $response);
 }
Beispiel #23
0
 function _valida($do)
 {
     $this->rapyd->load('dataobject');
     $obr = $do->get('obr');
     $obra = new Dataobject('obra');
     $obra->load($obr);
     $rr = $this->ivaplica2();
     $ivaa = $do->get('ivaa');
     $ivag = $do->get('ivag');
     $ivar = $do->get('ivar');
     $exento = $do->get('exento');
     $subtotal = $do->get('subtotal');
     $cod_prov = $do->get('cod_prov');
     $otrasrete = $do->get('otrasrete');
     $ivag = $ivag != 0 ? $subtotal * $rr['tasa'] / 100 : 0;
     $ivar = $ivar != 0 ? $subtotal * $rr['redutasa'] / 100 : 0;
     $ivaa = $ivaa != 0 ? $subtotal * $rr['sobretasa'] / 100 : 0;
     $do->set('ivaa', $ivaa);
     $do->set('ivag', $ivag);
     $do->set('ivar', $ivar);
     $iva = $ivag + $ivar + $ivaa;
     //$cod_prov     = $obra->get('cod_prov'  );
     $porcent = $obra->get('porcent');
     $tipo = $obra->get('tipo');
     $do->set('estadmin', $obra->get('codigoadm'));
     $do->set('fondo', $obra->get('fondo'));
     $creten = $do->get('creten');
     $reteiva_prov = $this->datasis->dameval("SELECT reteiva FROM sprv WHERE proveed = '{$cod_prov}'");
     if ($tipo == 'Compra') {
         $do->set('creten', '');
         $do->set('reten', 0);
     }
     $rete = $this->datasis->damerow("SELECT base1,tari1,pama1 FROM rete WHERE codigo='{$creten}'");
     if ($reteiva_prov != 75) {
         $reteiva_prov = 100;
     }
     $error = '';
     $reteiva = $mivag = $mivar = $mivaa = 0;
     $reten = 0;
     if (!empty($cod_prov)) {
         $reteiva = $iva * $reteiva_prov / 100;
         if ($rete) {
             if (substr($creten, 0, 1) == '1') {
                 $reten = round($subtotal * $rete['base1'] * $rete['tari1'] / 10000, 2);
             } else {
                 $reten = round(($subtotal - $rete['pama1']) * $rete['base1'] * $rete['tari1'] / 10000, 2);
             }
             if ($reten < 0) {
                 $reten = 0;
             }
             $do->set('reten', $reten);
         }
     } else {
         $reteiva = 0;
     }
     $impt = $impm = 0;
     $pimpm = $this->datasis->traevalor('IMPMUNICIPAL');
     $pimpt = $this->datasis->traevalor('IMPTIMBRE');
     $pcrs = $this->datasis->traevalor('CRS');
     if ($do->get('imptimbre') != 0) {
         $impt = $subtotal * $pimpt / 100;
     }
     if ($do->get('impmunicipal') != 0) {
         $impm = $subtotal * $pimpm / 100;
     }
     $crs = 0;
     if ($do->get('crs') != 0) {
         $crs = $obra->get('monto') * $pcrs / 100;
     }
     $total2 = $iva + $subtotal;
     $amortiza = $do->get('amortiza');
     //if($do->get('amortiza')!=0)
     //	$amortiza = $total2 * $porcent / 100;
     $total = $total2 - $reteiva - $reten - $amortiza - $otrasrete - $impt - $impm - $crs;
     //echo "</br>".$total2;
     //echo "</br>".$amortiza;
     //echo "</br>".$reten;
     //echo "</br>".$reteiva;
     //echo "</br>".$impt;
     //echo "</br>".$impm;
     //echo "</br>".$crs;
     //echo "</br>".$total;
     //exit();
     $do->set('impmunicipal', $impm);
     $do->set('imptimbre', $impt);
     $do->set('crs', $crs);
     $do->set('pimpmunicipal', $pimpm);
     $do->set('pimptimbre', $pimpt);
     $do->set('pcrs', $pcrs);
     $do->set('iva', $iva);
     $do->set('tivag', $rr['tasa']);
     $do->set('tivar', $rr['redutasa']);
     $do->set('tivaa', $rr['sobretasa']);
     $do->set('mivag', $ivag > 0 ? $ivag * 100 / $rr['tasa'] : 0);
     $do->set('mivar', $ivar > 0 ? $ivar * 100 / $rr['redutasa'] : 0);
     $do->set('mivaa', $ivaa > 0 ? $ivaa * 100 / $rr['sobretasa'] : 0);
     //$do->set('subtotal'      , $subtotal            );
     $do->set('exento', $exento);
     $do->set('reteiva', $reteiva);
     $do->set('total', $total);
     $do->set('total2', $total2);
     $do->set('status', 'O1');
     $do->set('cod_prov', $cod_prov);
     $do->set('breten', $rete['tari1']);
     $do->set('amortiza', $amortiza);
     $do->set('porcent', $porcent);
     $do->set('multiple', 'N');
     if (empty($error)) {
         if (empty($do->loaded)) {
             $nodirect = $this->datasis->fprox_numero('nodirect');
             $do->set('numero', $nodirect);
             $do->pk = array('numero' => $nodirect);
         }
     }
     if (!empty($error)) {
         $do->error_message_ar['pre_ins'] = $error;
         $do->error_message_ar['pre_upd'] = $error;
         return false;
     }
 }
/**
* Zwraca obiekt GeoJson FeatureCollection zawierający wszystkie gminy tego powiatu (właściwości są keszowane także)
*/
App::import('model', 'MPCache');
App::uses('Model', 'Dane.Dataobject');
// Try cache
$cacheKey = 'geojson/agg/gminy/powiat/' . $id;
$cache = new MPCache();
$cacheClient = $cache->getDataSource()->getRedisClient();
if ($cacheClient->exists($cacheKey)) {
    return json_decode($cacheClient->get($cacheKey));
} else {
    // Build geojson feature collection
    $gminy_ids = $this->DB->selectValues("SELECT id FROM epf.pl_gminy WHERE pl_powiat_id = {$id} AND akcept = '1'");
    if (!$gminy_ids) {
        throw new Exception("Nie znaleziono gmin dla pl_powiat_id = {$id}");
    }
    $gminy = array();
    foreach ($gminy_ids as $gid) {
        $d = new Dataobject();
        $g = $d->getObjectLayer('gminy', $gid, 'geojson', $params = array());
        unset($g['crs']);
        $gminy[] = $g;
    }
    $featc = array("type" => "FeatureCollection", "features" => $gminy);
    MpUtils::geoStampCRS($featc);
    // Put in cache
    $cacheClient->set($cacheKey, json_encode($featc));
    return $featc;
}
 function getCMSFields()
 {
     $fields = parent::getCMSFields();
     $fields->addFieldsToTab('Root.Main', array(DropdownField::create('Type', 'Type', singleton('Phone')->dbObject('Type')->enumValues()), TextField::create('ContactNumber', 'Number'), TextField::create('Label', 'Label')));
     return $fields;
 }
 public function testSaveIntoManyManyRelation()
 {
     $article = $this->objFromFixture('ListboxFieldTest_Article', 'articlewithouttags');
     $articleWithTags = $this->objFromFixture('ListboxFieldTest_Article', 'articlewithtags');
     $tag1 = $this->objFromFixture('ListboxFieldTest_Tag', 'tag1');
     $tag2 = $this->objFromFixture('ListboxFieldTest_Tag', 'tag2');
     $field = new ListboxField("Tags", "Test field", DataObject::get("ListboxFieldTest_Tag")->map()->toArray());
     $field->setMultiple(true);
     // Save new relations
     $field->setValue(array($tag1->ID, $tag2->ID));
     $field->saveInto($article);
     $article = Dataobject::get_by_id('ListboxFieldTest_Article', $article->ID, false);
     $this->assertEquals(array($tag1->ID, $tag2->ID), $article->Tags()->sort('ID')->column('ID'));
     // Remove existing relation
     $field->setValue(array($tag1->ID));
     $field->saveInto($article);
     $article = Dataobject::get_by_id('ListboxFieldTest_Article', $article->ID, false);
     $this->assertEquals(array($tag1->ID), $article->Tags()->sort('ID')->column('ID'));
     // Set NULL value
     $field->setValue(null);
     $field->saveInto($article);
     $article = Dataobject::get_by_id('ListboxFieldTest_Article', $article->ID, false);
     $this->assertEquals(array(), $article->Tags()->sort('ID')->column('ID'));
 }
Beispiel #27
0
 /**
  * Copies the object to another container/object
  *
  * Note that this function, because it operates within the Object Store
  * itself, is much faster than downloading the object and re-uploading it
  * to a new object.
  *
  * @param DataObject $target the target of the COPY command
  */
 public function Copy(Dataobject $target)
 {
     $uri = sprintf('/%s/%s', $target->Container()->Name(), $target->Name());
     $this->debug('Copying object to [%s]', $uri);
     $response = $this->Service()->Request($this->Url(), 'COPY', array('Destination' => $uri));
     // check response code
     if ($response->HttpStatus() > 202) {
         throw new Exceptions\ObjectCopyError(sprintf(Lang::translate('Error copying object [%s], status [%d] response [%s]'), $this->Url(), $response->HttpStatus(), $response->HttpBody()));
     }
     return $response;
 }
 function Events()
 {
     $now = date('Y-m-d H:i:s');
     $oAllEvents = Dataobject::get('CleanUpGroup', "(ToDate > '{$now}')", 'FromDate ASC', '', 10);
     if ($oAllEvents) {
         return $oAllEvents;
     } else {
         return array('Events' => null, 'Message' => 'Sorry no events for us to show you');
     }
 }