public function getVars()
 {
     $vars = Variable::get();
     $var = array();
     foreach ($vars as $v) {
         $var[$v->section] = array("title" => $v->title, "subtitle" => $v->subtitle, "body" => $v->body);
     }
     $var["months"] = array("فروردین", "اردیبهشت", "خرداد", "تیر", "مرداد", "شهریور", "مهر", "آبان", "آذر", "دی", "بهمن", "اسفند");
     return $var;
 }
 /**
  * Display a listing of the resource.
  *
  * @return Response
  */
 public function index()
 {
     $datasets = Dataset::all();
     $datasources = Datasource::all();
     $variables = Variable::all();
     $categories = DatasetCategory::all();
     $subcategories = DatasetSubcategory::all();
     $varTypes = VariableType::all();
     $sourceTemplate = Setting::where('meta_name', 'sourceTemplate')->first();
     $data = ['datasets' => $datasets, 'datasources' => $datasources, 'variables' => $variables, 'categories' => $categories, 'subcategories' => $subcategories, 'varTypes' => $varTypes, 'sourceTemplate' => $sourceTemplate];
     $response = view('import.index')->with('data', $data);
     return $response;
 }
 public function scopeUpdateSource($query, $variableId, $newDatasourceId)
 {
     if (!empty($newDatasourceId)) {
         $variable = Variable::find($variableId);
         //is it event necessary to update source?
         if ($variable->fk_dsr_id != $newDatasourceId) {
             //it is update both variable source all sources of all variable values
             $variable->fk_dsr_id = $newDatasourceId;
             $variable->save();
             //update all variable values
             DataValue::where('fk_var_id', $variable->id)->update(array('fk_dsr_id' => $newDatasourceId));
         }
     }
 }
 /**
  * Run the migrations.
  *
  * @return void
  */
 public function up()
 {
     DB::transaction(function () {
         Schema::table('variables', function ($table) {
             $table->string('uploaded_by')->nullable();
             $table->foreign('uploaded_by')->references('name')->on('users');
             $table->timestamp('uploaded_at');
         });
         foreach (Variable::all() as $var) {
             $var->uploaded_at = $var->created_at;
             $var->save();
         }
     });
 }
 public function scopeUpdateSource($query, $datasetId, $newDatasourceId)
 {
     if (!empty($newDatasourceId)) {
         $dataset = Dataset::find($datasetId);
         //is it event necessary to update source?
         if ($dataset->fk_dsr_id != $newDatasourceId) {
             //get all variables
             $variables = $dataset->variables;
             foreach ($variables as $variable) {
                 Variable::updateSource($variable->id, $newDatasourceId);
             }
         }
     }
 }
 /**
  * Bootstrap any application services.
  *
  * @return void
  */
 public function boot()
 {
     try {
         $nomEcole = Variable::whereKey('ECOLE_NOM')->first();
         if ($nomEcole) {
             view()->share('schoolName', $nomEcole);
         }
     } catch (QueryException $e) {
         //NOTHING
     }
     try {
         $logoEcole = Variable::whereKey('ECOLE_LOGO')->first();
         if ($logoEcole) {
             view()->share('schoolLogo', $logoEcole);
         }
     } catch (QueryException $e) {
         //NOTHING
     }
 }
 public function insertQuery(Request $request)
 {
     $type = $request->input('type');
     $tag = $request->input('tags');
     $id = $request->input('id');
     $mode = $request->input('mode');
     ////////////////////////////////////
     //mode = 0 edit , mode = 1 insert///
     ////////////////////////////////////
     if ($type == 'events') {
         $validator = Validator::make($request->all(), ['title' => 'required', 'address' => 'required', 'body' => 'required', 'tags' => 'required|array']);
         if ($validator->fails()) {
             return redirect()->back()->withErrors($validator)->withInput()->with(array('errorcode' => 'events', 'tags' => $this->returnTags()));
         } else {
             if ($mode == 1) {
                 $event = new Event();
                 $content = new Content();
             } else {
                 $event = Event::find($id);
                 $content = $event->content;
             }
             $content->title = $request->input('title');
             $event->address = $request->input('address');
             $content->body = $request->input('body');
             $content->type = $type;
             $content->save();
             $start = $request->input('start-day') . "|" . $request->input('start-month') . "|" . $request->input('start-year') . "|" . $request->input('start-hour') . ":" . $request->input('start-minute');
             $end = $request->input('end-day') . "|" . $request->input('end-month') . "|" . $request->input('end-year') . "|" . $request->input('end-hour') . ":" . $request->input('end-minute');
             $event->start = $start;
             $event->end = $end;
             $event->highlight = $request->input('highlight') == NULL ? 0 : 1;
             $files = $request->file('img');
             foreach ($files as $file) {
                 if ($file->isValid()) {
                     $photo = new Photo();
                     $tempName = $file->getClientOriginalName();
                     $extension = explode(".", $tempName);
                     $name = $extension[0] . "-" . time() . "." . $extension[1];
                     $destination = 'upload';
                     $file->move($destination, $name);
                     $photo->path = $destination . "/" . $name;
                     $content->photos()->save($photo);
                 }
             }
             if (!empty($tag)) {
                 foreach ($tag as $insertTag) {
                     $row = Tag::where('title', '=', $insertTag)->first();
                     $content->tags()->save($row);
                 }
             }
             $cat = Category::where('title', '=', $request->input('category'))->first();
             if ($cat != null) {
                 $content->categories()->attach($cat->id);
             }
             $content->event()->save($event);
             return redirect('admin');
         }
     } elseif ($type == 'members') {
         $validator = Validator::make($request->all(), ['firstname' => 'required', 'lastname' => 'required', 'email' => 'required']);
         if ($validator->fails()) {
             return redirect()->back()->withErrors($validator)->withInput()->with(array('errorcode' => 'members', 'tags' => $this->returnTags()));
         } else {
             if ($mode == 1) {
                 $member = new Member();
             } else {
                 $member = Member::find($id);
             }
             $member->firstname = $request->input('firstname');
             $member->lastname = $request->input('lastname');
             $member->email = $request->input('email');
             //$member->password = $request->input('password');
             $member->researchareas = $request->input('researchareas') == NULL ? NULL : $request->input('researchareas');
             $member->industrialareas = $request->input('intery') == NULL ? NULL : $request->input('industry');
             $member->tel = $request->input('telephone') == NULL ? NULL : $request->input('telephone');
             $member->mobile = $request->input('mobile') == NULL ? NULL : $request->input('mobile');
             $member->position = $request->input('position') == NULL ? NULL : $request->input('position');
             $member->googleplus = $request->input('googleplus') == NULL ? NULL : $request->input('pinterest');
             $member->facebook = $request->input('facebook') == NULL ? NULL : $request->input('facebook');
             $member->twitter = $request->input('twitter') == NULL ? NULL : $request->input('instagram');
             $member->linkedin = $request->input('linkedin') == NULL ? NULL : $request->input('linkedin');
             if ($request->hasFile('img')) {
                 $file = $request->file('img');
                 if ($file->isValid()) {
                     $photo = new Photo();
                     $tempName = $file->getClientOriginalName();
                     $extension = explode(".", $tempName);
                     $name = $extension[0] . "-" . time() . "." . $extension[1];
                     $destination = 'upload';
                     $file->move($destination, $name);
                     //$photo->title = $request->input('photoTitle');
                     $photo->path = $destination . "/" . $name;
                     Photo::where("member_id", $member->id)->delete();
                     $member->photo()->save($photo);
                 }
             }
             if ($request->hasFile('cv')) {
                 $file = $request->file('cv');
                 if ($file->isValid()) {
                     $tempName = $file->getClientOriginalName();
                     $extension = explode(".", $tempName);
                     $name = $extension[0] . "-" . time() . "." . $extension[count($extension) - 1];
                     $destination = 'upload';
                     $file->move($destination, $name);
                     $member->cv = $destination . "/" . $name;
                 }
             }
             $member->save();
             if ($mode == 0) {
                 $record = Member::find($id)->records;
                 foreach ($record as $rec) {
                     $rec->delete();
                 }
             }
             $recordArray = $request->input('rec');
             if (!empty($recordArray)) {
                 foreach ($recordArray as $key) {
                     if (empty($key['delete'])) {
                         $key['delete'] = 'off';
                     }
                     if ($key['delete'] != "on" && $key['institute'] != "") {
                         $record = new Record();
                         $record->institute = $key['institute'];
                         $record->position = $key['position'];
                         $record->start = $key['start'];
                         $record->end = $key['end'];
                         $record->type = $key['type'];
                         $member->records()->save($record);
                     }
                 }
             }
             // $cat = Category::where('title', '=', $request->input('category'))->first();
             return redirect('admin');
         }
     } elseif ($type == 'researches') {
         $validator = Validator::make($request->all(), ['author' => 'required', 'title' => 'required', 'abstract' => 'required']);
         if ($validator->fails()) {
             return redirect()->back()->withErrors($validator)->withInput()->with(array('errorcode' => 'researches', 'tags' => $this->returnTags()));
         } else {
             if ($mode == 1) {
                 $research = new Research();
                 $content = new Content();
             } else {
                 $research = Research::find($id);
                 $content = $research->content;
             }
             $content->title = $request->input('title');
             $content->body = $request->input('abstract');
             $content->type = $type;
             $content->save();
             $research->author = $request->input('author');
             $research->publisher = $request->input('publisher') == NULL ? NULL : $request->input('publisher');
             $date = $request->input('date-year') . "|" . $request->input('date-month') . "|" . $request->input('date-day') . "|" . $request->input('date-hour') . ":" . $request->input('date-minute');
             $research->date = $date;
             $research->external = $request->input("external") == NULL ? true : false;
             $research->pages = $request->input('pages') == NULL ? NULL : $request->input('pages');
             //                $research->abstract = $request->input('abstract') == NULL ? NULL : $request->input('abstract');
             $research->keywords = $request->input('keywords') == NULL ? NULL : $request->input('keywords');
             $research->link = $request->input('link') == NULL ? NULL : $request->input('link');
             $path = $request->file('path');
             if (!empty($path) && $path->isValid()) {
                 $tempName = $path->getClientOriginalName();
                 $extension = explode(".", $tempName);
                 $name = $extension[0] . time() . "." . $extension[count($extension) - 1];
                 $destination = 'upload';
                 $path->move($destination, $name);
                 $research->path = $destination . "/" . $name;
             }
             if (!empty($tag)) {
                 foreach ($tag as $insertTag) {
                     $row = Tag::where('title', '=', $insertTag)->first();
                     $content->tags()->save($row);
                 }
             }
             $research->content()->associate($content);
             $research->save();
             $cat = Category::where('title', '=', $request->input('category'))->first();
             if ($cat != null) {
                 $content->categories()->attach($cat->id);
             }
             return redirect('admin');
         }
     } elseif ($type == 'galleries') {
         $validator = Validator::make($request->all(), ['title' => 'required', 'body' => 'required']);
         if ($validator->fails()) {
             return redirect()->back()->withErrors($validator)->withInput()->with(array('errorcode' => 'galleries', 'tags' => $this->returnTags()));
         } else {
             if ($mode == 1) {
                 $content = new Content();
             } else {
                 $content = Content::find($id);
             }
             $content->title = $request->input('title');
             $content->body = $request->input('body');
             $content->type = $type;
             $content->save();
             if ($request->hasFile('img')) {
                 $file = $request->file('img');
                 for ($i = 0; $i < count($file); $i++) {
                     if ($file[$i]->isValid()) {
                         $photo = new Photo();
                         $tempName = $file[$i]->getClientOriginalName();
                         $extension = explode(".", $tempName);
                         $name = $extension[0] . "-" . time() . (string) $i . "." . $extension[count($extension) - 1];
                         $destination = 'upload';
                         $file[$i]->move($destination, $name);
                         $photo->title = $request->input('imgtitle')[$i];
                         $photo->path = $destination . "/" . $name;
                         $photo->highlight = $request->input("highlight")[$i] == "true" ? 1 : 0;
                         $content->photos()->save($photo);
                     }
                 }
             }
             if ($mode != 1) {
                 if (!empty($request->input('oldimg'))) {
                     foreach ($request->input('oldimg') as $img) {
                         if (empty($img['delete'])) {
                             $img['delete'] = "off";
                             $image = Photo::find($img['id']);
                             $image->title = $img['title'];
                             $image->highlight = $img['highlight'] == "true" ? 1 : 0;
                             $image->save();
                         }
                         if ($img['delete'] == "on") {
                             $temp = Photo::find($img['id']);
                             $temp->delete();
                         }
                     }
                 }
             }
             if (!empty($tag)) {
                 foreach ($tag as $insertTag) {
                     $row = Tag::where('title', '=', $insertTag)->first();
                     $content->tags()->save($row);
                 }
             }
             $cat = Category::where('title', '=', $request->input('category'))->first();
             if ($cat != null) {
                 $content->categories()->attach($cat->id);
             }
             return redirect('admin');
         }
     } elseif ($type == 'tags') {
         $input = $request->all();
         $split = explode("#", $input['body']);
         for ($i = 0; $i < count($split); $i++) {
             if (!empty($split[$i]) && $split[$i] != '') {
                 $tag = new Tag();
                 $tag->title = trim($split[$i]);
                 $tag->save();
             }
         }
         return redirect('admin');
     } elseif ($type == 'categories') {
         $cat = new Category();
         $cat->title = $request->input("title");
         $cat->parent = $request->input("cat-id");
         if ($cat->parent == 0) {
             $cat->parent = null;
         }
         $cat->save();
         return redirect('admin');
     } elseif ($type == "variables") {
         $var = Variable::find($id);
         $var->title = $request->input("title");
         $var->subtitle = $request->input("subtitle");
         $var->body = $request->input("body");
         if ($request->hasFile('img')) {
             $file = $request->file('img');
             if ($file->isValid()) {
                 $tempName = $file->getClientOriginalName();
                 $extension = explode(".", $tempName);
                 $name = $extension[0] . "-" . time() . "." . $extension[count($extension) - 1];
                 $destination = 'upload';
                 $file->move($destination, $name);
                 //$photo->title = $request->input('photoTitle');
                 $var->body = $destination . "/" . $name;
             }
         }
         $var->save();
         return redirect('admin');
     } else {
         $validator = Validator::make($request->all(), ['title' => 'required', 'body' => 'required', 'tags' => 'required|array']);
         if ($validator->fails()) {
             return redirect()->back()->withErrors($validator)->withInput()->with(array('errorcode' => 'news', 'tags' => $this->returnTags()));
         } else {
             if ($mode == 1) {
                 $news = new Content();
             } else {
                 $news = Content::find($id);
             }
             $news->title = $request->input('title');
             $news->body = $request->input('body');
             $news->type = $type;
             $news->save();
             if ($request->hasFile('img')) {
                 $files = $request->file('img');
                 if ($mode == 0) {
                     $oldphoto = Photo::where("content_id", $id)->first();
                     $oldphoto->delete();
                 }
                 foreach ($files as $file) {
                     if ($file->isValid()) {
                         $photo = new Photo();
                         $tempName = $file->getClientOriginalName();
                         $extension = explode(".", $tempName);
                         $name = $extension[0] . "-" . time() . "." . $extension[count($extension) - 1];
                         $destination = 'upload';
                         $file->move($destination, $name);
                         //$photo->title = $request->input('photoTitle');
                         $photo->path = $destination . "/" . $name;
                         $news->photos()->save($photo);
                     }
                 }
             }
             if (!empty($tag)) {
                 foreach ($tag as $insertTag) {
                     $row = Tag::where('title', '=', $insertTag)->first();
                     $news->tags()->save($row);
                 }
             }
             $cat = Category::find($request->input('cat-id'));
             if ($cat != null) {
                 $news->categories()->attach($cat->id);
             }
             return redirect('admin');
         }
     }
 }
 public function dimensions(Request $request)
 {
     set_time_limit(10);
     ini_set('memory_limit', '256M');
     //check we have everything we should have
     if (!Input::has('dimensions')) {
         //we don't have necessary info, bail out
         return ['success' => false];
     }
     //filtering by entities?
     $selectedCountriesIds = Input::get("selectedCountries");
     $selectedCountriesIdsString = !empty($selectedCountriesIds) && count($selectedCountriesIds) > 0 ? implode(",", $selectedCountriesIds) : "";
     //filtering by time?
     $chartTime = Input::get("chartTime");
     if (Input::has('chartId')) {
         //caching - construct key with selected countries as well
         $key = 'chart-dimensions-' . Input::get('chartId') . '-countries-' . $selectedCountriesIdsString;
         //if there's something in cache and not exporting
         if (Cache::has($key) && !Input::has('export') && (Input::has('cache') && Input::get('cache') === "true")) {
             //return Cache::get( $key );
         }
     }
     $data = array();
     //extra array for storing values for export
     $times = array();
     $datasourcesIdsArr = array();
     $dimensionsInput = Input::get('dimensions');
     $dimensions = json_decode($dimensionsInput);
     //isn't it just empty object
     if (empty($dimensions)) {
         return ['success' => false];
     }
     $chartType = Input::get('chartType');
     //there's special setting for linechart
     $isLineChart = $chartType == "1" || $chartType == "4" || $chartType == "5" || $chartType == "6" ? true : false;
     //find out how many variables we have
     $groupByEntity = Input::get('groupByVariables') == 'false' ? true : false;
     //special case for linechart with multiple variables
     $multiVariantByEntity = false;
     if ($groupByEntity && $isLineChart && count($dimensions) > 1) {
         //make sure they're all
         foreach ($dimensions as $dimension) {
             if ($dimension->property !== "y") {
                 $multiVariantByEntity = false;
                 break;
             }
             $multiVariantByEntity = true;
         }
     }
     $timeType = '';
     if ($groupByEntity) {
         $entities = array();
         $dataByEntity = array();
         $dataByEntityTime = array();
     } else {
         $variables = array();
         $dataByVariable = array();
         $dataByVariableTime = array();
     }
     /**
      * 1) get data into variable
      **/
     //store the longest variable, will be used as main one
     $dimensionsByKey = [];
     $minDataLength = false;
     $mainDimId = false;
     $otherDimIds = [];
     //for edge cases for legend, we need to store entityname
     $entityName = "";
     //categorical data
     $categoricalData = array();
     $categoricalData["color"] = array();
     $categoricalData["shape"] = array();
     $categoricalDimensions = array();
     foreach ($dimensions as $dimension) {
         $id = $dimension->variableId;
         //use query builder instead of eloquent
         $variableQuery = DB::table('data_values')->select('data_values.*', 'times.*', 'entities.name as name', 'variables.name as variable_name')->join('entities', 'data_values.fk_ent_id', '=', 'entities.id')->join('variables', 'data_values.fk_var_id', '=', 'variables.id')->join('times', 'data_values.fk_time_id', '=', 'times.id')->where('data_values.fk_var_id', $id);
         //are we filtering based on entity selection?
         if (!empty($selectedCountriesIds) && count($selectedCountriesIds) > 0) {
             $variableQuery->whereIn('data_values.fk_ent_id', $selectedCountriesIds);
         }
         //are we filtering based on time selection?
         if (!empty($chartTime) && count($chartTime) > 1) {
             //exclude categorical properties from time filtering
             if ($dimension->property !== "color" && $dimension->property !== "shape") {
                 $minTime = $chartTime[0];
                 $maxTime = $chartTime[1];
                 $variableQuery->where('times.startDate', '>=', $minTime);
                 //$variableQuery->where( 'times.date', '>=', $minTime );
                 $variableQuery->where('times.endDate', '<=', $maxTime);
                 //$variableQuery->where( 'times.date', '<=', $maxTime );
             }
         }
         $variableData = $variableQuery->get();
         //insert data into existing variable
         $dimension->data = $variableData;
         //is shortes variable? cannot be color/shape variable
         $dataLen = count($variableData);
         if (($dataLen > $minDataLength || !$minDataLength) && ($dimension->property != "color" && $dimension->property != "shape")) {
             $minDataLength = $dataLen;
             $mainDimId = $id;
         }
         //is categorical data
         if ($dimension->property === "color" || $dimension->property === "shape") {
             //store it for later processing
             $categoricalDimensions[] = $dimension;
         }
     }
     /**
      * 2) assign data to entities
      **/
     foreach ($dimensions as $dimension) {
         $id = $dimension->variableId;
         $property = $dimension->property;
         $variableData = $dimension->data;
         //store in array for step 3
         $dimensionsByKey[$id] = $dimension;
         if ($id != $mainDimId) {
             $otherDimIds[] = $id;
         }
         //selectedCountries
         if ($groupByEntity) {
             //group variable data by entities
             //$i = 0;
             $oldEntityId = -1;
             foreach ($variableData as $datum) {
                 //$entityId = $datum->fk_ent_id;
                 $entityId = !$multiVariantByEntity ? $datum->fk_ent_id : $datum->fk_ent_id . "-" . $datum->fk_var_id;
                 //check if new entity and we need to reset cycle
                 if ($oldEntityId != $entityId) {
                     //$i = 0;
                 }
                 $oldEntityId = $entityId;
                 //do we have already object for that entity
                 if (!array_key_exists($entityId, $dataByEntity)) {
                     $key = !$multiVariantByEntity ? $datum->name : $datum->name . " - " . $datum->variable_name;
                     $dataByEntity[$entityId] = array("id" => $entityId, "key" => $key, "entity" => $datum->name, "values" => []);
                 }
                 //is it first property being saved for given property
                 if (!array_key_exists($property, $dataByEntity[$entityId]["values"])) {
                     $dataByEntity[$entityId]["values"][$property] = [];
                 }
                 //store value
                 //AMMEND HERE - store as startYear-endYear?
                 $timeId = $datum->fk_ttype_id !== "6" ? floatval($datum->date) : floatval($datum->startDate) . "-" . floatval($datum->endDate);
                 $dataByEntity[$entityId]["values"][$property][$timeId] = $property != "color" && $property != "shape" && $property != "map" ? floatval($datum->value) : $datum->value;
                 //need to store dimension variablename, dimensions are returned
                 if (!array_key_exists("variableName", $dimension)) {
                     $dimension->variableName = $datum->variable_name;
                 }
                 //if is linechart, store time into x axis
                 /*if( $isLineChart ) {
                 			$dataByEntity[ $entityId ][ "values" ][ $i ][ "x" ] = floatval( $datum->date );
                 		}
                 		$i++;*/
                 //store time type if not stored
                 if (empty($timeType)) {
                     $timeType = TimeType::find($datum->fk_ttype_id)->name;
                 }
                 //store for the need of export
                 if (!array_key_exists($entityId, $dataByEntityTime)) {
                     $dataByEntityTime[$entityId] = [];
                     $entities[$entityId] = $datum->name;
                 }
                 $dataByEntityTime[$entityId][$datum->label] = $datum->value;
                 //AMMEND HERE - store simply as a string?
                 $times[floatval($datum->date)] = true;
                 $datasourcesIdsArr[$datum->fk_dsr_id] = true;
             }
         } else {
             //multivariables
             //get variable names
             $variable = Variable::find($dimension->variableId);
             $key = !empty($variable) && isset($variable->name) ? $variable->name : "";
             //could have display name
             if (!empty($dimension) && !empty($dimension->displayName)) {
                 $key = $dimension->displayName;
             }
             $dataByVariable["id-" . $id] = array("id" => $id, "key" => $key, "values" => []);
             //store variable name to dimension info (useful for stack bar chart)
             $dimensionsByKey[$id]->variableName = $key;
             foreach ($variableData as $datum) {
                 //store entity name for legend purposes
                 $entityName = $datum->name;
                 $dataByVariable["id-" . $id]["values"][] = array("x" => floatval($datum->date), "y" => floatval($datum->value));
                 $times[$datum->label] = true;
                 $datasourcesIdsArr[$datum->fk_dsr_id] = true;
                 //store time type if not stored
                 if (empty($timeType)) {
                     $timeType = TimeType::find($datum->fk_ttype_id)->name;
                 }
                 //store for the need of export
                 if (!array_key_exists($dimension->variableId, $dataByVariableTime)) {
                     $dataByVariableTime[$dimension->variableId] = [];
                     $variables[$dimension->variableId] = $datum->fk_var_id;
                 }
                 $dataByVariableTime[$dimension->variableId][$datum->label] = $datum->value;
             }
         }
     }
     /**
      * 3) prepare array for different chart types
      **/
     //$normalizedData = [];
     $mainDimension = $dimensionsByKey[$mainDimId];
     if ($groupByEntity) {
         $normalizedData = Chart::formatDataForChartType($chartType, $dataByEntity, $dimensionsByKey, $times, false, $mainDimension, $otherDimIds);
     } else {
         //grouping by variable, for linechart, we already have what we need
         if ($chartType !== '1' && $chartType !== '2') {
             $dataByVariable = Chart::formatDataForChartType($chartType, $dataByVariableTime, $dimensionsByKey, $times, true, $mainDimension, $otherDimIds, $entityName);
         }
     }
     if ($chartType == '9999') {
         //if getting dimensions for map, don't need info bellow, just send of the data
         $data = [];
         foreach ($normalizedData as $entityData) {
             $data[] = $entityData;
         }
         $result = ['success' => true, 'data' => $data];
         //TODO - put to cache
         //store into cache - there is no cache
         /*if( !empty( $key ) ) {
         			$minutes = 60*24;
         			Cache::put( $key, $result, $minutes );
         		}*/
         return $result;
     }
     if ($groupByEntity) {
         //convert to array
         foreach ($normalizedData as $entityData) {
             //TODO better check for this?
             if ($entityData['values']) {
                 //here we add any possible categorical data
                 foreach ($categoricalDimensions as $catDimension) {
                     $entityId = $entityData['id'];
                     //is there data for specific property
                     if (array_key_exists('values', $dataByEntity[$entityId]) && array_key_exists($catDimension->property, $dataByEntity[$entityId]['values'])) {
                         //get value - http://stackoverflow.com/questions/1028668/get-first-key-in-a-possibly-associative-array
                         $value = reset($dataByEntity[$entityId]['values'][$catDimension->property]);
                         $catValue = Chart::getValueForCategory($catDimension->property, $categoricalData, $value);
                         //color is assinged to whole entity, shape is assigned to individual data entries
                         if ($catDimension->property === "color") {
                             $entityData[$catDimension->property] = $catValue;
                         } else {
                             if ($catDimension->property === "shape") {
                                 foreach ($entityData["values"] as &$entityValue) {
                                     $entityValue[$catDimension->property] = $catValue;
                                 }
                             }
                         }
                     }
                 }
                 $data[] = $entityData;
             }
         }
     } else {
         //convert to array
         foreach ($dataByVariable as $varData) {
             $data[] = $varData;
         }
     }
     /**
      *	4) fetch all the other necessary data
      **/
     //get all necessary info for datasources
     $datasources = array();
     $prevDimension = "";
     $sourcesByNameDim = array();
     foreach ($dimensions as $dimension) {
         $datasource = new \stdClass();
         //special dimension header for linechart
         $dsr = Variable::getSource($dimension->variableId)->first();
         if ($isLineChart) {
             $dimension = false;
         }
         $currDimension = !empty($dimension) && isset($dimension->name) ? $dimension->name : "undefined";
         $datasource->description = !empty($dsr) ? $this->createSourceDescription($dimension, $dsr, $currDimension === $prevDimension) : '';
         $datasource->name = !empty($dsr) && !empty($dsr->name) ? $dsr->name : '';
         $datasource->link = !empty($dsr) && !empty($dsr->name) ? $dsr->link : '';
         //make sure we don't repeat for the same name and dimension
         $nameDimKey = $currDimension . "-" . $datasource->name;
         if (!isset($sourcesByNameDim[$nameDimKey])) {
             $datasources[] = $datasource;
             $sourcesByNameDim[$nameDimKey] = true;
         }
         //store curr dimension so we don't have to repeat title for next if it's same
         $prevDimension = !empty($dimension) && isset($dimension->name) ? $dimension->name : "";
     }
     /*$datasourcesIds = array_keys( $datasourcesIdsArr );
     		$datasourcesSources = Variable::getSources( $datasourcesIds )->get();//Datasource::findMany( $datasourcesIds );
     		$datasources = array();
     
     		//format datasources info (create generated tables)
     		foreach( $datasourcesSources as $datasourceSource ) {
     			$datasource = new \stdClass();
     			$dimension = $this->findDimensionForVarId( $dimensions, $datasourceSource->var_id );
     			//special dimension header for linechart
     			if( $isLineChart ) {
     				$dimension = false;
     			}
     			$datasource->description = $this->createSourceDescription( $dimension, $datasourceSource );
     			$datasource->name = $datasourceSource->name;
     			$datasource->link = $datasourceSource->link;
     			//$datasource->description = $datasourceSource->description;
     			$datasources[] = $datasource;
     		}*/
     //process data to csv friendly format
     $timeKeys = array_keys($times);
     //sort timeKeys by time
     //AMMEND HERE - what is intervals
     usort($timeKeys, function ($a, $b) {
         if ($a == $b) {
             return 0;
         } else {
             return $a > $b ? 1 : -1;
         }
     });
     //get all the licence information
     $license = License::find(1)->first();
     if ($request->ajax()) {
         $result = ['success' => true, 'data' => $data, 'dimensions' => $dimensions, 'datasources' => $datasources, 'timeType' => $timeType, 'license' => $license];
         //store into cache - there is no cache
         if (!empty($key)) {
             $minutes = 60 * 24;
             Cache::put($key, $result, $minutes);
         }
         return $result;
     } else {
         //export is now happening in front-end
         if (Input::has('export') && Input::get('export') == 'csv') {
             //http://localhost:8888/oxford/our-world-in-data-chart-builder/public/data/dimensions?dimensions=%5B%7B%22variableId%22%3A%221%22%2C%22property%22%3A%22y%22%2C%22name%22%3A%22Y+axis%22%7D%5D
             //return $data;
             //return $this->downloadCsv( $exportData );
         } else {
             //not ajax request, nor csv export, just spit out whatever is in data
             return $data;
         }
     }
 }
 public function updateSource(Variable $variable, $newDatasourceId)
 {
     if (!empty($newDatasourceId)) {
         //is it event necessary to update source?
         if ($variable->fk_dsr_id != $newDatasourceId) {
             //it is update both variable source all sources of all variable values
             $variable->fk_dsr_id = $newDatasourceId;
             $variable->save();
             //update all variable values
             DataValue::where('fk_var_id', $variable->id)->update(array('fk_dsr_id' => $newDatasourceId));
             Cache::flush();
         }
     }
 }
 /**
  * Show the form for editing the specified resource.
  *
  * @param  int  $id
  * @return Response
  */
 public function edit(Chart $chart, Request $request)
 {
     $config = json_decode($chart->config);
     if ($request->ajax()) {
         return response()->json($config);
     } else {
         $data = new \StdClass();
         $data->variables = Variable::with('Dataset')->get();
         $data->categories = DatasetCategory::all();
         $data->subcategories = DatasetSubcategory::all();
         $data->chartTypes = ChartType::lists('name', 'id');
         $logoUrl = Setting::where('meta_name', 'logoUrl')->first();
         $data->logoUrl = !empty($logoUrl) ? url('/') . '/' . $logoUrl->meta_value : '';
         return view('charts.edit', compact('chart'))->with('data', $data);
     }
 }
Beispiel #11
0
 private function variables()
 {
     return Variable::get();
 }
 /**
  * Run the database seeds.
  *
  * @return void
  */
 public function run()
 {
     // General
     \App\Language::create(['code' => 'es', 'name' => 'Español', 'image' => 'es.png']);
     \App\Site::create(['name' => 'Plataforma ', 'domain' => 'http://mimg.dev/', 'root' => '/', 'es' => ['title' => 'PROGRAMA MUNICIPAL DE RECONOCIMIENTO Y FOMENTO A INICIATIVAS SOSTENIBLES', 'description' => 'Nuestro objetivo es programar la plataforma del Programa Municipal de Reconocimiento y Fomento a Iniciativas Sostenibles en formato es php y sql para entorno web, en base a un contenido y diseño previamente definido.', 'keywords' => 'programa, municipal, iniciativas sostenibles, medio ambiente, guayaquil, ecuador'], 'google_verification' => '', 'analytics' => '']);
     // Nodos
     $node_registry_a = \App\Node::create(['name' => 'registry-a', 'table_name' => 'registry_a', 'type' => 'form']);
     \App\NodeExtra::create(['parent_id' => $node_registry_a->id, 'display' => 'admin', 'type' => 'filter', 'parameter' => 'field', 'value_array' => json_encode(['status', 'company_type', 'guayaquil_zone'])]);
     \App\NodeExtra::create(['parent_id' => $node_registry_a->id, 'display' => 'admin', 'type' => 'graph', 'parameter' => 'pie', 'value_array' => json_encode(['status', 'company_type', 'guayaquil_zone'])]);
     $node_registry_b = \App\Node::create(['name' => 'registry-b', 'table_name' => 'registry_b', 'type' => 'form']);
     \App\NodeExtra::create(['parent_id' => $node_registry_b->id, 'display' => 'admin', 'type' => 'filter', 'parameter' => 'field', 'value_array' => json_encode(['status', 'clasification', 'guayaquil_belongs'])]);
     \App\NodeExtra::create(['parent_id' => $node_registry_b->id, 'display' => 'admin', 'type' => 'graph', 'parameter' => 'pie', 'value_array' => json_encode(['status', 'clasification', 'guayaquil_belongs'])]);
     $node_postulation_a = \App\Node::create(['name' => 'postulation-a', 'table_name' => 'postulation_a', 'type' => 'form']);
     \App\NodeExtra::create(['parent_id' => $node_postulation_a->id, 'display' => 'admin', 'type' => 'filter', 'parameter' => 'field', 'value_array' => json_encode(['status'])]);
     \App\NodeExtra::create(['parent_id' => $node_postulation_a->id, 'display' => 'admin', 'type' => 'filter', 'parameter' => 'parent_field', 'value_array' => json_encode([['name' => 'guayaquil_zone', 'parent' => 'registry-a', 'data' => 'registry_a_id'], ['name' => 'company_type', 'parent' => 'registry-a', 'data' => 'registry_a_id']])]);
     \App\NodeExtra::create(['parent_id' => $node_postulation_a->id, 'display' => 'admin', 'type' => 'graph', 'parameter' => 'pie', 'value_array' => json_encode(['status'])]);
     \App\NodeExtra::create(['parent_id' => $node_postulation_a->id, 'display' => 'admin', 'type' => 'parent_graph', 'parameter' => 'pie', 'value_array' => json_encode([['name' => 'guayaquil_zone', 'parent' => 'registry_a', 'data' => 'registry_a_id'], ['name' => 'company_type', 'parent' => 'registry_a', 'data' => 'registry_a_id']])]);
     $node_postulation_b = \App\Node::create(['name' => 'postulation-b', 'table_name' => 'postulation_b', 'type' => 'form']);
     \App\NodeExtra::create(['parent_id' => $node_postulation_b->id, 'display' => 'admin', 'type' => 'filter', 'parameter' => 'field', 'value_array' => json_encode(['status'])]);
     \App\NodeExtra::create(['parent_id' => $node_postulation_b->id, 'display' => 'admin', 'type' => 'filter', 'parameter' => 'parent_field', 'value_array' => json_encode([['name' => 'guayaquil_belongs', 'parent' => 'registry-b', 'data' => 'registry_b_id'], ['name' => 'clasification', 'parent' => 'registry-b', 'data' => 'registry_b_id']])]);
     \App\NodeExtra::create(['parent_id' => $node_postulation_b->id, 'display' => 'admin', 'type' => 'graph', 'parameter' => 'pie', 'value_array' => json_encode(['status'])]);
     \App\NodeExtra::create(['parent_id' => $node_postulation_b->id, 'display' => 'admin', 'type' => 'parent_graph', 'parameter' => 'pie', 'value_array' => json_encode([['name' => 'guayaquil_belongs', 'parent' => 'registry_b', 'data' => 'registry_b_id'], ['name' => 'clasification', 'parent' => 'registry_b', 'data' => 'registry_b_id']])]);
     $node_deadlines = \App\Node::create(['name' => 'deadline']);
     $node_social_network = \App\Node::create(['name' => 'social-network', 'table_name' => 'social_networks', 'location' => 'app', 'type' => 'global', 'model' => '\\App\\SocialNetwork']);
     $node_title = \App\Node::create(['name' => 'title']);
     $node_content = \App\Node::create(['name' => 'content']);
     $node_banner = \App\Node::create(['name' => 'banner']);
     $node_agenda = \App\Node::create(['name' => 'agenda']);
     $node_sponsor = \App\Node::create(['name' => 'sponsor']);
     $node_contact = \App\Node::create(['name' => 'contact', 'table_name' => 'contact']);
     $node_form_contact = \App\Node::create(['name' => 'form-contact', 'type' => 'form', 'table_name' => 'form_contact']);
     // Menu: Home
     $page_home = \App\Page::create(['type' => 'customized', 'customized_name' => 'home', 'es' => ['name' => 'Inicio']]);
     \App\Menu::create(['page_id' => $page_home->id]);
     \App\Section::create(['id' => 1, 'page_id' => $page_home->id, 'node_id' => $node_title->id]);
     \App\Section::create(['id' => 2, 'page_id' => $page_home->id, 'node_id' => $node_content->id]);
     \App\Section::create(['id' => 3, 'page_id' => $page_home->id, 'node_id' => $node_title->id]);
     \App\Section::create(['id' => 4, 'page_id' => $page_home->id, 'node_id' => $node_agenda->id]);
     \App\Section::create(['id' => 5, 'page_id' => $page_home->id, 'node_id' => $node_title->id]);
     \App\Section::create(['id' => 6, 'page_id' => $page_home->id, 'node_id' => $node_sponsor->id]);
     // Menu: Sobre el Programa
     $page_programa = \App\Page::create(['es' => ['name' => 'Sobre el Programa']]);
     \App\Menu::create(['page_id' => $page_programa->id]);
     \App\Section::create(['id' => 7, 'page_id' => $page_programa->id, 'node_id' => $node_content->id]);
     // Menu: Categorias
     $page_categorias = \App\Page::create(['es' => ['name' => 'Categorias']]);
     \App\Menu::create(['page_id' => $page_categorias->id]);
     \App\Section::create(['id' => 8, 'page_id' => $page_categorias->id, 'node_id' => $node_content->id]);
     // Menu: Premios
     $page_premios = \App\Page::create(['es' => ['name' => 'Premios']]);
     \App\Menu::create(['page_id' => $page_premios->id]);
     \App\Section::create(['id' => 9, 'page_id' => $page_premios->id, 'node_id' => $node_content->id]);
     // Menu: Cronograma
     $page_cronograma = \App\Page::create(['es' => ['name' => 'Cronograma']]);
     \App\Menu::create(['page_id' => $page_cronograma->id]);
     \App\Section::create(['id' => 10, 'page_id' => $page_cronograma->id, 'node_id' => $node_content->id]);
     // Menu: Registro
     $menu_registro = \App\Menu::create(['type' => 'blank', 'es' => ['name' => 'Registro']]);
     $page_registro_a = \App\Page::create(['es' => ['name' => 'Registro A']]);
     \App\Menu::create(['level' => 2, 'parent_id' => $menu_registro->id, 'es' => ['name' => 'A. Distinción a empresas ambientalmente sostenibles', 'link' => 'registro-a']]);
     \App\Section::create(['id' => 11, 'page_id' => $page_registro_a->id, 'node_id' => $node_content->id]);
     \App\Section::create(['id' => 12, 'page_id' => $page_registro_a->id, 'node_id' => $node_registry_a->id]);
     $page_registro_b = \App\Page::create(['es' => ['name' => 'Registro B']]);
     \App\Menu::create(['level' => 2, 'parent_id' => $menu_registro->id, 'es' => ['name' => 'B. Capital semilla a iniciativas sostenibles', 'link' => 'registro-b']]);
     \App\Section::create(['id' => 13, 'page_id' => $page_registro_b->id, 'node_id' => $node_content->id]);
     \App\Section::create(['id' => 14, 'page_id' => $page_registro_b->id, 'node_id' => $node_registry_b->id]);
     // Page: Postulación A
     $page_postulacion_a = \App\Page::create(['es' => ['name' => 'Postulacion A']]);
     \App\Section::create(['id' => 15, 'page_id' => $page_postulacion_a->id, 'node_id' => $node_content->id]);
     \App\Section::create(['id' => 16, 'page_id' => $page_postulacion_a->id, 'node_id' => $node_postulation_a->id]);
     // Page: Postulación B
     $page_postulacion_b = \App\Page::create(['es' => ['name' => 'Postulacion B']]);
     \App\Section::create(['id' => 17, 'page_id' => $page_postulacion_b->id, 'node_id' => $node_content->id]);
     \App\Section::create(['id' => 18, 'page_id' => $page_postulacion_b->id, 'node_id' => $node_postulation_b->id]);
     // Menu: Contacto
     $page_contacto = \App\Page::create(['es' => ['name' => 'Contacto']]);
     \App\Menu::create(['page_id' => $page_contacto->id]);
     \App\Section::create(['id' => 19, 'page_id' => $page_contacto->id, 'node_id' => $node_contact->id]);
     \App\Section::create(['id' => 20, 'page_id' => $page_contacto->id, 'node_id' => $node_form_contact->id]);
     // Panel: Postulaciones
     $page_postulaciones = \App\Page::create(['type' => 'customized', 'customized_name' => 'postulaciones', 'es' => ['name' => 'Postulaciones']]);
     \App\Section::create(['id' => 21, 'page_id' => $page_postulaciones->id, 'node_id' => $node_content->id]);
     // Home Segunda Parte
     \App\Section::create(['id' => 22, 'page_id' => $page_home->id, 'node_id' => $node_banner->id]);
     // Crear menu en Admin
     /*$m_list = \App\Menu::create(['menu_type'=>'admin', 'icon'=>'th-list', 'es'=>['name'=>'Listas de Correos', 'link'=>'admin/model-list/target-list']]);
       $m_email = \App\Menu::create(['menu_type'=>'admin', 'icon'=>'th-list', 'es'=>['name'=>'Enviar Emails', 'link'=>'admin/model-list/email']]);
       $m_history = \App\Menu::create(['menu_type'=>'admin', 'icon'=>'th-list', 'es'=>['name'=>'Emails Enviados', 'link'=>'admin/model-list/sent-email']]);*/
     // Variables
     \App\Variable::create(['name' => 'admin_email', 'type' => 'string', 'es' => ['value' => '*****@*****.**']]);
     \Solunes\Master\App\Variable::create(['name' => 'footer_name', 'type' => 'string', 'es' => ['value' => 'GAD MUNICIPAL DE GUAYAQUIL - GUAYAQUIL, ECUADOR']]);
     \Solunes\Master\App\Variable::create(['name' => 'footer_rights', 'type' => 'string', 'es' => ['value' => 'TODOS LOS DERECHOS RESERVADOS']]);
     // Social Networks
     \App\SocialNetwork::create(['code' => 'facebook', 'url' => 'https://www.facebook.com/alcaldiaguayaquil/']);
     \App\SocialNetwork::create(['code' => 'twitter', 'url' => 'https://twitter.com/alcaldiagye/']);
     \App\SocialNetwork::create(['code' => 'youtube', 'url' => 'https://www.youtube.com/user/municipioguayaquil/']);
     \App\SocialNetwork::create(['code' => 'instagram', 'url' => 'https://www.instagram.com/municipiogye/']);
     /*factory(App\Customer::class, 30)->create();
       factory(App\CustomerPoint::class, 150)->create();
       factory(App\Operator::class, 100)->create(['city_id'=>$lpz->id]);
       factory(App\Operator::class, 100)->create(['city_id'=>$scz->id]);
       factory(App\OperatorAttendance::class, 100)->create(['operator_id'=>1, 'status'=>'1/2']);
       factory(App\OperatorAttendance::class, 100)->create(['operator_id'=>2, 'status'=>'O']);
       factory(App\Product::class, 20)->create(['type'=>'product']);
       factory(App\Product::class, 30)->create(['type'=>'implement']);*/
     /*factory(App\FilledForm::class, 50)->create(['form_id'=>1]);
       factory(App\FilledForm::class, 50)->create(['form_id'=>2]);
       factory(App\FilledForm::class, 50)->create(['form_id'=>3]);
       factory(App\FilledForm::class, 50)->create(['form_id'=>4]);
       factory(App\FilledForm::class, 50)->create(['form_id'=>5]);
       factory(App\FilledField::class, 50)->create(['filled_form_id'=>rand(1,50), 'field_id'=>rand(1,9)]);
       factory(App\FilledField::class, 50)->create(['filled_form_id'=>rand(51,100), 'field_id'=>rand(10,15)]);
       factory(App\FilledField::class, 50)->create(['filled_form_id'=>rand(101,150), 'field_id'=>rand(16,26)]);
       factory(App\FilledField::class, 50)->create(['filled_form_id'=>rand(151,200), 'field_id'=>rand(27,65)]);
       factory(App\FilledField::class, 50)->create(['filled_form_id'=>rand(201,250), 'field_id'=>rand(66,77)]);*/
     //factory(App\Questionnaire::class, 100)->create(['user_id'=>1]);
 }
Beispiel #13
0
 public function sitesUpdate()
 {
     echo "<pre>";
     // Limit the types of sites and variables loaded
     // change these to load more or less
     // Only interested in GAMUT sites
     // ( Issues exist with USGS duplicates that break unique constraints if those sites are included )
     $siteCodeContains = ['RB_', 'PR_', 'LR_'];
     // Revised to focus on suffix
     $siteCodeContains = ['_BA', '_AA'];
     // Only interested in Stream data
     $siteTypes = ['Stream'];
     // Only interested in common variables
     $variableLevels = ['Common'];
     // Only interested in RAW data
     // Can't rely on QC data
     $qualityControlLevelCodes = [0];
     // Get sites
     $siteKeys = ['network' => '', 'sitecode' => '', 'sitename' => '', 'latitude' => '', 'longitude' => ''];
     $sitesJSON = file_get_contents("http://data.iutahepscor.org/tsa/api/v1/sites/?limit=0");
     $sites = json_decode($sitesJSON);
     // Process sites into database
     foreach ($sites->objects as $site) {
         // Only add desiered site types
         if (in_array($site->sitetype, $siteTypes)) {
             // Only add desired sitecodes
             foreach ($siteCodeContains as $piece) {
                 if (strpos($site->sitecode, $piece) !== false) {
                     // Clean up array
                     $site = (array) $site;
                     $site = array_intersect_key($site, $siteKeys);
                     // Add
                     try {
                         Site::firstOrCreate((array) $site);
                         break;
                     } catch (Exception $e) {
                         // Didn't add to DB because of conflict, ignore...
                     }
                 }
             }
         }
     }
     // Get series
     $seriesKeys = ['sitecode' => '', 'variablecode' => '', 'getdataurl' => ''];
     $variableKeys = ['variablecode' => '', 'variablename' => '', 'variableunitsname' => '', 'variableunitsabbreviation' => ''];
     $seriesJSON = file_get_contents("http://data.iutahepscor.org/tsa/api/v1/dataseries/?limit=0");
     $series = json_decode($seriesJSON);
     // Process series into database
     foreach ($series->objects as $s) {
         // Only add series if site was added
         if (!Site::where(['sitecode' => $s->sitecode])->get()->isempty()) {
             // Only add desired variables
             if (in_array($s->variablelevel, $variableLevels) && in_array($s->qualitycontrollevelcode, $qualityControlLevelCodes)) {
                 // Strip down arrays for insert
                 $s = (array) $s;
                 $v = array_intersect_key($s, $variableKeys);
                 $s = array_intersect_key($s, $seriesKeys);
                 // Add Series
                 try {
                     Series::firstOrCreate($s);
                 } catch (Exception $e) {
                     // Series already exists
                 }
                 // Add Variable
                 try {
                     Variable::firstOrCreate($v);
                 } catch (Exception $e) {
                     // Variable already exists, this will catch a lot!
                 }
             }
         }
     }
     // Redirect to sites list
     return redirect()->action('DataController@sites');
 }
 private function save_nom($nom)
 {
     $variable = new Variable();
     $variable->updateOrCreate(['key' => 'ECOLE_NOM'], ['key' => 'ECOLE_NOM', 'value' => $nom]);
 }
 /**
  * Execute the command.
  *
  * @return void
  */
 public function handle()
 {
     //set_time_limit( 600 );
     //ini_set('memory_limit', '256M');
     //bump up limits
     set_time_limit(600);
     ini_set('memory_limit', '256M');
     return;
     //will we be checking entities
     $entityCheck = $this->validate_entities == 'on' ? false : true;
     //create new file
     $inputFileData = ['raw_data' => $this->data, 'fk_user_id' => $this->userId];
     $inputFile = InputFile::create($inputFileData);
     $inputFileDataId = $inputFile->id;
     $multivariantDataset = $this->multivariant_dataset;
     $variables = $this->variables;
     if (!empty($variables)) {
         $entityData = [];
         //creating new datasource, if there is some
         $sourceName = $this->source_name;
         if (!empty($sourceName)) {
             $datasourceData = ['name' => $this->source_name, 'link' => $this->source_link, 'description' => $this->source_description];
             $datasource = Datasource::create($datasourceData);
         } else {
             //fake datasoure
             $datasource = new \stdClass();
             $datasource->id = null;
         }
         //create new dataset or pick existing one
         $datasetName = $this->new_dataset_name;
         $datasetData = ['name' => $datasetName, 'fk_dst_cat_id' => $this->category_id, 'fk_dst_subcat_id' => $this->subcategory_id, 'description' => $this->new_dataset_description, 'fk_dsr_id' => $datasource->id];
         $dataset = Dataset::create($datasetData);
         $datasetId = $dataset->id;
         //process possible tags
         $tagsInput = $this->new_dataset_tags;
         if (!empty($tagsInput)) {
             $tagsArr = explode(',', $tagsInput);
             foreach ($tagsArr as $tag) {
                 $tag = DatasetTag::create(['name' => $tag]);
                 $tagId = $tag->id;
                 $datasetTagLink = LinkDatasetsTags::create(['fk_dst_id' => $datasetId, 'fk_dst_tags_id' => $tagId]);
             }
         }
         //store inserted variables, for case of rolling back
         $inserted_variables = array();
         foreach ($variables as $variableJsonString) {
             //convert back single out to actual single quote
             //$variableJsonString = str_replace( "'", "‘", $variableJsonString );
             //setting json_decode second param to false, to try to save memory
             $variableObj = json_decode($variableJsonString, false);
             $variableData = ['name' => $variableObj->name, 'fk_var_type_id' => $this->variable_type, 'fk_dst_id' => $datasetId, 'unit' => $variableObj->unit, 'description' => $variableObj->description, 'fk_dsr_id' => $datasource->id];
             //update of existing variable or new variable
             if (!isset($variableObj->id)) {
                 //new variable
                 $variable = Variable::create($variableData);
             } else {
                 //update variable
                 $variable = Variable::find($variableObj->id);
                 $variable->fill($variableData);
                 $variable->save();
             }
             $variableId = $variable->id;
             $inserted_variables[] = $variable;
             $variableValues = $variableObj->values;
             foreach ($variableValues as $countryValue) {
                 $entityData = ['name' => $countryValue->key, 'fk_ent_t_id' => 5, 'validated' => 0];
                 if ($entityCheck) {
                     //entity validation (only if not multivariant dataset)
                     //find corresponding iso code
                     $entityIsoName = EntityIsoName::match($entityData['name'])->first();
                     if (!$entityIsoName) {
                         //!haven't found corresponding country, throw an error!
                         //rollback everything first
                         foreach ($inserted_variables as $inserted_var) {
                             $inserted_var->data()->delete();
                             $inserted_var->delete();
                         }
                         //is new dataset
                         if ($this->new_dataset === '1') {
                             $dataset = Dataset::find($datasetId);
                             //delete itself
                             $dataset->delete();
                         }
                         \Log::error('Error non-existing entity in dataset.');
                         \Log::error($entityData['name']);
                         return redirect()->route('import')->with('message', 'Error non-existing entity in dataset.')->with('message-class', 'error');
                     }
                     //enter standardized info
                     $entityData['name'] = $entityIsoName->name;
                     $entityData['code'] = $entityIsoName->code;
                     $entityData['validated'] = 1;
                 }
                 //find try finding entity in db
                 if (isset($entityIsoName)) {
                     $entity = Entity::where('code', $entityIsoName->code)->first();
                 } else {
                     //not standardized data
                     $entity = Entity::where('code', $entityData['name'])->orWhere('name', $entityData['name'])->first();
                 }
                 if (!$entity) {
                     //entity haven't found in database, so insert it
                     $entity = Entity::create($entityData);
                 }
                 //check to override validation if stored in db not validated and now is validate
                 if ($entity->validated == 0 && $entityData['validated'] === 1) {
                     $entity->validated = 1;
                     $entity->save();
                 }
                 $entityId = $entity->id;
                 $countryValues = $countryValue->values;
                 //prepare vars for mass insert
                 $times = [];
                 $values = [];
                 //TODO - get latest time for base timeId
                 $lastTime = Time::orderBy('id', 'desc')->first();
                 $timeId = !empty($lastTime) ? $lastTime->id : 0;
                 foreach ($countryValues as $value) {
                     if ($this->hasValue($value->x) && $this->hasValue($value->y)) {
                         $timeId++;
                         //create time
                         $timeObj = $value->x;
                         $timeValue = ['startDate' => isset($timeObj->sd) ? $timeObj->sd : "", 'endDate' => isset($timeObj->ed) ? $timeObj->ed : "", 'date' => isset($timeObj->d) ? $timeObj->d : "", 'label' => isset($timeObj->l) ? $timeObj->l : ""];
                         //convert timedomain
                         $fk_ttype_id = 1;
                         if (!empty($timeObj->td)) {
                             $ttQuery = TimeType::query();
                             $fk_ttype_id = $ttQuery->whereRaw('LOWER(`name`) like ?', [$timeObj->td])->first()->id;
                         }
                         $timeValue['fk_ttype_id'] = $fk_ttype_id;
                         //using mass insert instead
                         //$time = Time::create( $timeValue );
                         //$timeId = $time->id;
                         $times[] = $timeValue;
                         //create value
                         $dataValueData = ['value' => $value->y, 'fk_time_id' => $timeId, 'fk_input_files_id' => $inputFileDataId, 'fk_var_id' => $variableId, 'fk_ent_id' => $entityId, 'fk_dsr_id' => $datasource->id];
                         //using mass insert instead
                         //$dataValue = DataValue::create( $dataValueData );
                         $values[] = $dataValueData;
                     }
                 }
                 //mass insertion
                 Time::insert($times);
                 DataValue::insert($values);
             }
         }
     }
 }
 public function variable(Request $request)
 {
     try {
         $variableObj = $request->all();
         $varId = $request->has('varId') ? $request->get('varId') : '';
         $varName = $request->has('name') ? $request->get('name') : '';
         $varType = $request->has('variableType') ? $request->get('variableType') : 1;
         $varUnit = $request->has('unit') ? $request->get('unit') : '';
         $varDescription = $request->has('description') ? $request->get('description') : '';
         $datasetId = $request->has('datasetId') ? $request->get('datasetId') : '';
         $datasourceId = $request->has('datasourceId') ? $request->get('datasourceId') : '';
         //$variableObj = json_decode( $variableJsonString, false );
         $variableData = ['name' => $varName, 'fk_var_type_id' => $varType, 'fk_dst_id' => $datasetId, 'unit' => $varUnit, 'description' => $varDescription, 'fk_dsr_id' => $datasourceId];
         //update of existing variable or new variable
         if (empty($varId)) {
             //new variable
             $variable = Variable::create($variableData);
         } else {
             //update variable
             $variable = Variable::find($varId);
             if (!empty($variable)) {
                 $variable->fill($variableData);
                 $variable->save();
             } else {
                 //not found existing variable
                 return ['success' => false];
             }
         }
         $variableId = $variable->id;
         return ['success' => true, 'data' => ['variableId' => $variableId]];
     } catch (Exception $e) {
         return ['success' => false];
     }
 }