public function act_dashboard()
 {
     global $global, $conf;
     $activeFormats = getActiveFormats();
     $entityFields = Browse::getAllEntityFields();
     $response = array();
     foreach ($activeFormats as $format => $formatTitle) {
         if ($conf['dashboard_format_counts_' . $format] != 'true') {
             continue;
         }
         $count_query = "SELECT COUNT(*) as count FROM {$format} ";
         try {
             $res_count = $global['db']->Execute($count_query);
             foreach ($res_count as $row) {
                 $response["counts"][$format] = array((int) $row["count"], $formatTitle);
             }
         } catch (Exception $e) {
         }
     }
     $timelineType = "day";
     if ($_REQUEST['timelinetype'] == "month") {
         $timelineType = "month";
     } elseif ($_REQUEST['timelinetype'] == "year") {
         $timelineType = "year";
     }
     $this->timelineType = $timelineType;
     if ($timelineType == "month") {
         $dateFormat = '%b %Y';
     } elseif ($timelineType == "year") {
         $dateFormat = '%Y';
     } else {
         $dateFormat = '%d %b %Y';
     }
     $datestart = "";
     $dateend = "";
     if (isset($_REQUEST['daterange'])) {
         $daterange = $_REQUEST['daterange'];
         $daterange = explode(",", $daterange);
         $datestart2 = trim($daterange[0]);
         $dateend2 = trim($daterange[1]);
         $date_format = 'Y-m-d';
         $timestart = strtotime($datestart2);
         $timeend = strtotime($dateend2);
         if ($timestart && $timeend) {
             $datestart = date($date_format, $timestart);
             $dateend = date($date_format, $timeend);
         }
     }
     if ($datestart && $dateend) {
         $this->daterange = $datestart . " , " . $dateend;
     } else {
         $this->daterange = "";
     }
     /*$sql = "SELECT  DATE_FORMAT(m.date_of_entry,'$dateFormat') as val , COUNT(e.event_record_number) AS count
               FROM  event e join management m on m.entity_id=e.event_record_number and m.entity_type='event' ";
       if ($datestart && $dateend) {
           $sql .= " where m.date_of_entry BETWEEN '$datestart' AND '$dateend' ";
       }
       $sql .= "GROUP BY val order by m.date_of_entry ";*/
     $dashboard_date_counts = array();
     if ($conf['dashboard_date_counts']) {
         $dashboard_date_counts = @json_decode($conf['dashboard_date_counts']);
         $dashboard_date_counts = (array) $dashboard_date_counts;
     }
     $response["timeline"] = array();
     foreach ($entityFields as $record) {
         $entity = $record['entity'];
         $field = $record['field_name'];
         $selVal = $entity . "|||" . $field;
         if (in_array($selVal, $dashboard_date_counts)) {
             $primary_key = get_primary_key($entity);
             if (in_array($field, array('date_received', 'date_of_entry', 'date_updated'))) {
                 $sql = "SELECT  DATE_FORMAT(m.{$field},'{$dateFormat}') as val , COUNT(e.{$primary_key}) AS count\n                      FROM  {$entity} e join management m on m.entity_id=e.{$primary_key} and m.entity_type='{$entity}' ";
                 if ($datestart && $dateend) {
                     $sql .= " where m.{$field} BETWEEN '{$datestart}' AND '{$dateend}' ";
                 }
                 $sql .= "GROUP BY val order by m.{$field} ";
             } else {
                 $sql = "SELECT  DATE_FORMAT(e.{$field} ,'{$dateFormat}') as val , COUNT(e.{$primary_key}) AS count\n                      FROM  {$entity} e  ";
                 if ($datestart && $dateend) {
                     $sql .= " where e.{$field}  BETWEEN '{$datestart}' AND '{$dateend}' ";
                 }
                 $sql .= "GROUP BY val order by e.{$field}  ";
             }
             $response["timeline"][$selVal]['entity'] = $entity;
             $response["timeline"][$selVal]['entity_label'] = $activeFormats[$entity];
             $response["timeline"][$selVal]['field_name'] = $field;
             $response["timeline"][$selVal]['field_label'] = $record['field_label'];
             try {
                 $res_count = $global['db']->Execute($sql);
                 foreach ($res_count as $row) {
                     $response["timeline"][$selVal]['data'][0] = array(ucfirst($timelineType), "Count");
                     if (!$row["val"] && !(int) $row["count"]) {
                         continue;
                     }
                     if (!$row["val"]) {
                         $row["val"] = "Undefined";
                     }
                     $response["timeline"][$selVal]['data'][] = array($row["val"], (int) $row["count"]);
                 }
             } catch (Exception $e) {
             }
         }
     }
     $barcharts = array();
     $dashboard_select_counts = array();
     if ($conf['dashboard_select_counts']) {
         $dashboard_select_counts = @json_decode($conf['dashboard_select_counts']);
         $dashboard_select_counts = (array) $dashboard_select_counts;
     }
     foreach ($entityFields as $record) {
         $entity = $record['entity'];
         $selVal = $entity . "|||" . $record['field_name'];
         if (in_array($selVal, $dashboard_select_counts)) {
             $barcharts[] = array("entity" => $entity, "field" => $record['field_name']);
         }
     }
     require_once APPROOT . 'mod/analysis/searchSql.php';
     $searchSql = new SearchResultGenerator();
     foreach ($barcharts as $key => $barchart) {
         $selEntity = $selEntityOriginal = $barchart["entity"];
         $field = $barchart["field"];
         $entityForm = $searchSql->getEntityArray($selEntityOriginal);
         if (!isset($entityForm[$field])) {
             continue;
         }
         $fieldArray = $entityForm[$field];
         $fieldType = $fieldArray["type"];
         $recField = get_primary_key($selEntityOriginal);
         $sqlArray['result'] = "select * from {$selEntityOriginal} ";
         $sqlchart = "";
         if ($fieldArray['map']['mlt']) {
             $mltTable = 'mlt_' . $searchSql->tableOfEntity($fieldArray['map']['entity']) . '_' . $fieldArray['map']['field'];
             $sqlchart = "SELECT IFNULL(l.msgstr , english) as val, COUNT(t.record_number) AS count\n                            FROM ({$sqlArray['result']}) d LEFT JOIN {$mltTable} t  on  t.record_number=d.{$recField} left join\n                            mt_vocab m on m.vocab_number=t.vocab_number\n                            LEFT JOIN mt_vocab_l10n l ON ( l.msgid = m.vocab_number AND l.locale = '{$conf['locale']}' )  GROUP BY t.vocab_number\n                            ";
         } elseif (is_management_field($fieldArray)) {
             $f = $fieldArray['map']['field'];
             $sqlchart = "SELECT IFNULL(l.msgstr , english) as val, COUNT(d.{$recField}) AS count\n                            FROM ({$sqlArray['result']}) d LEFT JOIN management t  on t.entity_id=d.{$recField} and t.entity_type='{$selEntity}' \n                            left join  mt_vocab m on m.vocab_number=t.{$fieldArray['map']['field']}\n                            LEFT JOIN mt_vocab_l10n l ON ( l.msgid = m.vocab_number AND l.locale = '{$conf['locale']}' )  GROUP BY {$f}\n                            ";
         } else {
             $f = $fieldArray['map']['field'];
             if ($fieldType == "mt_select" || $fieldType == "mt_tree") {
                 $sqlchart = "SELECT IFNULL(l.msgstr , english)  as val, COUNT({$recField}) AS count\n                            FROM ({$sqlArray['result']}) d left join  mt_vocab m on m.vocab_number=d.{$f}\n                            LEFT JOIN mt_vocab_l10n l ON ( l.msgid = m.vocab_number AND l.locale = '{$conf['locale']}' )  GROUP BY {$f}";
             } else {
                 $sqlchart = "SELECT d.{$f} as val, COUNT({$recField}) AS count\n                            FROM ({$sqlArray['result']}) d   GROUP BY {$f}";
             }
         }
         if ($sqlchart) {
             try {
                 $res = $global['db']->Execute($sqlchart);
                 $chart = array();
                 $chart["type"] = "barchart";
                 $chart["id"] = "barchart" . $key;
                 $chart["title"] = $fieldArray["label"];
                 $chart2 = $chart;
                 $total = 0;
                 foreach ($res as $val) {
                     $chart["data"][0][0] = $chart["title"];
                     $chart["data"][1][0] = "";
                     $vall = _t("Undefined");
                     if ($val[0]) {
                         if ($val[0] == "y") {
                             $vall = _t('YES');
                         } elseif ($val[0] == "n") {
                             $vall = _t('NO');
                         } else {
                             $vall = $val[0];
                         }
                     } elseif (!(int) $val[1]) {
                         continue;
                     }
                     $chart["data"][0][] = $vall;
                     $chart["data"][1][] = (int) $val[1];
                     $chart2["data"][0] = array($chart["title"], _t("COUNT"));
                     $chart2["data"][] = array($vall, (int) $val[1]);
                     $total += (int) $val[1];
                 }
                 $chart2["total"] = $total;
                 $response["barchart"][] = $chart2;
             } catch (Exception $e) {
                 $response->error = "error";
                 //$e->getMessage();
             }
         }
     }
     $entities = array_keys($activeFormats);
     foreach ($entities as $entity) {
         $recField = get_primary_key($entity);
         $count_query = "SELECT COUNT(m.entity_id) AS count\n                FROM  {$entity} e join management m on m.entity_id=e.{$recField} and m.entity_type='{$entity}'\n                    where m.date_of_entry BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE()\n                    GROUP BY m.entity_type  ";
         try {
             $res_count = $global['db']->Execute($count_query);
             foreach ($res_count as $row) {
                 $response["counts30"][$entity] = array((int) $row["count"], $activeFormats[$entity]);
             }
         } catch (Exception $e) {
         }
     }
     $sql = "SELECT al.username as val,COUNT(al.`action`) AS count\n                FROM  audit_log al where al.action='create'\n                    GROUP BY al.username order by `count` desc ";
     try {
         $res_count = $global['db']->Execute($sql);
         foreach ($res_count as $row) {
             $response["activeusers"][] = array($row["val"], (int) $row["count"]);
         }
     } catch (Exception $e) {
     }
     $sql = "SELECT al.username as val,COUNT(al.`action`) AS count\n                FROM  audit_log al where al.action='update'\n                    GROUP BY al.username order by `count` desc ";
     try {
         $res_count = $global['db']->Execute($sql);
         foreach ($res_count as $row) {
             $response["editusers"][] = array($row["val"], (int) $row["count"]);
         }
     } catch (Exception $e) {
     }
     $sql = "SELECT al.username as username,entity,record_number\n                FROM  audit_log al where al.action='delete'\n                order by `timestamp` desc limit 10  ";
     try {
         $res_count = $global['db']->Execute($sql);
         foreach ($res_count as $row) {
             $response["deleteusers"][] = array($row["entity"], $row["record_number"], $row["username"]);
         }
     } catch (Exception $e) {
     }
     // var_dump($response);exit;
     $this->response = $response;
 }
Example #2
0
 public function getFieldAlias($formField, $type = 'query', $entityType = null, $onlyAlias = false)
 {
     //$type can be 'query' or 'view'
     //if there are multiple instances of the same entity , each different entity should have different aliases.
     $entityField = null;
     // field name used for entity
     if ($this->isPersonExtention($entityType) == true) {
         $formField['map']['entity'] = $entityType;
     }
     $entityField = $formField['map']['entity'];
     if ($formField['map']['mlt']) {
         $fieldSqlArray = $this->mtJoin($formField, $type);
         $entityField = $fieldSqlArray['field'];
         $entityFieldAs = $fieldSqlArray['as'];
         if ($type == 'view' || $type == 'field') {
             $as = $entityFieldAs;
         }
         if ($onlyAlias == false) {
             return $entityField . $as;
         } else {
             //var_dump('onlyAlias' , $as );
             return $entityFieldAs;
         }
         //return $fieldName;
     }
     if (is_management_field($formField)) {
         //*** IMPLEMENT if the management field has not being joined, join it.
         $this->managementJoin($formField['map']['entity'], $formField['map']['field']);
         //if($type == 'view'){
         //	$as = ' AS ' . $formField['map']['entity'].'_'. $formField['map']['field'];
         //}
         //$formField['map']['entity'] = $formField['map']['entity'] . '_management' ;
         $entityField = $formField['map']['entity'] . '_management';
         //var_dump( $formField['map']['entity'].'_management'.'.'. $formField['map']['field'] . $as );
         //return $formField['map']['entity'].'_management'.'.'. $formField['map']['field'] . $as ;
     }
     if ($this->isPersonExtention($entityType) == true) {
         //var_dump('came to personExtension');
         $entityField = $this->setPersonSecondaryEntity($entityType);
         //var_dump('personAs' , $asReturn);
         //    		if($type == 'view' ){
         //    			$as = ' AS ' . $asReturn.'_'. $formField['map']['field'];
         //    		}
         //    		return $asReturn . '.' . $formField['map']['field'] . $as;
     }
     if ($formField['map']['entity'] == 'person' && $formField['map']['field'] == 'person_addresses') {
         //$sqlArray['select'][] = 'address.*';
         //$sqlArray['join'][] = array('table'=>'address' , 'jointype'=>'LEFT' , 'field1'=>'person_record_number', 'field2' =>'person'  , 'as'=>null );
         return null;
     }
     if ($this->tableOfEntity($formField['map']['entity']) == 'person' && $this->tableOfEntity($formField['map']['field']) == 'addresses') {
     }
     if ($formField['type'] == 'document') {
         return null;
     }
     if ($formField['type'] == 'upload') {
         return null;
     }
     if ($type == 'view') {
         $as = ' AS ' . $formField['map']['entity'] . '_' . $formField['map']['field'];
     } else {
         if ($type == 'field') {
             // called only when the field is a mt_tree.
             $as = ' AS ' . $formField['map']['entity'] . '_' . $formField['map']['field'];
         }
     }
     if ($onlyAlias == false && !is_null($entityField)) {
         return $entityField . '.' . $formField['map']['field'] . $as;
     } else {
         //var_dump('onlyAlias' , $type , $as );
         return $as;
     }
 }
 public function act_facetsearchresults()
 {
     global $global, $conf;
     $searchparams = $_GET['searchparams'];
     $searchparams = json_decode($searchparams);
     $resp = array();
     if ($searchparams) {
         $domaindata = $this->getEntityFields();
         $query = new stdClass();
         $ents = array();
         $additionalFields = array();
         if (count((array) $searchparams->selected_terms)) {
             $fieldCounts = array();
             foreach ($searchparams->selected_terms as $entity => $fields) {
                 foreach ($fields as $field => $terms) {
                     if (!$terms) {
                         continue;
                     }
                     $ents[] = $entity;
                     if ($domaindata->{$entity}->ac_type) {
                         $selEntity2 = $domaindata->{$entity}->ac_type;
                     } else {
                         $selEntity2 = $entity;
                     }
                     $condition = new stdClass();
                     $condition->entity = $entity;
                     $condition->field = $field;
                     $condition->operator = "in";
                     $condition->value = implode(",", $terms);
                     $condition->link = "and";
                     if ($domaindata->{$selEntity2}->fields->{$field}->field_type == "mt_tree") {
                         $condition->operator = "subin";
                     } else {
                         $condition->operator = "in";
                     }
                     $query->conditions[] = $condition;
                 }
             }
         }
         $selEntity = $selEntityOriginal = $searchparams->entities[0];
         //var_dump($selEntity);exit;
         if ($domaindata->{$selEntity}->ac_type) {
             $selEntity = $domaindata->{$selEntity}->ac_type;
         }
         $selectFields = array();
         foreach ($query->conditions as $cond) {
             $sel = new stdClass();
             $sel->entity = $cond->entity;
             $sel->field = $cond->field;
             $selectFields[] = $sel;
         }
         if ($searchparams->facets) {
             foreach ($searchparams->facets as $facet) {
                 $sel = new stdClass();
                 $sel->entity = $facet->entity;
                 $sel->field = $facet->field;
                 $selectFields[] = $sel;
             }
         }
         foreach ($domaindata->{$selEntity}->fields as $field) {
             if ($field->select == "y") {
                 $sel = new stdClass();
                 $sel->entity = $selEntityOriginal;
                 $sel->field = $field->value;
                 $selectFields[] = $sel;
             }
         }
         $selectFields = array_unique($selectFields, SORT_REGULAR);
         foreach ($selectFields as $sfield) {
             if (!in_array($sfield->entity, $ents)) {
                 $ents[] = $sfield->entity;
                 $condition = new stdClass();
                 $entt = $sfield->entity;
                 $selEntt = $entt;
                 if ($domaindata->{$entt}->ac_type) {
                     $selEntt = $domaindata->{$entt}->ac_type;
                 }
                 $fields = (array) $domaindata->{$selEntt};
                 $f = (array) $domaindata->{$selEntt}->fields;
                 $pkey = get_primary_key($selEntt);
                 if ($f[$pkey]) {
                     $f = $f[$pkey];
                 } else {
                     $f = array_shift($f);
                 }
                 $condition->entity = $entt;
                 $condition->field = $f->value;
                 $condition->operator = "contains";
                 $condition->value = "";
                 $query->conditions[] = $condition;
             }
         }
         foreach ($ents as $ent) {
             $recField = get_primary_key($ent);
             $sel = new stdClass();
             $sel->entity = $ent;
             $sel->field = $recField;
             if (!in_array($sel, $selectFields)) {
                 $selectFields[] = $sel;
                 $additionalFields[$sel->entity][] = $recField;
             }
         }
         $selectFields = array_unique($selectFields, SORT_REGULAR);
         $query->select = $selectFields;
         function entitySort($a, $b)
         {
             $enord = array('event', 'act', 'intervention', 'arrest', 'torture', 'killing', 'destruction', 'victim', 'involvement', 'perpetrator', 'information', 'source', 'chain_of_events', 'intervening_party', 'address', 'biographic_details', 'supporting_docs_meta');
             $aorder = array_search($a->entity, $enord);
             $border = array_search($b->entity, $enord);
             return $border - $aorder;
         }
         usort($query->select, "entitySort");
         usort($query->conditions, "entitySort");
         $from = (int) $searchparams->paging->from;
         $size = (int) $searchparams->paging->size;
         if ($from < 0) {
             $from = 0;
         }
         if ($size < 1) {
             $size = 20;
         }
         $records = array();
         include_once 'searchSql.php';
         $start = $from;
         $limit = $size;
         $sidx = $_GET['sidx'];
         if (!$sidx) {
             $sidx = 1;
         }
         $sord = $_GET['sord'];
         $fields_array = array();
         $entities = analysis_get_search_entities();
         $fieldTitles = array();
         //if the query is a search put select fields to the array
         foreach ($query->select as $field) {
             if (in_array($field->field, $additionalFields[$field->entity])) {
                 continue;
             }
             $entity = isset($entities[$field->entity]['ac_type']) ? $entities[$field->entity]['ac_type'] : $field->entity;
             $mt = is_mt_field($entity, $field->field);
             array_push($fields_array, array('name' => $field->entity . '_' . $field->field, 'mt' => $mt));
             $fieldname = $field->field;
             if (isset($domaindata->{$entity}->fields->{$fieldname}->label)) {
                 $fieldTitles[] = $domaindata->{$entity}->fields->{$fieldname}->label;
             } else {
                 $fieldTitles[] = $field->field;
             }
         }
         $records[0] = $fieldTitles;
         $searchSql = new SearchResultGenerator();
         $sqlArray = $searchSql->sqlForJsonQuery(json_encode($query));
         $count_query = "SELECT COUNT(*) FROM ({$sqlArray['result']}) as results";
         try {
             $res_count = $global['db']->Execute($count_query);
         } catch (Exception $e) {
             $response->error = "error";
             //$e->getMessage();
             $res_count = null;
         }
         if ($res_count != null) {
             while (!$res_count->EOF) {
                 $count = $res_count->fields[0];
                 $res_count->MoveNext();
             }
         }
         $sql = $sqlArray['result'];
         if ($limit != -1) {
             $sql .= " LIMIT {$start} , {$limit}";
         }
         try {
             $res = $global['db']->Execute($sql);
         } catch (Exception $e) {
             $response->error = "error";
             //$e->getMessage();
         }
         $resp = array("response" => array("start" => $from, "found" => $count));
         $number_of_fields = count($fields_array);
         foreach ($res as $key => $val) {
             //$response->aaData[$i]['id'] = $val[$fields_array[0]];
             $array_values = array();
             for ($count = 0; $number_of_fields > $count; $count++) {
                 $field_name = $fields_array[$count]['name'];
                 $record_number_field = substr($field_name, strlen($field_name) - 13);
                 $confidentiality_field = substr($field_name, strlen($field_name) - 15);
                 $deceased_field = substr($field_name, strlen($field_name) - 8);
                 $doc_field = substr($field_name, strlen($field_name) - 6);
                 if ($confidentiality_field == 'confidentiality') {
                     if ($val[$field_name] == 'y') {
                         $val[$field_name] = _t('YES');
                     } elseif ($val[$field_name] == 'n') {
                         $val[$field_name] = _t('NO');
                     }
                 }
                 if ($deceased_field == 'deceased') {
                     if ($val[$field_name] == 'y') {
                         $val[$field_name] = _t('YES');
                     } else {
                         $val[$field_name] = _t('NO');
                     }
                 }
                 $string = null;
                 if ($fields_array[$count]['mt']) {
                     $list = explode(',', $val[$field_name]);
                     //var_dump($val);exit;
                     foreach ($list as $term) {
                         $string = $string . ", " . get_mt_term(trim($term));
                     }
                     $array_values[$field_name] = ltrim($string, ',');
                 } else {
                     if ($record_number_field == 'record_number' || $doc_field == 'doc_id') {
                         if (preg_match('/event/', $field_name)) {
                             $link_entity = 'event';
                         } else {
                             if (preg_match('/act/', $field_name)) {
                                 $link_entity = 'act';
                             } else {
                                 if (preg_match('/source/', $field_name)) {
                                     $link_entity = 'source';
                                 } else {
                                     if (preg_match('/perpetrator/', $field_name)) {
                                         $link_entity = 'perpetrator';
                                     } else {
                                         if (preg_match('/victim/', $field_name)) {
                                             $link_entity = 'victim';
                                         } else {
                                             if (preg_match('/involvement/', $field_name)) {
                                                 $link_entity = 'involvement';
                                             } else {
                                                 if (preg_match('/information/', $field_name)) {
                                                     $link_entity = 'information';
                                                 } else {
                                                     if (preg_match('/intervention/', $field_name)) {
                                                         $link_entity = 'intervention';
                                                     } else {
                                                         if (preg_match('/intervening_party/', $field_name)) {
                                                             $link_entity = 'intervening_party';
                                                         } else {
                                                             if (preg_match('/person/', $field_name)) {
                                                                 $link_entity = 'person';
                                                             } else {
                                                                 if (preg_match('/biographic_details/', $field_name)) {
                                                                     $link_entity = 'biographic_details';
                                                                 } else {
                                                                     if (preg_match('/supporting_docs_meta/', $field_name)) {
                                                                         $link_entity = 'supporting_docs_meta';
                                                                     } else {
                                                                         if (preg_match('/address/', $field_name)) {
                                                                             $link_entity = 'address';
                                                                         }
                                                                     }
                                                                 }
                                                             }
                                                         }
                                                     }
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                         if ($link_entity != 'address') {
                             $url = get_record_url($val[$field_name], $link_entity);
                             $array_values[$field_name] = "<a href='{$url}' target='_blank'>" . $val[$field_name] . "</a>";
                         } else {
                             if ($val[$field_name]) {
                                 $array_values[$field_name] = $val[$field_name];
                             } else {
                                 $array_values[$field_name] = "";
                             }
                         }
                     } else {
                         if ($val[$field_name]) {
                             $array_values[$field_name] = $val[$field_name];
                         } else {
                             $array_values[$field_name] = "";
                         }
                     }
                 }
             }
             $records[] = $array_values;
             $i++;
         }
         $resp["response"]["records"] = $records;
         $recField = get_primary_key($selEntity);
         // . "_record_number";
         $charts = array();
         $conditions = array();
         if (count((array) $query->conditions)) {
             foreach ($query->conditions as $condition) {
                 $condition2 = $condition;
                 $conditions[$condition->entity][$condition->field][] = $condition2;
             }
         }
         //var_dump($conditions, $sqlArray['result']);
         if ($searchparams->facets) {
             foreach ($searchparams->facets as $facet) {
                 $entity = $facet->entity;
                 $field = $facet->field;
                 if ($domaindata->{$entity}->ac_type) {
                     $en = $domaindata->{$entity}->ac_type;
                     $fields = $domaindata->{$en}->fields;
                 } else {
                     $fields = $domaindata->{$entity}->fields;
                 }
                 $fieldType = $fields->{$field}->field_type;
                 $listCode = $fields->{$field}->list_code;
                 //charts
                 $entityForm = $searchSql->getEntityArray($entity);
                 $fieldArray = $entityForm[$field];
                 $recField = get_primary_key($selEntityOriginal);
                 $selEntt = $entity;
                 if ($domaindata->{$selEntt}->ac_type) {
                     $selEntt = $domaindata->{$selEntt}->ac_type;
                 }
                 $recFieldEnt = get_primary_key($searchSql->tableOfEntity($fieldArray['map']['entity']));
                 if ($fieldArray['map']['mlt'] && $fieldArray['type'] != "user_select") {
                     $mltTable = 'mlt_' . $searchSql->tableOfEntity($fieldArray['map']['entity']) . '_' . $fieldArray['map']['field'];
                     $sqlchart = "SELECT IFNULL(l.msgstr , english) as val, COUNT(t.record_number) AS count,m.vocab_number as vocab_number\n                            FROM ({$sqlArray['result']}) d LEFT JOIN {$mltTable} t  on  t.record_number=d.{$entity}_{$recFieldEnt} left join\n                            mt_vocab m on m.vocab_number=t.vocab_number\n                            LEFT JOIN mt_vocab_l10n l ON ( l.msgid = m.vocab_number AND l.locale = '{$conf['locale']}' )  GROUP BY t.vocab_number\n                            ";
                 } elseif (is_management_field($fieldArray)) {
                     $f = $entity . "_" . $fieldArray['map']['field'];
                     $sqlchart = "SELECT IFNULL(l.msgstr , english) as val, COUNT(d.{$selEntityOriginal}_{$recField}) AS count,m.vocab_number as vocab_number\n                            FROM ({$sqlArray['result']}) d LEFT JOIN management t  on t.entity_id=d.{$entity}_{$recFieldEnt} and t.entity_type='{$entity}'\n                            left join  mt_vocab m on m.vocab_number=t.{$fieldArray['map']['field']}\n                            LEFT JOIN mt_vocab_l10n l ON ( l.msgid = m.vocab_number AND l.locale = '{$conf['locale']}' )  GROUP BY {$f}\n                            ";
                 } else {
                     $f = $entity . "_" . $fieldArray['map']['field'];
                     if ($fieldType == "mt_select" || $fieldType == "mt_tree") {
                         $sqlchart = "SELECT IFNULL(l.msgstr , english)  as val, COUNT({$selEntityOriginal}_{$recField}) AS count,m.vocab_number as vocab_number\n                            FROM ({$sqlArray['result']}) d left join  mt_vocab m on m.vocab_number=d.{$f}\n                            LEFT JOIN mt_vocab_l10n l ON ( l.msgid = m.vocab_number AND l.locale = '{$conf['locale']}' )  GROUP BY {$f}";
                     } else {
                         $sqlchart = "SELECT d.{$f} as val, COUNT({$selEntityOriginal}_{$recField}) AS count,d.{$f} as vocab_number\n                            FROM ({$sqlArray['result']}) d   GROUP BY {$f}";
                     }
                 }
                 $facetcounts = array();
                 if ($sqlchart) {
                     try {
                         $res = $global['db']->Execute($sqlchart);
                         $chart = array();
                         $chart["type"] = "editchart";
                         $chart["editcharttype"] = "BarChart";
                         $chart["title"] = $fieldArray["label"];
                         $chart2 = $chart;
                         $chart2["editcharttype"] = "PieChart";
                         foreach ($res as $val) {
                             $vall = _t("Undefined");
                             if ($val[0]) {
                                 if ($val[0] == "y") {
                                     $vall = _t('YES');
                                 } elseif ($val[0] == "n") {
                                     $vall = _t('NO');
                                 } else {
                                     $vall = $val[0];
                                 }
                             } elseif (!(int) $val[1]) {
                                 continue;
                             }
                             $chart["data"][0][0] = $chart["title"];
                             $chart["data"][1][0] = "";
                             $chart["data"][0][] = $vall;
                             $chart["data"][1][] = (int) $val[1];
                             $chart2["data"][0] = array($chart["title"], _t("COUNT"));
                             $chart2["data"][] = array($vall, (int) $val[1]);
                             $facetcounts[$val[2]] = (int) $val[1];
                         }
                         //$resp["charts"][] = array($chart, $chart2);
                         $resp["charts"][] = array($chart);
                         $resp["charts"][] = array($chart2);
                     } catch (Exception $e) {
                         $response->error = "error";
                         //$e->getMessage();
                     }
                 }
                 $terms = array();
                 switch ($fieldType) {
                     case 'radio':
                         $label = _t('YES');
                         if (isset($facetcounts["y"])) {
                             $label .= " (" . $facetcounts["y"] . ")";
                         }
                         $resp["facets"][$field]["terms"][] = array('term' => 'y', 'label' => $label);
                         $label = _t('NO');
                         if (isset($facetcounts["n"])) {
                             $label .= " (" . $facetcounts["n"] . ")";
                         }
                         $resp["facets"][$field]["terms"][] = array('term' => 'n', 'label' => $label);
                         $resp["facets"][$field]["entity"] = $entity;
                         break;
                     case 'mt_select':
                         $data_array = MtFieldWrapper::getMTList($listCode);
                         $size = count($data_array);
                         $options[''] = ' ';
                         for ($i = 0; $i < $size; $i++) {
                             $label = $data_array[$i]['label'];
                             if (isset($facetcounts[$data_array[$i]['vocab_number']])) {
                                 $label .= " (" . $facetcounts[$data_array[$i]['vocab_number']] . ")";
                             }
                             $terms[] = array('term' => $data_array[$i]['vocab_number'], 'label' => $label);
                         }
                         $resp["facets"][$field] = array("terms" => $terms, "entity" => $entity);
                         break;
                     case 'mt_tree':
                         $data_array = MtFieldWrapper::getMTList($listCode);
                         $count = count($data_array);
                         for ($i = 0; $i < $count;) {
                             $element1 = $data_array[$i];
                             $label = $element1['label'];
                             if (isset($facetcounts[$element1['vocab_number']])) {
                                 $label .= " (" . $facetcounts[$element1['vocab_number']] . ")";
                             }
                             $terms[] = array('term' => $element1['vocab_number'], 'label' => $label, 'level' => (int) $element1["term_level"]);
                             $i++;
                         }
                         $resp["facets"][$field] = array("terms" => $terms, "field_type" => "mt_tree", "entity" => $entity);
                         break;
                 }
             }
         }
         $locationFields = Browse::getEntityLocationFields($selEntity);
         $field_names = array();
         $fieldsArray = array();
         $markers = array();
         if ($locationFields) {
             $selectFields = array();
             $sel = new stdClass();
             $sel->entity = $selEntityOriginal;
             $sel->field = get_primary_key($selEntity);
             // . "_record_number";
             $selectFields[] = $sel;
             foreach ($locationFields as $locationField) {
                 $field_names[] = $locationField["field_name"];
                 /* $fieldsArray[] = $locationField["field_name"] . "_latitude";
                    $fieldsArray[] = $locationField["field_name"] . "_longitude"; */
                 $sel = new stdClass();
                 $sel->entity = $selEntityOriginal;
                 $sel->field = $locationField["field_name"] . "_latitude";
                 $selectFields[] = $sel;
                 $sel = new stdClass();
                 $sel->entity = $selEntityOriginal;
                 $sel->field = $locationField["field_name"] . "_longitude";
                 $selectFields[] = $sel;
             }
             $query->select = $selectFields;
             $searchSql = new SearchResultGenerator();
             $sqlArray = $searchSql->sqlForJsonQuery(json_encode($query));
             $sql = $sqlArray['result'];
             if ($limit != -1) {
                 // $sql .= " LIMIT $start , $limit";
             }
             //$sql = "select " . $selEntity . "_record_number," . implode(",", $fieldsArray) . " from " . $selEntity;
             try {
                 $res = $global['db']->GetAll($sql);
             } catch (Exception $e) {
                 $response->error = "error";
                 //$e->getMessage();
             }
             foreach ($res as $val) {
                 $url = get_record_url($val[0], $selEntity);
                 $i = 1;
                 foreach ($field_names as $field_name) {
                     if ($val[$i] && $val[$i + 1]) {
                         $markers[] = array("latitude" => $val[$i], "longitude" => $val[$i + 1], "title" => $val[0], "content" => "<a href='" . $url . "' target='_blank'>" . $val[0] . "</a>");
                     }
                     $i = $i + 2;
                 }
             }
         }
         $resp["markers"] = $markers;
     }
     echo json_encode($resp);
     exit;
 }