Exemple #1
0
 public static function writeObjectParts($obj)
 {
     ////var_dump("writing obj: " . $obj["varname"]);
     ////var_dump($obj);
     $adjObj = array();
     foreach ($obj as $key => $value) {
         $strkey = strval($key);
         if (substr($strkey, 0, 1) == "/") {
             $strkey = substr($strkey, 1);
         }
         $adjObj[$strkey] = $value;
     }
     $obj = $adjObj;
     foreach ($obj as $key => $value) {
         $strkey = strval($key);
         if ($value == null) {
             ////var_dump("reading null: " . $obj["varname"] . "." . $strkey);
             $value = PiPress::getVar($obj["varname"] . "." . $strkey);
         }
         if (is_string($value) && is_json($value)) {
             ////var_dump("json string");
             $value = json_decode($value, true);
         }
         ////var_dump("dump1: ");
         ////var_dump($value);
         if (is_array($value)) {
             $value["varname"] = $obj["varname"] . "." . $strkey;
             //var_dump($value["varname"]);
             PiPress::writeObjectParts($value);
             $obj[$key] = null;
         }
     }
     //PiPress::createDocumentation($obj);
     file_put_contents("./" . $obj["varname"] . ".json", json_encode($obj));
 }
Exemple #2
0
 function __construct()
 {
     parent::__construct();
     if ($this->config->item('use_db_config')) {
         // Get CI instance so we can set a global var.
         $CI =& get_instance();
         // First check memcache, if found use dbconfig from memcache
         if ($cached = $this->memcache->get('dbconfig')) {
             // Override data origin.
             $cached->_data_origin = 'memcached';
             $CI->dbconfig = $cached;
             return true;
         }
         // Get config from db
         $result = $this->db->select('key, value')->get('config')->result();
         // Create new array and set data origin
         $dbconf = array('_data_origin' => 'database');
         // Loop through db-result.
         foreach ($result as $conf) {
             $dbconf[addslashes($conf->key)] = is_json($conf->value) ? json_decode($conf->value) : $conf->value;
         }
         // Cache in memcache forever
         $this->memcache->set('dbconfig', (object) $dbconf, 0);
     } else {
         // Default to an empty array
         $dbconf = array();
     }
     // Set dbconfig from database result.
     $CI->dbconfig = (object) $dbconf;
 }
Exemple #3
0
 /**
  * Menu json to array.
  *
  * @param $content
  * @return mixed
  */
 public function getContentAttribute($content)
 {
     if (is_json($content)) {
         return json_decode($content);
     }
     return $content;
 }
Exemple #4
0
function Curl($url, $method = 'GET', $postData = array())
{
    $data = '';
    if (!empty($url)) {
        try {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            if (is_json($postData)) {
                curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
            }
            if (strtoupper($method) == 'POST') {
                $curlPost = is_array($postData) ? http_build_query($postData) : $postData;
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
            }
            $data = curl_exec($ch);
            curl_close($ch);
        } catch (Exception $e) {
            $data = null;
        }
    }
    return $data;
}
 public static function valueFromUrl($_url)
 {
     $request_http = new com_http($_url);
     $dataUrl = $request_http->exec();
     if (!is_json($dataUrl)) {
         return;
     }
     return json_decode($dataUrl, true);
 }
Exemple #6
0
 function categorization($id = null)
 {
     header('Content-Type: application/json');
     $cat = $this->categorization_model->get_categorization($id);
     $cat_settings = array_get_value((array) $cat, 'cat_settings');
     $cat_settings = unserialize($cat_settings);
     $cat_settings = $cat_settings && is_json($cat_settings) ? $cat_settings : json_encode(array('url' => base_url('data/category-builder-template.js')), JSON_UNESCAPED_SLASHES);
     echo $cat_settings;
 }
Exemple #7
0
 /**
  * Decode a request result.
  *
  * @param $body
  * @return mixed
  */
 private function decode($body)
 {
     if (is_json($body)) {
         return json_decode($body, true);
     }
     if (is_xml($body)) {
         return xml_to_json($body);
     }
     return $body;
 }
Exemple #8
0
 public function doImport()
 {
     $jsonData = file_get_contents($this->importFile);
     if (is_json($jsonData) === false) {
         throw new Exception('El fichero de importación no parece que este en formato json');
     }
     $arrayData = Zend_Json::decode($jsonData, Zend_Json::TYPE_ARRAY);
     foreach ($arrayData as $roleData) {
         $this->createRole($roleData);
     }
 }
Exemple #9
0
 public function parse()
 {
     $data = $this->data;
     if (is_array($data)) {
         return $this->arrayParser($data);
     }
     if (is_json($data)) {
         return $this->jsonParser($data);
     }
     return $this->arrayParser($data);
 }
Exemple #10
0
 public function doImport()
 {
     $jsonData = file_get_contents($this->importFile);
     if (is_json($jsonData) === false) {
         throw new Exception('El fichero de importación no parece que este en formato json');
     }
     $dataArray = Zend_Json::decode($jsonData, Zend_Json::TYPE_ARRAY);
     foreach ($dataArray as $data) {
         $this->createObject($data);
     }
     $this->reassignReferences();
 }
Exemple #11
0
function get_api_data($url, $param = array())
{
    $url = API_URL . $url;
    $sign = encrypt($param);
    $param['sign'] = $sign;
    $api_str = send_request($url, $param);
    if (is_json($api_str)) {
        return json_decode($api_str, TRUE);
    } else {
        return return_format(array($api_str), "json_str 解析错误,这是api内部报错!请联系1162097842@qq.com", API_NORMAL_ERR);
    }
}
 private function sendData($param)
 {
     $url = C('WEB_URL');
     $checkCode = C('CHECK_CODE');
     $param = json_encode($param);
     $post = array('param' => $param, 'sign' => md5($param . $checkCode));
     $data = url_data($url, $post);
     if (is_json($data)) {
         $data = json_decode($data, true);
     }
     return $data;
 }
Exemple #13
0
 public function testIsJson()
 {
     $this->assertEquals(is_json('[]'), true);
     $this->assertEquals(is_json('[1]'), true);
     $this->assertEquals(is_json('[1.23]'), true);
     $this->assertEquals(is_json('["a"]'), true);
     $this->assertEquals(is_json('["a",1]'), true);
     $this->assertEquals(is_json('[1,"a",["b"]]'), true);
     $this->assertEquals(is_json('x'), false);
     $this->assertEquals(is_json('['), false);
     $this->assertEquals(is_json('[]]'), false);
     $this->assertEquals(is_json('[[]'), false);
     $this->assertEquals(is_json('["a"'), false);
 }
Exemple #14
0
 public function debug($method = 'config')
 {
     if (method_exists(__CLASS__, $method)) {
         $result = self::$method(Input::all());
         if (is_array($result)) {
             Helper::ta($result);
         } elseif (is_json($result)) {
             Helper::ta(json_decode($result, TRUE));
         } elseif (is_string($result)) {
             echo $result;
         }
     } else {
         echo 'Error...';
     }
 }
 public function requestKeyValue($url, $method = 'GET', $fields = [])
 {
     try {
         $response = $this->request($url, $method, $fields);
     } catch (Exception $e) {
         throw $e;
     }
     // Extract body from response.
     $body = $response->getBody();
     // Handle expected json.
     $data = [];
     if (is_json($body, $data)) {
         return $data;
     }
     // Parse body as keyvalue.
     return keyvalue_to_array($body);
 }
 public function getVerifyToken($id)
 {
     global $table_prefix;
     $id = intval($id);
     if (!$this->isExistID($id)) {
         return FALSE;
     }
     try {
         $sth = $this->dbh->prepare("SELECT * FROM {$table_prefix}users_temp WHERE `id` = :id ");
         $sth->bindParam(':id', $id);
         $sth->execute();
         $result = $sth->fetch(PDO::FETCH_ASSOC);
         $verify_token = $result['verify_token'];
         if (is_json($verify_token)) {
             $verify_token = json_decode($verify_token, true);
         } else {
             $verify_token = array("", "");
         }
         return $verify_token;
     } catch (PDOExecption $e) {
         echo "<br>Error: " . $e->getMessage();
     }
 }
 public function loadCmdFromConf($_update = false)
 {
     if (!is_file(dirname(__FILE__) . '/../config/devices/' . $this->getConfFilePath())) {
         return;
     }
     $content = file_get_contents(dirname(__FILE__) . '/../config/devices/' . $this->getConfFilePath());
     if (!is_json($content)) {
         return;
     }
     $device = json_decode($content, true);
     if (!is_array($device) || !isset($device['commands'])) {
         return true;
     }
     $cmd_order = 0;
     $link_cmds = array();
     if (isset($device['name']) && !$_update) {
         $this->setName('[' . $this->getLogicalId() . ']' . $device['name']);
     }
     if (isset($device['configuration'])) {
         foreach ($device['configuration'] as $key => $value) {
             try {
                 $this->setConfiguration($key, $value);
             } catch (Exception $e) {
             }
         }
     }
     nodejs::pushUpdate('jeedom::alert', array('level' => 'warning', 'message' => __('Création des commandes à partir d\'une configuration', __FILE__)));
     $commands = $device['commands'];
     foreach ($commands as &$command) {
         if (!isset($command['configuration']['instanceId'])) {
             $command['configuration']['instanceId'] = 0;
         }
         if (!isset($command['configuration']['class'])) {
             $command['configuration']['class'] = '';
         }
         try {
             $cmd = new openzwaveCmd();
             $cmd->setOrder($cmd_order);
             $cmd->setEqLogic_id($this->getId());
             utils::a2o($cmd, $command);
             if (isset($command['value'])) {
                 $cmd->setValue(null);
             }
             $cmd->save();
             if (isset($command['value'])) {
                 $link_cmds[$cmd->getId()] = $command['value'];
             }
             $cmd_order++;
         } catch (Exception $exc) {
         }
     }
     if (count($link_cmds) > 0) {
         foreach ($this->getCmd() as $eqLogic_cmd) {
             foreach ($link_cmds as $cmd_id => $link_cmd) {
                 if ($link_cmd == $eqLogic_cmd->getName()) {
                     $cmd = cmd::byId($cmd_id);
                     if (is_object($cmd)) {
                         $cmd->setValue($eqLogic_cmd->getId());
                         $cmd->save();
                     }
                 }
             }
         }
     }
     $this->save();
     nodejs::pushUpdate('jeedom::alert', array('level' => 'warning', 'message' => ''));
 }
    echo "    <select class='formfld' name='default_setting_value'>\n";
    echo "    \t<option value='true' " . ($default_setting_value == "true" ? "selected='selected'" : null) . ">" . $text['label-true'] . "</option>\n";
    echo "    \t<option value='false' " . ($default_setting_value == "false" ? "selected='selected'" : null) . ">" . $text['label-false'] . "</option>\n";
    echo "    </select>\n";
} elseif ($category == "voicemail" && $subcategory == "voicemail_file" && $name == "text") {
    echo "    <select class='formfld' name='default_setting_value'>\n";
    echo "    \t<option value='listen' " . ($default_setting_value == "listen" ? "selected='selected'" : null) . ">" . $text['option-voicemail_file_listen'] . "</option>\n";
    echo "    \t<option value='link' " . ($default_setting_value == "link" ? "selected='selected'" : null) . ">" . $text['option-voicemail_file_link'] . "</option>\n";
    echo "    \t<option value='attach' " . ($default_setting_value == "attach" ? "selected='selected'" : null) . ">" . $text['option-voicemail_file_attach'] . "</option>\n";
    echo "    </select>\n";
} elseif ($category == "voicemail" && $subcategory == "keep_local" && $name == "boolean") {
    echo "\t<select class='formfld' name='default_setting_value'>\n";
    echo "    \t<option value='true' " . ($default_setting_value == "true" ? "selected='selected'" : null) . ">" . $text['label-true'] . "</option>\n";
    echo "    \t<option value='false' " . ($default_setting_value == "false" ? "selected='selected'" : null) . ">" . $text['label-false'] . "</option>\n";
    echo "\t</select>\n";
} elseif (is_json($default_setting_value)) {
    echo "\t<textarea class='formfld' style='width: 100%; height: 80px; font-family: courier; white-space: nowrap; overflow: auto;' name='default_setting_value' wrap='off'>" . $default_setting_value . "</textarea>\n";
} else {
    echo "\t<input class='formfld' type='text' name='default_setting_value' value=\"" . htmlspecialchars($default_setting_value) . "\">\n";
}
echo "<br />\n";
echo $text['description-value'] . "\n";
echo "</td>\n";
echo "</tr>\n";
if ($name == "array" || $name == '') {
    echo "<tr>\n";
    echo "<td class='vncellreq' valign='top' align='left' nowrap='nowrap' width='30%'>\n";
    echo "    " . $text['label-order'] . "\n";
    echo "</td>\n";
    echo "<td class='vtable' align='left'>\n";
    echo "\t<select name='default_setting_order' class='formfld'>\n";
Exemple #19
0
     }
     ajax::success($return);
 }
 if (init('action') == 'autoCompleteGroup') {
     if (!isConnect('admin')) {
         throw new Exception(__('401 - Accès non autorisé', __FILE__));
     }
     $return = array();
     foreach (scenario::listGroup(init('term')) as $group) {
         $return[] = $group['group'];
     }
     ajax::success($return);
 }
 if (init('action') == 'toHtml') {
     if (init('id') == 'all' || is_json(init('id'))) {
         if (is_json(init('id'))) {
             $scenario_ajax = json_decode(init('id'), true);
             $scenarios = array();
             foreach ($scenario_ajax as $id) {
                 $scenarios[] = scenario::byId($id);
             }
         } else {
             $scenarios = scenario::all();
         }
         $return = array();
         foreach ($scenarios as $scenario) {
             if ($scenario->getIsVisible() == 1) {
                 $return[$scenario->getId()] = $scenario->toHtml(init('version'));
             }
         }
         ajax::success($return);
Exemple #20
0
 public static function getUsbMapping($_name = '', $_getGPIO = false)
 {
     $cache = cache::byKey('jeedom::usbMapping');
     if (!is_json($cache->getValue()) || $_name == '') {
         $usbMapping = array();
         foreach (ls('/dev/', 'ttyUSB*') as $usb) {
             $vendor = '';
             $model = '';
             foreach (explode("\n", shell_exec('/sbin/udevadm info --name=/dev/' . $usb . ' --query=all')) as $line) {
                 if (strpos($line, 'E: ID_MODEL=') !== false) {
                     $model = trim(str_replace(array('E: ID_MODEL=', '"'), '', $line));
                 }
                 if (strpos($line, 'E: ID_VENDOR=') !== false) {
                     $vendor = trim(str_replace(array('E: ID_VENDOR=', '"'), '', $line));
                 }
             }
             if ($vendor == '' && $model == '') {
                 $usbMapping['/dev/' . $usb] = '/dev/' . $usb;
             } else {
                 $name = trim($vendor . ' ' . $model);
                 $number = 2;
                 while (isset($usbMapping[$name])) {
                     $name = trim($vendor . ' ' . $model . ' ' . $number);
                     $number++;
                 }
                 $usbMapping[$name] = '/dev/' . $usb;
             }
         }
         if ($_getGPIO) {
             if (file_exists('/dev/ttyAMA0')) {
                 $usbMapping['Raspberry pi'] = '/dev/ttyAMA0';
             }
             if (file_exists('/dev/ttymxc0')) {
                 $usbMapping['Jeedom board'] = '/dev/ttymxc0';
             }
             if (file_exists('/dev/S2')) {
                 $usbMapping['Banana PI'] = '/dev/S2';
             }
             if (file_exists('/dev/ttyS2')) {
                 $usbMapping['Banana PI (2)'] = '/dev/ttyS2';
             }
             if (file_exists('/dev/ttyS0')) {
                 $usbMapping['Cubiboard'] = '/dev/ttyS0';
             }
             foreach (ls('/dev/', 'ttyACM*') as $value) {
                 $usbMapping['/dev/' . $value] = '/dev/' . $value;
             }
         }
         cache::set('jeedom::usbMapping', json_encode($usbMapping), 0);
     } else {
         $usbMapping = json_decode($cache->getValue(), true);
     }
     if ($_name != '') {
         if (isset($usbMapping[$_name])) {
             return $usbMapping[$_name];
         }
         $usbMapping = self::getUsbMapping('', $_getGPIO);
         if (isset($usbMapping[$_name])) {
             return $usbMapping[$_name];
         }
         if (file_exists($_name)) {
             return $_name;
         }
         return '';
     }
     return $usbMapping;
 }
Exemple #21
0
 public function getTranslation($_language)
 {
     $dir = dirname(__FILE__) . '/../../plugins/' . $this->getId() . '/core/i18n';
     if (!file_exists($dir)) {
         @mkdir($dir, 0775, true);
     }
     if (!file_exists($dir)) {
         return array();
     }
     if (file_exists($dir . '/' . $_language . '.json')) {
         $return = file_get_contents($dir . '/' . $_language . '.json');
         if (is_json($return)) {
             return json_decode($return, true);
         } else {
             return array();
         }
     }
     return array();
 }
Exemple #22
0
 /**
  * @throws \Zend_Json_Exception
  */
 protected function logUsageStatistics()
 {
     $params = [];
     $disallowedKeys = ["_dc", "module", "controller", "action", "password"];
     foreach ($this->getAllParams() as $key => $value) {
         if (is_json($value)) {
             $value = \Zend_Json::decode($value);
             if (is_array($value)) {
                 array_walk_recursive($value, function (&$item, $key) {
                     if (strpos($key, "pass") !== false) {
                         $item = "*************";
                     }
                 });
             }
             $value = \Zend_Json::encode($value);
         }
         if (!in_array($key, $disallowedKeys) && is_string($value)) {
             $params[$key] = strlen($value) > 40 ? substr($value, 0, 40) . "..." : $value;
         }
     }
     \Pimcore\Log\Simple::log("usagelog", ($this->getUser() ? $this->getUser()->getId() : "0") . "|" . $this->getParam("module") . "|" . $this->getParam("controller") . "|" . $this->getParam("action") . "|" . @json_encode($params));
 }
 public function validate_datajson($datajson_url = null, $datajson = null, $headers = null, $schema = null, $return_source = false, $quality = false, $component = null)
 {
     if ($datajson_url) {
         $datajson_header = $headers ? $headers : $this->campaign->uri_header($datajson_url);
         $errors = array();
         // Max file size
         $max_remote_size = $this->config->item('max_remote_size');
         // Only download the data.json if we need to
         if (empty($datajson_header['download_content_length']) || $datajson_header['download_content_length'] < 0 || !empty($datajson_header['download_content_length']) && $datajson_header['download_content_length'] > 0 && $datajson_header['download_content_length'] < $max_remote_size) {
             // Load the JSON
             $opts = array('http' => array('method' => "GET", 'user_agent' => "Data.gov data.json crawler"));
             $context = stream_context_create($opts);
             $datajson = @file_get_contents($datajson_url, false, $context, -1, $max_remote_size + 1);
             if ($datajson == false) {
                 $datajson = curl_from_json($datajson_url, false, false);
                 if (!$datajson) {
                     $errors[] = "File not found or couldn't be downloaded";
                 }
             }
         }
         if (!empty($datajson) && (empty($datajson_header['download_content_length']) || $datajson_header['download_content_length'] < 0)) {
             $datajson_header['download_content_length'] = strlen($datajson);
         }
         // See if it exceeds max size
         if ($datajson_header['download_content_length'] > $max_remote_size) {
             //$filesize = human_filesize($datajson_header['download_content_length']);
             //$errors[] = "The data.json file is " . $filesize . " which is currently too large to parse with this tool. Sorry.";
             // Increase the timeout limit
             @set_time_limit(6000);
             $this->load->helper('file');
             if ($rawfile = $this->archive_file('datajson-lines', $this->current_office_id, $datajson_url)) {
                 $outfile = $rawfile . '.lines.json';
                 $stream = fopen($rawfile, 'r');
                 $out_stream = fopen($outfile, 'w+');
                 $listener = new DataJsonParser();
                 $listener->out_file = $out_stream;
                 if ($this->environment == 'terminal' or $this->environment == 'cron') {
                     echo 'Attempting to convert to JSON lines' . PHP_EOL;
                 }
                 try {
                     $parser = new JsonStreamingParser_Parser($stream, $listener);
                     $parser->parse();
                 } catch (Exception $e) {
                     fclose($stream);
                     throw $e;
                 }
                 // Get the dataset count
                 $datajson_lines_count = $listener->_array_count;
                 // Delete temporary raw source file
                 unlink($rawfile);
                 $out_stream = fopen($outfile, 'r+');
                 $chunk_cycle = 0;
                 $chunk_size = 200;
                 $chunk_count = intval(ceil($datajson_lines_count / $chunk_size));
                 $buffer = '';
                 $response = array();
                 $response['errors'] = array();
                 if ($quality !== false) {
                     $response['qa'] = array();
                 }
                 echo "Analyzing {$datajson_lines_count} lines in {$chunk_count} chunks of {$chunk_size} lines each" . PHP_EOL;
                 while ($chunk_cycle < $chunk_count) {
                     $buffer = '';
                     $datajson_qa = null;
                     $counter = 0;
                     if ($chunk_cycle > 0) {
                         $key_offset = $chunk_size * $chunk_cycle;
                     } else {
                         $key_offset = 0;
                     }
                     $next_offset = $key_offset + $chunk_size;
                     //echo "Analyzing chunk $chunk_cycle of $chunk_count ($key_offset to $next_offset of $datajson_lines_count)" . PHP_EOL;
                     if ($chunk_cycle == 0) {
                         $json_header = fgets($out_stream);
                     }
                     while (($buffer .= fgets($out_stream)) && $counter < $chunk_size) {
                         $counter++;
                     }
                     $buffer = $json_header . $buffer;
                     $buffer = substr($buffer, 0, strlen($buffer) - 2) . ']}';
                     $validator = $this->campaign->jsonschema_validator($buffer, 'federal-v1.1');
                     if (!empty($validator['errors'])) {
                         $response['errors'] = array_merge($response['errors'], $this->process_validation_errors($validator['errors'], $key_offset));
                     }
                     if ($quality !== false) {
                         $datajson_qa = $this->campaign->datajson_qa($buffer, 'federal-v1.1', $quality, $component);
                         if (!empty($datajson_qa)) {
                             $response['qa'] = array_merge_recursive($response['qa'], $datajson_qa);
                         }
                     }
                     $chunk_cycle++;
                 }
                 // Delete json lines file
                 unlink($outfile);
                 // ###################################################################
                 // Needs to be refactored into separate function
                 // ###################################################################
                 // Sum QA counts
                 if (!empty($response['qa'])) {
                     if (!empty($response['qa']['bureauCodes'])) {
                         $response['qa']['bureauCodes'] = array_keys($response['qa']['bureauCodes']);
                     }
                     if (!empty($response['qa']['programCodes'])) {
                         $response['qa']['programCodes'] = array_keys($response['qa']['programCodes']);
                     }
                     $sum_array_fields = array('API_total', 'downloadURL_present', 'downloadURL_total', 'accessURL_present', 'accessURL_total', 'accessLevel_public', 'accessLevel_restricted', 'accessLevel_nonpublic', 'license_present', 'redaction_present', 'redaction_no_explanation');
                     foreach ($sum_array_fields as $array_field) {
                         if (!empty($response['qa'][$array_field]) && is_array($response['qa'][$array_field])) {
                             $response['qa'][$array_field] = array_sum($response['qa'][$array_field]);
                         }
                     }
                     // Sum validation counts
                     if (!empty($response['qa']['validation_counts']) && is_array($response['qa']['validation_counts'])) {
                         foreach ($response['qa']['validation_counts'] as $validation_key => $validation_count) {
                             if (is_array($response['qa']['validation_counts'][$validation_key])) {
                                 $response['qa']['validation_counts'][$validation_key] = array_sum($response['qa']['validation_counts'][$validation_key]);
                             }
                         }
                     }
                 }
                 $response['valid'] = empty($response['errors']) ? true : false;
                 $response['valid_json'] = true;
                 $response['total_records'] = $datajson_lines_count;
                 if (!empty($datajson_header['download_content_length'])) {
                     $response['download_content_length'] = $datajson_header['download_content_length'];
                 }
                 if (empty($response['errors'])) {
                     $response['errors'] = false;
                 }
                 return $response;
                 // ###################################################################
             } else {
                 $errors[] = "File not found or couldn't be downloaded";
             }
         }
         // See if it's valid JSON
         if (!empty($datajson) && $datajson_header['download_content_length'] < $max_remote_size) {
             // See if raw file is valid
             $raw_valid_json = is_json($datajson);
             // See if we can clean up the file to make it valid
             if (!$raw_valid_json) {
                 $datajson_processed = json_text_filter($datajson);
                 $valid_json = is_json($datajson_processed);
             } else {
                 $valid_json = true;
             }
             if ($valid_json !== true) {
                 $errors[] = 'The validator was unable to determine if this was valid JSON';
             }
         }
         if (!empty($errors)) {
             $valid_json = isset($valid_json) ? $valid_json : null;
             $raw_valid_json = isset($raw_valid_json) ? $raw_valid_json : null;
             $response = array('raw_valid_json' => $raw_valid_json, 'valid_json' => $valid_json, 'valid' => false, 'fail' => $errors, 'download_content_length' => $datajson_header['download_content_length']);
             if ($valid_json && $return_source === false) {
                 $catalog = json_decode($datajson_processed);
                 if ($schema == 'federal-v1.1' or $schema == 'non-federal-v1.1') {
                     $response['total_records'] = count($catalog->dataset);
                 } else {
                     $response['total_records'] = count($catalog);
                 }
             }
             return $response;
         }
     }
     // filter string for json conversion if we haven't already
     if ($datajson && empty($datajson_processed)) {
         $datajson_processed = json_text_filter($datajson);
     }
     // verify it's valid json
     if ($datajson_processed) {
         if (!isset($valid_json)) {
             $valid_json = is_json($datajson_processed);
         }
     }
     if ($datajson_processed && $valid_json) {
         $datajson_decode = json_decode($datajson_processed);
         if (!empty($datajson_decode->conformsTo) && $datajson_decode->conformsTo == 'https://project-open-data.cio.gov/v1.1/schema') {
             if ($schema !== 'federal-v1.1' && $schema !== 'non-federal-v1.1') {
                 if ($schema == 'federal') {
                     $schema = 'federal-v1.1';
                 } else {
                     if ($schema == 'non-federal') {
                         $schema = 'non-federal-v1.1';
                     } else {
                         $schema = 'federal-v1.1';
                     }
                 }
             }
             $this->schema = $schema;
         }
         if ($schema == 'federal-v1.1' && empty($datajson_decode->dataset)) {
             $errors[] = "This file does not appear to be using the federal-v1.1 schema";
             $response = array('raw_valid_json' => $raw_valid_json, 'valid_json' => $valid_json, 'valid' => false, 'fail' => $errors);
             return $response;
         }
         if ($schema !== 'federal-v1.1' && $schema !== 'non-federal-v1.1') {
             $chunk_size = 500;
             $datajson_chunks = array_chunk($datajson_decode, $chunk_size);
         } else {
             $datajson_chunks = array($datajson_decode);
         }
         $response = array();
         $response['errors'] = array();
         if ($quality !== false) {
             $response['qa'] = array();
         }
         // save detected schema version to output
         $response['schema_version'] = $schema;
         foreach ($datajson_chunks as $chunk_count => $chunk) {
             $chunk = json_encode($chunk);
             $validator = $this->campaign->jsonschema_validator($chunk, $schema);
             if (!empty($validator['errors'])) {
                 if ($chunk_count) {
                     $key_offset = $chunk_size * $chunk_count;
                     $key_offset = $key_offset;
                 } else {
                     $key_offset = 0;
                 }
                 $response['errors'] = $response['errors'] + $this->process_validation_errors($validator['errors'], $key_offset);
             }
             if ($quality !== false) {
                 $datajson_qa = $this->campaign->datajson_qa($chunk, $schema, $quality, $component);
                 if (!empty($datajson_qa)) {
                     $response['qa'] = array_merge_recursive($response['qa'], $datajson_qa);
                 }
             }
         }
         // Sum QA counts
         if (!empty($response['qa'])) {
             if (!empty($response['qa']['bureauCodes'])) {
                 $response['qa']['bureauCodes'] = array_keys($response['qa']['bureauCodes']);
             }
             if (!empty($response['qa']['programCodes'])) {
                 $response['qa']['programCodes'] = array_keys($response['qa']['programCodes']);
             }
             $sum_array_fields = array('accessURL_present', 'accessURL_total', 'accessLevel_public', 'accessLevel_restricted', 'accessLevel_nonpublic');
             foreach ($sum_array_fields as $array_field) {
                 if (!empty($response['qa'][$array_field]) && is_array($response['qa'][$array_field])) {
                     $response['qa'][$array_field] = array_sum($response['qa'][$array_field]);
                 }
             }
             // Sum validation counts
             if (!empty($response['qa']['validation_counts']) && is_array($response['qa']['validation_counts'])) {
                 foreach ($response['qa']['validation_counts'] as $validation_key => $validation_count) {
                     if (is_array($response['qa']['validation_counts'][$validation_key])) {
                         $response['qa']['validation_counts'][$validation_key] = array_sum($response['qa']['validation_counts'][$validation_key]);
                     }
                 }
             }
         }
         $valid_json = isset($raw_valid_json) ? $raw_valid_json : $valid_json;
         $response['valid'] = empty($response['errors']) ? true : false;
         $response['valid_json'] = $valid_json;
         if ($schema == 'federal-v1.1' or $schema == 'non-federal-v1.1') {
             $response['total_records'] = count($datajson_decode->dataset);
         } else {
             $response['total_records'] = count($datajson_decode);
         }
         if (!empty($datajson_header['download_content_length'])) {
             $response['download_content_length'] = $datajson_header['download_content_length'];
         }
         if (empty($response['errors'])) {
             $response['errors'] = false;
         }
         if ($return_source) {
             $dataset_array = ($schema == 'federal-v1.1' or $schema == 'non-federal-v1.1') ? true : false;
             $datajson_decode = filter_json($datajson_decode, $dataset_array);
             $response['source'] = $datajson_decode;
         }
         return $response;
     } else {
         $errors[] = "This does not appear to be valid JSON";
         $response = array('valid_json' => false, 'valid' => false, 'fail' => $errors);
         if (!empty($datajson_header['download_content_length'])) {
             $response['download_content_length'] = $datajson_header['download_content_length'];
         }
         return $response;
     }
 }
<?php

$atts = array('class' => '', 'data-bind' => 'submit: CategoryBuilder.updateCategorization', 'method' => 'POST', 'id' => '');
$categorization = (array) $categorization;
$hidden = array('active' => false, 'id' => element('id', $categorization));
$cat_settings = unserialize(element('cat_settings', $categorization));
$cat_settings = $cat_settings && is_json($cat_settings) ? $cat_settings : json_encode(array('url' => base_url('data/category-builder-template.js')), JSON_UNESCAPED_SLASHES);
$cat_settings = htmlspecialchars($cat_settings, ENT_QUOTES, 'UTF-8');
echo form_open('tools/categorybuilder/edit/' . element('id', $categorization), $atts, $hidden);
?>
	
<div class="row">
	<div class="col-md-4 col-sm-3">
		<div class="box">
			<div class="box-header with-border">
				<h3 class="box-title">
				<i class="fa fa-info-circle"></i>
					Basic Info
				</h3>
				<div class="box-tools pull-right">
					<a class="btn btn-success btn-flat btn-sm pull-right" href="<?php 
echo base_url('tools/categorybuilder/add');
?>
" >New Categorization</a>
				</div>
			</div>		
			<div class="box-body" >
				<div class="form-group">
					<label class="control-label" for="name"><span class="text-danger">*</span> Name</label>		  
					<?php 
$data = array('name' => 'name', 'id' => 'name', 'maxlength' => '30', 'class' => 'form-control', 'value' => element('name', $categorization), 'placeholder' => 'Enter name');
Exemple #25
0
 public function toHtml($_version = 'dashboard', $options = '', $_cmdColor = null, $_cache = 2)
 {
     $version = jeedom::versionAlias($_version);
     $html = '';
     $template_name = 'cmd.' . $this->getType() . '.' . $this->getSubType() . '.' . $this->getTemplate($version, 'default');
     $template = '';
     if (!isset(self::$_templateArray[$version . '::' . $template_name])) {
         if ($this->getTemplate($version, 'default') != 'default') {
             if (config::byKey('active', 'widget') == 1) {
                 $template = getTemplate('core', $version, $template_name, 'widget');
             }
             if ($template == '') {
                 foreach (plugin::listPlugin(true) as $plugin) {
                     $template = getTemplate('core', $version, $template_name, $plugin->getId());
                     if ($template != '') {
                         break;
                     }
                 }
             }
             if ($template == '') {
                 $template_name = 'cmd.' . $this->getType() . '.' . $this->getSubType() . '.default';
                 $template = getTemplate('core', $version, $template_name);
             }
         } else {
             $template = getTemplate('core', $version, $template_name);
         }
         self::$_templateArray[$version . '::' . $template_name] = $template;
     } else {
         $template = self::$_templateArray[$version . '::' . $template_name];
     }
     $replace = array('#id#' => $this->getId(), '#name#' => $this->getDisplay('icon') != '' ? $this->getDisplay('icon') : $this->getName(), '#name_display#' => $this->getDisplay('icon') != '' ? $this->getDisplay('icon') : $this->getName(), '#history#' => '', '#displayHistory#' => 'display : none;', '#unite#' => $this->getUnite(), '#minValue#' => $this->getConfiguration('minValue', 0), '#maxValue#' => $this->getConfiguration('maxValue', 100), '#logicalId#' => $this->getLogicalId());
     if ($_cmdColor == null && $version != 'scenario') {
         $eqLogic = $this->getEqLogic();
         $vcolor = $version == 'mobile' ? 'mcmdColor' : 'cmdColor';
         if ($eqLogic->getPrimaryCategory() == '') {
             $replace['#cmdColor#'] = jeedom::getConfiguration('eqLogic:category:default:' . $vcolor);
         } else {
             $replace['#cmdColor#'] = jeedom::getConfiguration('eqLogic:category:' . $eqLogic->getPrimaryCategory() . ':' . $vcolor);
         }
     } else {
         $replace['#cmdColor#'] = $_cmdColor;
     }
     if ($this->getDisplay('doNotShowNameOnView') == 1 && ($_version == 'dview' || $_version == 'mview')) {
         $replace['#name_display#'] = '';
         $replace['#name#'] = '';
     } else {
         if ($this->getDisplay('doNotShowNameOnDashboard') == 1 && ($_version == 'mobile' || $_version == 'dashboard')) {
             $replace['#name_display#'] = '';
             $replace['#name#'] = '';
         } else {
             $replace['#name_display#'] .= '<br/>';
         }
     }
     if ($this->getType() == 'info') {
         $replace['#state#'] = '';
         $replace['#tendance#'] = '';
         $replace['#state#'] = $this->execCmd(null, $_cache);
         if (strpos($replace['#state#'], 'error::') !== false) {
             $template = getTemplate('core', $version, 'cmd.error');
             $replace['#state#'] = str_replace('error::', '', $replace['#state#']);
         } else {
             if ($this->getSubType() == 'binary' && $this->getDisplay('invertBinary') == 1) {
                 $replace['#state#'] = $replace['#state#'] == 1 ? 0 : 1;
             }
         }
         if (method_exists($this, 'formatValueWidget')) {
             $replace['#state#'] = $this->formatValueWidget($replace['#state#']);
         }
         $replace['#collectDate#'] = $this->getCollectDate();
         $replace['#valueDate#'] = $this->getValueDate();
         if ($this->getIsHistorized() == 1) {
             $replace['#history#'] = 'history cursor';
             if (config::byKey('displayStatsWidget') == 1 && strpos($template, '#displayHistory#') !== false) {
                 $showStat = true;
                 if ($this->getDisplay('doNotShowStatOnDashboard') == 1 && $_version == 'dashboard') {
                     $showStat = false;
                 }
                 if ($this->getDisplay('doNotShowStatOnView') == 1 && ($_version == 'dview' || $_version == 'mview')) {
                     $showStat = false;
                 }
                 if ($this->getDisplay('doNotShowStatOnMobile') == 1 && $_version == 'mobile') {
                     $showStat = false;
                 }
                 if ($showStat) {
                     $startHist = date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s') . ' -' . config::byKey('historyCalculPeriod') . ' hour'));
                     $replace['#displayHistory#'] = '';
                     $historyStatistique = $this->getStatistique($startHist, date('Y-m-d H:i:s'));
                     if ($historyStatistique['avg'] == 0 && $historyStatistique['min'] == 0 && $historyStatistique['max'] == 0) {
                         $replace['#averageHistoryValue#'] = round($replace['#state#'], 1);
                         $replace['#minHistoryValue#'] = round($replace['#state#'], 1);
                         $replace['#maxHistoryValue#'] = round($replace['#state#'], 1);
                     } else {
                         $replace['#averageHistoryValue#'] = round($historyStatistique['avg'], 1);
                         $replace['#minHistoryValue#'] = round($historyStatistique['min'], 1);
                         $replace['#maxHistoryValue#'] = round($historyStatistique['max'], 1);
                     }
                     $startHist = date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s') . ' -' . config::byKey('historyCalculTendance') . ' hour'));
                     $tendance = $this->getTendance($startHist, date('Y-m-d H:i:s'));
                     if ($tendance > config::byKey('historyCalculTendanceThresholddMax')) {
                         $replace['#tendance#'] = 'fa fa-arrow-up';
                     } else {
                         if ($tendance < config::byKey('historyCalculTendanceThresholddMin')) {
                             $replace['#tendance#'] = 'fa fa-arrow-down';
                         } else {
                             $replace['#tendance#'] = 'fa fa-minus';
                         }
                     }
                 }
             }
         }
         $parameters = $this->getDisplay('parameters');
         if (is_array($parameters)) {
             foreach ($parameters as $key => $value) {
                 $replace['#' . $key . '#'] = $value;
             }
         }
         return template_replace($replace, $template);
     } else {
         $cmdValue = $this->getCmdValue();
         if (is_object($cmdValue) && $cmdValue->getType() == 'info') {
             $replace['#state#'] = $cmdValue->execCmd(null, 2);
             $replace['#valueName#'] = $cmdValue->getName();
             $replace['#unite#'] = $cmdValue->getUnite();
         } else {
             $replace['#state#'] = $this->getLastValue() != null ? $this->getLastValue() : '';
             $replace['#valueName#'] = $this->getName();
             $replace['#unite#'] = $this->getUnite();
         }
         $parameters = $this->getDisplay('parameters');
         if (is_array($parameters)) {
             foreach ($parameters as $key => $value) {
                 $replace['#' . $key . '#'] = $value;
             }
         }
         $replace['#valueName#'] .= '<br/>';
         $html .= template_replace($replace, $template);
         if (trim($html) == '') {
             return $html;
         }
         if ($options != '') {
             $options = jeedom::toHumanReadable($options);
             if (is_json($options)) {
                 $options = json_decode($options, true);
             }
             if (is_array($options)) {
                 foreach ($options as $key => $value) {
                     $replace['#' . $key . '#'] = $value;
                 }
             }
         }
         if ($version == 'scenario' && $this->getType() == 'action' && $this->getSubtype() == 'message') {
             if (!isset($replace['#title#'])) {
                 $replace['#title#'] = '';
             }
             if (!isset($replace['#message#'])) {
                 $replace['#message#'] = '';
             }
         }
         if ($version == 'scenario' && $this->getType() == 'action' && $this->getSubtype() == 'slider' && !isset($replace['#slider#'])) {
             $replace['#slider#'] = '';
         }
         if ($version == 'scenario' && $this->getType() == 'action' && $this->getSubtype() == 'slider' && !isset($replace['#color#'])) {
             $replace['#color#'] = '';
         }
         $replace['#title_placeholder#'] = $this->getDisplay('title_placeholder', __('Titre', __FILE__));
         $replace['#message_placeholder#'] = $this->getDisplay('message_placeholder', __('Message', __FILE__));
         $replace['#message_disable#'] = $this->getDisplay('message_disable', 0);
         $replace['#title_disable#'] = $this->getDisplay('title_disable', 0);
         $replace['#title_possibility_list#'] = $this->getDisplay('title_possibility_list', '');
         $replace['#slider_placeholder#'] = $this->getDisplay('slider_placeholder', __('Valeur', __FILE__));
         $html = template_replace($replace, $html);
         return $html;
     }
 }
Exemple #26
0
 /**
  * __data() is the generic __data proxy and is called on each access via getData()
  *
  * @param Doozr_Base_State_Interface       $state         The request state object
  * @param Doozr_Base_Presenter_Rest_Config $configuration The configuration
  *
  * @author Benjamin Carl <*****@*****.**>
  * @return void
  * @access protected
  * @throws Doozr_Base_Model_Rest_Exception
  * @throws Doozr_Exception
  */
 protected function __data(Doozr_Base_State_Interface $state, Doozr_Base_Presenter_Rest_Config $configuration)
 {
     // Store state of this model
     /* @var $state Doozr_Request_State */
     $this->setStateObject($state);
     // Extract additional arguments from route
     $model = $this;
     /* @var $model Doozr_Base_Model */
     $resource = $this->getStateObject()->get($configuration->getRootNode() . $configuration->getRoute(), function () use($model) {
         $result = [];
         foreach (func_get_args() as $argument) {
             $result[] = $model->escape($argument);
         }
         return $result;
     });
     // Build a key => value store from already extracted identifiers and the recently extracted resource array
     $routeArguments = array_combine($configuration->getIds(), $resource);
     // Get arguments passed with this request
     $requestArguments = $this->getStateObject()->getQueryParams();
     // Get the identifier of the field/argument containing the real Id (uid) of the resource
     $id = $configuration->getId();
     if ($id !== null) {
         // Check for passed Id for all follow up operations on this resource
         if (array_key_exists('{{' . $id . '}}', $routeArguments)) {
             $id = $routeArguments['{{' . $id . '}}'];
         } elseif (isset($requestArguments->{$id})) {
             $id = $requestArguments->{$id};
         }
     }
     // Combine arguments from "route" with arguments from "request"
     $arguments = $this->mergeArguments($routeArguments, $requestArguments);
     // Check for submitted DOOZR_REQUEST_BODY and extract the structure so we can access the arguments
     if (isset($arguments['DOOZR_REQUEST_BODY']) === true && is_json($arguments['DOOZR_REQUEST_BODY'])) {
         $arguments = object_to_array(json_decode($arguments['DOOZR_REQUEST_BODY']));
     }
     $data = null;
     // Dispatch to resource manager if one is defined...
     $method = $this->getMethodByVerbAndRoute($this->getStateObject()->getMethod(), $configuration->getRealRoute());
     if (is_callable(array($this, $method))) {
         $data = $this->{$method}($configuration, $arguments, getallheaders(), $id);
     } else {
         // Inform developer about a not resolvable route endpoint and show him/her the methods available as hint!
         $methodsDefined = get_class_methods(__CLASS__);
         throw new Doozr_Base_Model_Rest_Exception('Could not call "' . $method . '" operation method in model "' . __CLASS__ . '". Currently defined methods of the model [unordered] are: ' . var_export($methodsDefined, true));
     }
     // So we just need to set our new fresh (or updated) data internally. "protected $data" is returned by
     // getData() to caller :) If the caller follows our strict call api
     $this->setData($data);
 }
Exemple #27
0
     }
     $history = history::byCmdIdDatetime(init('cmd_id'), init('datetime'));
     if (!is_object($history)) {
         throw new Exception(__('Aucun point ne correspond pour l\'historique : ', __FILE__) . init('cmd_id') . ' - ' . init('datetime'));
     }
     $history->setValue(init('value', null));
     $history->save(null, true);
     ajax::success();
 }
 if (init('action') == 'getHistory') {
     $return = array();
     $data = array();
     $dateStart = null;
     $dateEnd = null;
     if (init('dateRange') != '' && init('dateRange') != 'all') {
         if (is_json(init('dateRange'))) {
             $dateRange = json_decode(init('dateRange'), true);
             if (isset($dateRange['start'])) {
                 $dateStart = $dateRange['start'];
             }
             if (isset($dateRange['end'])) {
                 $dateEnd = $dateRange['end'];
             }
         } else {
             $dateEnd = date('Y-m-d H:i:s');
             $dateStart = date('Y-m-d 00:00:00', strtotime('- ' . init('dateRange') . ' ' . $dateEnd));
         }
     }
     if (init('dateStart') != '') {
         $dateStart = init('dateStart');
     }
 /**
  * TO DO - when agencies provide a valid url, we should validate that before
  * the download.
  *
  * Open the archived file that has been downloaded in campaign status method and
  * validate it against the schema
  *
  * @param <array> $status
  * @param <string> $file_path
  * @param <string> $component
  * @param <string> $real_url
  */
 public function validate_archive_file_with_schema($status, $file_path, $component, $real_url)
 {
     $fp = fopen($file_path, 'r');
     if (!$fp) {
         $status['errors'][] = "Unable to open archived json file";
     }
     $status['total_records'] = 0;
     $status['download_content_length'] = 0;
     $status['content_type'] = "application/json";
     $status['schema_version'] = "1.0";
     $json = file_get_contents($file_path);
     if (empty($json)) {
         $status['errors'][] = 'Archived json file is empty';
         $status['valid_json'] = false;
     } else {
         if (!is_json($json)) {
             $json = json_text_filter($json);
         }
     }
     if (!empty($json) && !is_json($json)) {
         $status['errors'][] = 'Invalid archived json file';
         $status['valid_json'] = false;
     } else {
         $status['download_content_length'] = strlen($json);
         $data = json_decode($json);
         $status['total_records'] = count($data);
         $status['valid_json'] = true;
     }
     $schema = $this->datajson_schema($component);
     if (!empty($data)) {
         $validator = new JsonSchema\Validator();
         $validator->check($data, $schema);
         if (!$validator->isValid()) {
             $errors = $validator->getErrors();
             $status['schema_errors'] = $errors;
         }
     }
     return $status;
 }
 public static function getExpressionOptions($_expression, $_options)
 {
     $startLoadTime = getmicrotime();
     $cmd = cmd::byId(str_replace('#', '', cmd::humanReadableToCmd($_expression)));
     if (is_object($cmd)) {
         $return['html'] = trim($cmd->toHtml('scenario', $_options));
     } else {
         try {
             $return['html'] = getTemplate('core', 'scenario', $_expression . '.default');
             if (is_json($_options)) {
                 $_options = json_decode($_options, true);
             }
             if (is_array($_options) && count($_options) > 0) {
                 foreach ($_options as $key => $value) {
                     $replace['#' . $key . '#'] = $value;
                 }
             }
             if (!isset($replace['#id#'])) {
                 $replace['#id#'] = rand();
             }
             $return['html'] = template_replace(cmd::cmdToHumanReadable($replace), $return['html']);
         } catch (Exception $e) {
         }
     }
     $replace = array('#uid#' => 'exp' . mt_rand());
     $return['html'] = translate::exec(template_replace($replace, $return['html']), 'core/template/scenario/' . $_expression . '.default');
     return $return;
 }
Exemple #30
0
    $hostLogSaltID = $pmxHostLog->newSaltID();
    /**
     * 命令的名字
     */
    $cname = $command;
    if ($pmxHostLog->addCommand($sid, $cname, $command, $hostLogSaltID)) {
        json_out(1, "Success.", $command);
    } else {
        json_out(0, "False.");
    }
} else {
    $mid = isset($_REQUEST['mid']) ? $_REQUEST['mid'] : "";
    $mconfig = isset($_REQUEST['data']) ? $_REQUEST['data'] : "";
    // 用户提交的模块参数
    if ($mconfig != "") {
        if (!is_json($mconfig)) {
            json_out(0, "The module configure is invalid.");
        }
        $mconfig = json_decode($mconfig, TRUE);
        // array(参数名, 参数值)
    } else {
        $mconfig = array();
    }
    /**
     * 模块是否可使用
     */
    if (in_array($mid, $mid_deny)) {
        json_out(0, "The module you have selected is only for project.");
    }
    /**
     * 模块是否存在