static function unwrap($token, $domains, $address = null) { if ($package = base64_decode($token, true)) { if ($package = json::decode($package)) { if (isset($package->value) and isset($package->domain) and isset($package->expire_at) and isset($package->digest)) { $digest = $package->digest; unset($package->digest); if ($digest === self::digest($package)) { if (isset($package->address)) { if (is_null($address) or $package->address !== $address) { return null; } } if ($package->expire_at === 0 or $package->expire_at > @time()) { foreach ($domains as $domain) { if (ends_with('.' . $package->domain, '.' . $domain)) { return $package->value; } } } } } } } return null; }
public function make_call($path, $data = array(), $method = "GET") { $fields = $this->getFields($data); $field_string = implode('&', $fields); //open connection $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //what type of request? if ($method == "GET") { curl_setopt($ch, CURLOPT_URL, $this->api_url . $path . '?' . $field_string); } elseif ($method == "POST" || $method == "PATCH" || $method == "DELETE") { if ($method == "PATCH") { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH"); } if ($method == "DELETE") { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); } curl_setopt($ch, CURLOPT_URL, $this->api_url . $path); curl_setopt($ch, CURLOPT_POST, count($fields)); curl_setopt($ch, CURLOPT_POSTFIELDS, $field_string); } //execute post $result = curl_exec($ch); //close connection curl_close($ch); //send our data back return json::decode($result); }
function request($type, $url, $get = [], $post = []) { $developer = cookie::developer(); if ($developer) { $get['_mode'] = 'developer'; } $request = ['method' => $type, 'protocol_version' => '1.1', 'header' => 'Connection: Close']; foreach ($post as $name => &$param) { if (is_array($param) and empty($param)) { $param = '_empty_array'; } } if (!empty($post)) { $request['header'] .= "\r\nContent-type: application/x-www-form-urlencoded"; $request['content'] = http_build_query($post); } $ctx = stream_context_create(['http' => $request]); $response = file_get_contents($this->endpoint . (empty($get) ? $url : $url . '?' . http_build_query($get)), false, $ctx); $object = json::decode($response, true); if (is_null($object)) { if ($developer) { var_dump($response); die; } else { throw new Exception("Error Processing Request", 1); } } $content = $object['content']; return (is_object($content) or is_array($content) and array_values($content) !== $content) ? (object) $content : $content; }
function query_direct($args) { switch ($this->method) { case 'photos': isset($args['_venue_id']) or backend_error('bad_query', 'Foursquare _venue_id argument missing'); $photos = []; if ($result = json::decode(file_get_contents('https://api.foursquare.com/v2/venues/' . $args['venue_id'] . '/photos?' . $this->foursquare->get()))) { foreach ($result->response->photos->groups as $group) { if ($group->type == 'venue') { foreach ($group->items as $item) { $photo = ['url' => $item->url, 'created' => $item->createdAt, 'user' => ['id' => $item->user->id, 'firstName' => $item->user->firstName, 'lastName' => @$item->user->lastName, 'gender' => $item->user->gender, 'photo' => $item->user->photo]]; $resampled = []; foreach ($item->sizes->items as $size) { $resampled[] = ['url' => $size->url, 'width' => $size->width, 'height' => $size->height]; } $photo['resampled'] = $resampled; $photos[] = $photo; } } } } !(empty($photos) and $this->required) or backend_error('bad_input', 'Empty response from Froursquare procedure'); return (object) $photos; case 'venues': isset($args['_latitude']) or backend_error('bad_query', 'Foursquare _latitude argument missing'); isset($args['_longitude']) or backend_error('bad_query', 'Foursquare _longitude argument missing'); $venues = []; if ($result = json::decode(file_get_contents('https://api.foursquare.com/v2/venues/search?ll=' . $args['_latitude'] . ',' . $args['_longitude'] . '&' . $this->foursquare->get()))) { foreach ($result->response->groups as $group) { if ($group->type == 'nearby') { foreach ($group->items as $item) { $venue[] = ['id' => $item->id, 'name' => $item->name, 'url' => $item->canonicalUrl]; $categories = []; foreach ($item->categories as $category) { $categories[] = ['id' => $category->id, 'name' => $category->name, 'pluralName' => $category->pluralName, 'shortName' => $category->shortName, 'icon' => $category->icon]; } $venue['categories'] = $categories; $venues[] = $venue; } } } } !(empty($venues) and $this->required) or backend_error('bad_input', 'Empty response from Froursquare procedure'); return (object) $venues; } }
public function make_call($path, $data = array(), $method = "GET") { //our parameters for the call $data['client_id'] = $this->client_id; $data['client_secret'] = $this->client_secret; $data['access_token'] = $this->user_token; //url-ify the data for the call $fields_string = ""; $fieldsCount = 0; foreach ($data as $key => $value) { $fields_string .= $key . '=' . $value . '&'; $fieldsCount++; } rtrim($fields_string, '&'); //open connection $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //what type of request? if ($method == "GET") { curl_setopt($ch, CURLOPT_URL, $this->api_url . $path . '?' . $fields_string); } elseif ($method == "POST" || $method == "PATCH" || $method == "DELETE") { if ($method == "PATCH") { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH"); } if ($method == "DELETE") { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); } curl_setopt($ch, CURLOPT_URL, $this->api_url . $path); curl_setopt($ch, CURLOPT_POST, $fieldsCount); curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string); } //execute post $result = curl_exec($ch); //$info = curl_getinfo($ch); //close connection curl_close($ch); //send our data back return json::decode($result); }
public function getDriverConfig() { //load up our config $config = json::decode($this->get('driver_config')); if (!is_object($config)) { $config = new stdClass(); } $config->name = $this->getName(); //default our slicing value if (!isset($config->can_slice)) { $config->can_slice = True; } return $config; }
function json_decode($string, $type = 1) { require_once 'json.class.php'; $json = new json(); return $json->decode($string, $type); }
function request($params, $global, $get, $post, $cookies, $files, $extensions) { $values = []; $batch = []; foreach (array_merge($global, $this->params) as $name => $param) { $value = self::substitute($param->value, $params); switch ($param->type) { case 'value': $values[$name] = $value; break; case 'json': $values[$name] = json::decode(fs::checked_read($value)); break; case 'xml': $values[$name] = 'TODO: Add XML support here'; break; case 'query': $batch[$name] = $value; break; case 'get': isset($get[$value]) or isset($param->default) or runtime_error('GET parameter not found: ' . $name); $values[$name] = isset($get[$value]) ? $get[$value] : $param->default; break; case 'post': isset($post[$value]) or isset($param->default) or runtime_error('POST parameter not found: ' . $name); $values[$name] = isset($post[$value]) ? $post[$value] : $param->default; break; case 'cookie': isset($cookies[$value]) or isset($param->default) or runtime_error('Cookie parameter not found: ' . $name); $values[$name] = isset($cookies[$value]) ? $cookies[$value] : $param->default; break; } } foreach ($batch as $name => &$value) { $value = preg_replace_callback('/\\{@(\\w+)\\}/', function ($matches) use($values) { return isset($values[$matches[1]]) ? $values[$matches[1]] : $matches[0]; }, $value); } $response = []; $params = array_merge($values, empty($batch) ? [] : $this->api->batch($batch)); if ($this->script) { $script_args = $params; if ($this->files) { $script_args = array_merge($script_args, [$this->files => $files]); } $prototype = '$' . implode(',$', array_keys($script_args)); $script = ''; foreach ($this->require as $require) { $script .= 'require_once(\'' . $this->scripts . $require . '\');'; } $script .= 'return function(' . (empty($script_args) ? '' : $prototype) . ") { {$this->script} };"; $closure = eval($script); if ($result = call_user_func_array($closure->bindTo($this->api), array_values($script_args))) { $params = array_replace($params, $result); } foreach (['cookies', 'redirect', 'headers'] as $builtin) { $mangled = '_' . $builtin; if (isset($params[$mangled])) { $response[$builtin] = $params[$mangled]; unset($params[$mangled]); } } } if ($this->template) { switch ($this->engine) { case 'twig': $loader = new Twig_Loader_Filesystem($this->templates); $options = []; if ($this->cache) { $options['cache'] = $this->cache; } $twig = new Twig_Environment($loader, $options); //$twig->addExtension(new Twig_Extension_Debug()); $twig->getExtension('core')->setNumberFormat(0, '.', ' '); $closure = function ($haystack, $needle) { return $needle === "" or strpos($haystack, $needle) === 0; }; $function = new Twig_SimpleFunction('starts_with', $closure); $twig->addFunction($function); $closure = function ($filename) { return json_decode(file_get_contents($this->data . $filename)); }; $function = new Twig_SimpleFunction('json', $closure->bindTo($this, $this)); $twig->addFunction($function); $closure = function ($object) { $array = []; foreach ($object as $key => $value) { $array[$key] = $value; } return $array; }; $filter = new Twig_SimpleFilter('array', $closure); $twig->addFilter($filter); $closure = function ($number) { return ceil($number); }; $filter = new Twig_SimpleFilter('ceil', $closure); $twig->addFilter($filter); $closure = function ($string) { return md5($string); }; $filter = new Twig_SimpleFilter('md5', $closure); $twig->addFilter($filter); $closure = function ($alias) { return $this->locale->get($alias); }; $function = new Twig_SimpleFilter('local', $closure->bindTo($this, $this)); $twig->addFilter($function); if (!is_null($extensions) and isset($extensions['twig'])) { if (isset($extensions['twig']['filters'])) { foreach ($extensions['twig']['filters'] as $name => $closure) { $twig->addFilter(new Twig_SimpleFilter($name, $closure->bindTo($this, $this))); } } if (isset($extensions['twig']['functions'])) { foreach ($extensions['twig']['functions'] as $name => $closure) { $twig->addFunction(new Twig_SimpleFunction($name, $closure->bindTo($this, $this))); } } } $template = $twig->loadTemplate($this->template); $response['content'] = $template->render($params); break; case 'smarty': $smarty = new Smarty(); $smarty->setTemplateDir($this->templates); if ($this->cache) { $smarty->setCompileDir($this->cache)->setCacheDir($this->cache); } $smarty->assign($params); $response['content'] = @$smarty->fetch($this->template); break; } } return (object) $response; }
public function driver_form() { try { //load our bot $bot = new Bot($this->args('id')); if (!$bot->isHydrated()) { throw new Exception("Could not find that bot."); } if (!$bot->isMine()) { throw new Exception("You cannot view that bot."); } if ($this->args('token_id') == 0) { $this->set('nodriver', "No driver was selected"); } else { //load our token $token = new OAuthToken($this->args('token_id')); if (!$token->isHydrated()) { throw new Exception("Could not find that computer."); } if (!$token->isMine()) { throw new Exception("This is not your computer."); } //what driver form to create? $driver = $this->args('driver'); //pass on our info. $this->set('bot', $bot); $this->set('driver', $driver); $this->set('token', $token); $devices = json::decode($token->get('device_data')); $this->set('devices', $devices); //pull in our driver config $driver_config = $bot->getDriverConfig(); //if we're using the same driver, pull in old values... if ($driver == $bot->get('driver_name')) { $this->set('driver_config', $driver_config); if (is_object($driver_config)) { $this->set('delay', $driver_config->delay); $this->set('serial_port', $driver_config->port); $this->set('baudrate', $driver_config->baud); } } else { if ($driver == "dummy") { $this->set('delay', '0.001'); } } //pull in our old webcam values too. if (is_object($driver_config) && !empty($driver_config->webcam)) { $this->set('webcam_id', $driver_config->webcam->id); $this->set('webcam_name', $driver_config->webcam->name); $this->set('webcam_device', $driver_config->webcam->device); $this->set('webcam_brightness', $driver_config->webcam->brightness); $this->set('webcam_contrast', $driver_config->webcam->contrast); } else { //some default webcam settings. $this->set('webcam_id', ''); $this->set('webcam_name', ''); $this->set('webcam_device', ''); $this->set('webcam_brightness', 50); $this->set('webcam_contrast', 50); } $this->set('driver_config', $driver_config); $this->set('baudrates', array(250000, 115200, 57600, 38400, 28880, 19200, 14400, 9600)); } } catch (Exception $e) { $this->set('megaerror', $e->getMessage()); } }
function jsonDecode($str) { $json = new json(); return $json->decode($str); }
public function canonizeEvent($extra, $event = array()) { // Check if (empty($extra)) { return ''; } // object to array if (is_object($extra)) { $extra = $extra->toArray(); } // Make register_discount $extra['register_discount'] = json::decode($extra['register_discount'], true); // Set register_details $extra['register_details'] = Pi::service('markup')->render($extra['register_details'], 'html', 'html'); // Set time $extra['time_start_view'] = empty($extra['time_start']) ? '' : _date($extra['time_start'], array('pattern' => 'yyyy-MM-dd')); $extra['time_end_view'] = empty($extra['time_end']) ? '' : _date($extra['time_end'], array('pattern' => 'yyyy-MM-dd')); // Set register_price if (is_numeric($extra['register_price']) && $extra['register_price'] > 0) { $uid = Pi::user()->getId(); $roles = Pi::user()->getRole($uid); if (!empty($extra['register_discount'])) { $price = $extra['register_price']; foreach ($extra['register_discount'] as $role => $percent) { if (isset($percent) && $percent > 0 && in_array($role, $roles)) { $price = $extra['register_price'] - $extra['register_price'] * ($percent / 100); } } $extra['register_price'] = $price; } if (Pi::service('module')->isActive('order')) { $priceView = Pi::api('api', 'order')->viewPrice($extra['register_price']); } else { $priceView = _currency($extra['register_price']); } } else { $priceView = _currency($extra['register_price']); } // Set order $config = Pi::service('registry')->config->read($this->getModule()); if ($config['order_active']) { if ($extra['register_price'] > 0 && $extra['register_stock'] > 0) { $extra['register_price_view'] = $priceView; } elseif ($extra['register_price'] > 0 && $extra['register_stock'] == 0) { $extra['register_price_view'] = sprintf(__('Out of stock ( %s )'), $priceView); } else { $extra['register_price_view'] = __('free!'); } } else { if (is_numeric($extra['register_price']) && $extra['register_price'] > 0) { $extra['register_price_view'] = _currency($extra['register_price']); } else { $extra['register_price_view'] = __('free!'); } } // Set currency $configSystem = Pi::service('registry')->config->read('system'); $extra['price_currency'] = empty($configSystem['number_currency']) ? 'USD' : $configSystem['number_currency']; // canonize guide module details $extra['guide_category'] = Json::decode($extra['guide_category'], true); $extra['guide_location'] = Json::decode($extra['guide_location'], true); $extra['guide_item'] = Json::decode($extra['guide_item'], true); // Set event url $extra['eventUrl'] = Pi::url(Pi::service('url')->assemble('event', array('module' => $this->getModule(), 'controller' => 'index', 'slug' => $extra['slug']))); // Set register url $extra['eventOrder'] = Pi::url(Pi::service('url')->assemble('event', array('module' => $this->getModule(), 'controller' => 'register', 'action' => 'add'))); // Set category if (isset($event['topics']) && !empty($event['topics'])) { $topicList = array(); foreach ($event['topics'] as $topic) { $topicList[] = array('title' => $topic['title'], 'url' => Pi::url(Pi::service('url')->assemble('event', array('module' => $this->getModule(), 'controller' => 'category', 'slug' => $topic['slug'])))); } $extra['topics'] = $topicList; } // Check guide module if (Pi::service('module')->isActive('guide') && !empty($extra['guide_location'])) { $locationList = Pi::registry('locationList', 'guide')->read(); $extra['locationInfo'] = $locationList[$extra['guide_location'][0]]; } return $extra; }
static function json($root, $json) { $xml = new xml(); $xml->append(self::assoc_node($xml, $root, json::decode($json, true))); return $xml; }
function json_decode($string) { return json::decode($string); }
function json($url) { $json = self::get($url); return json::decode($json); }
public function getArenaTeam($realm, $teamname, $size, $fields = null) { // URL: /api/wow/arena/{realm}/{size}/{name} (size being 2v2, 3v3 or 5v5) // Basic information: name, ranking, rating, weekly/season statistics // Optional fields: members (roster) $url = sprintf('http://%s.battle.net/api/wow/arena/%s/%s/%s', $this->region, $realm, $size, $teamname); $request = new HttpRequest($url); $ret = json::decode((string) $request); return $ret; }
/** * GENERAL SALES - monthly-Stock. * @author ptr.nov [ptr.nov@gmail.com] * @since 1.2 */ public function actionStockMonthly() { $request = Yii::$app->request; $tgl = $request->get('tgl'); $tglParam = $tgl != '' ? $tgl : date('Y-m-d'); //***get count data visiting $_visiting = new ArrayDataProvider(['allModels' => Yii::$app->db_esm->createCommand("\t\n\t\t\t\tSELECT \tx1.TGL, month(x1.TGL) AS bulan,DATE_FORMAT(x1.TGL,'%d') as TGL_NO,LEFT(COMPONEN_hari(x1.TGL),2) as hari, \n\t\t\t\t\t\tx1.CCval,x1.ACval,x2.ECval,x1.CASEval,x2.ACval_COMPARE\t\t\t\n\t\t\t\tFROM\n\t\t\t\t(\tSELECT \n\t\t\t\t\tsum(CASE WHEN a1.CUST_ID <> '' AND a1.STATUS_CASE<>1 THEN 1 ELSE 0 END) AS CCval,\n\t\t\t\t\tsum(CASE WHEN a1.CUST_ID <> '' AND a1.STATUS= 1 THEN 1 ELSE 0 END) AS ACval,\n\t\t\t\t\tsum(CASE WHEN a1.CUST_ID <> '' AND a1.STATUS_CASE=1 THEN 1 ELSE 0 END) AS CASEval,a1.TGL\n\t\t\t\t\tFROM c0002scdl_detail a1 LEFT JOIN c0001 a2 ON a2.CUST_KD=a1.CUST_ID\n\t\t\t\t\tWHERE a1.STATUS<>3 AND a2.CUST_NM not LIKE 'customer demo%'\n\t\t\t\t\tGROUP BY a1.TGL\n\t\t\t\t) x1 LEFT JOIN\n\t\t\t\t(\tSELECT sum(CASE WHEN ID IS NOT NULL THEN 1 ELSE 0 END) AS ACval_COMPARE,\n\t\t\t\t\t\t\tsum(CASE WHEN STATUS_EC IS NOT NULL THEN 1 ELSE 0 END) AS ECval,TGL\n\t\t\t\t\tFROM c0002rpt_cc_time x1\n\t\t\t\t\tWHERE CUST_NM not LIKE 'customer demo%'\t\n\t\t\t\t\tGROUP BY TGL\n\t\t\t\t) x2 on x2.TGL=x1.TGL\n\t\t\t\t#WHERE MONTH(x1.TGL)=10 AND x1.TGL <= CURDATE()\n\t\t\t\tWHERE MONTH(x1.TGL)=month('" . $tglParam . "') AND x1.TGL <= CURDATE()\n\t\t\t")->queryAll(), 'pagination' => ['pageSize' => 200]]); $_modelVisiting = ArrayHelper::toArray($_visiting->getModels()); foreach ($_modelVisiting as $row => $value) { $hari[] = ["label" => $value['hari'] . "-" . $value['TGL_NO'] . "-" . $value['bulan']]; $cc[] = ["value" => strval($value['CCval'])]; $ac[] = ["value" => strval($value['ACval'])]; $ec[] = ["value" => strval($value['ECval'])]; $case[] = ["value" => strval($value['CASEval'])]; $acSum[] = $value['ACval']; $ecSum[] = $value['ECval']; } //***get AVG AC FROM data visiting $cntAC = count($acSum); $sumAC = array_sum($acSum); $avgAC = $sumAC / $cntAC; $avgACnm = "AvgAC (" . number_format($avgAC, 2) . ")"; //***get AVG EC FROM data visiting $cntEC = count($ecSum); $sumEC = array_sum($ecSum); $avgEC = $sumEC / $cntEC; $avgECnm = "AvgEC (" . number_format($avgEC, 2) . ")"; /** * Maping Chart * Type : msline * */ $rsltSrc = '{ "chart": { "caption": "Summary Stock Month Of Year", "subCaption": "Supllier, Distributor, Sales ", "captionFontSize": "12", "subcaptionFontSize": "10", "subcaptionFontBold": "0", "paletteColors": "#cc0000,#1e86e5,#16ce87,#b7843d", "bgcolor": "#ffffff", "showBorder": "0", "showShadow": "0", "showCanvasBorder": "0", "usePlotGradientColor": "0", "legendBorderAlpha": "0", "legendShadow": "0", "showAxisLines": "0", "showAlternateHGridColor": "0", "divlineThickness": "1", "divLineIsDashed": "1", "divLineDashLen": "1", "divLineGapLen": "1", "xAxisName": "Day", "showValues": "1" }, "categories": [ { "category": ' . Json::encode($hari) . ' } ], "dataset": [ { "seriesname": "PO-Purchase", "data":' . Json::encode($cc) . ' }, { "seriesname": "Stock-Gudang", "data":' . Json::encode($ac) . ' }, { "seriesname": "PO-Sales", "data":' . Json::encode($ec) . ' }, { "seriesname": "CASE", "data":' . Json::encode($case) . ' } ], "trendlines": [ { "line": [ { "startvalue": "' . $avgAC . '", "color": "#0b0d0f", "valueOnRight": "1", "displayvalue":"' . $avgACnm . '" }, { "startvalue": "' . $avgEC . '", "color": "#0b0d0f", "valueOnRight": "1", "displayvalue": "' . $avgECnm . '" } ] } ] }'; return json::decode($rsltSrc); //return $avgAc; }
public static function run_test() { $array = array('foo' => array('bar', 'baz' => array(1, 2, 3, 4, 5, 6, 7), array('a', 'b', 'c', 'd')), 'bar' => array(5, 4, 3, 2, 1), 'oop' => 'oxxxbj&%$ect oriented programming', 'baz' => array(1, 2, 3, 4, 5, array('a', array(1, 2, 3), 'b', 'x' => 'c'))); header('content-type: text/plain'); $json = new json(); $string = $json->encode($array); $converted = $json->decode($string); print_r($converted); }
function json_decode($json_value, $bool = false) { $json = new json(); return $json->decode($json_value, $bool); }
public function api_devicescanresults() { //$old_scan_data = json::decode($this->token->get('device_data')); $scan_data = json::decode($this->args('scan_data')); //var_dump($scan_data); if (!empty($_FILES)) { // We currently don't want to delete the old data // //delete any old files if we have them. // if (!empty($old_scan_data->camera_files)) { // foreach ($old_scan_data->camera_files AS $id) { // $data_file = Storage::get($id); // $data_file->delete(); // } // } foreach ($_FILES as $file) { if (is_uploaded_file($file['tmp_name'])) { $filename = $file['name']; $filename = str_replace(" ", "_", $filename); $filename = preg_replace("/[^-_.[0-9a-zA-Z]/", "", $filename); $this->ensureGoodFile($file); //okay, we're good.. do it. $data_file = Storage::newFile(); $data_file->set('user_id', User::$me->id); $data_file->upload($file['tmp_name'], StorageInterface::getNiceDir($filename)); $scan_data->camera_files[] = $data_file->id; } } } //var_dump($scan_data); //var_dump($_FILES); $this->token->set('device_data', json::encode($scan_data)); $this->token->set('last_seen', date('Y-m-d H:i:s')); $this->token->save(); return True; }
/** * FUSIONCHAT GANTT PLAN ACTUAL * Status : Fixed, Dept. * ========== BACA ================ * UPDATE * Locate : Tab View Pilot Project. * 1. update Source : chart,categories * @since 1.1 * author piter novian [ptr.nov@gmail.com]. */ public function chartGanttPlanActual() { //***kategory Month $monthCtg = new ActiveDataProvider(['query' => Cnfmonth::find()->asArray(), 'pagination' => ['pageSize' => 24]]); //***kategory Week $weekCtg = new ActiveDataProvider(['query' => Cnfweek::find()->asArray(), 'pagination' => ['pageSize' => 200]]); //***get Data Pilotproject $_modalPilot = new ActiveDataProvider(['query' => Pilotproject::find()->Where(['CREATED_BY' => Yii::$app->user->identity->username])->orderBy('PLAN_DATE1')->asArray(), 'pagination' => ['pageSize' => 200]]); //***Task foreach ($_modalPilot->getModels() as $row => $value) { $taskCtg[] = ['label' => $value['PILOT_NM'], 'id' => strval($value['ID'])]; $taskPIC[] = ['label' => $value['CREATED_BY']]; } //***get plan actual pilot project $_modalActualPlan = new ArrayDataProvider(['allModels' => Yii::$app->db_widget->createCommand("\n\t\t\t\t\tSELECT *,x1.ID as IDX\n\t\t\t\t\tFROM sc0001 x1 RIGHT JOIN sc0001b x2 on x1.ENABLE_ACTUAL=x2.ENABLE_ACTUAL \n\t\t\t\t\tWHERE x2.ENABLE_ACTUAL=2 AND x1.CREATED_BY='" . Yii::$app->user->identity->username . "';\t\t\t\t\t\n\t\t\t")->queryAll(), 'pagination' => ['pageSize' => 400]]); $aryPlanActual = ArrayHelper::toArray($_modalActualPlan->getModels()); //***Task foreach ($aryPlanActual as $row => $value) { if ($value['ENABLE_NM'] == 'PLAN') { $task[] = ["label" => "Planned", "processid" => strval($value['IDX']), "start" => Yii::$app->formatter->asDatetime($value['PLAN_DATE1'], 'php:Y-m-d'), "end" => Yii::$app->formatter->asDatetime($value['PLAN_DATE2'], 'php:Y-m-d'), "id" => strval($value['IDX']) . "-1", "color" => "#008ee4", "height" => "32%", "toppadding" => "12%"]; } elseif ($value['ENABLE_NM'] == 'ACTUAL') { $task[] = ["label" => "Actual", "processid" => strval($value['IDX']), "start" => Yii::$app->formatter->asDatetime($value['ACTUAL_DATE1'], 'php:Y-m-d'), "end" => Yii::$app->formatter->asDatetime($value['ACTUAL_DATE2'], 'php:Y-m-d'), "id" => strval($value['IDX']), "color" => "#6baa01", "toppadding" => "56%", "height" => "32%"]; } } // print_r($task); // die(); $cntTask = sizeof($taskCtg); $maxRow = $cntTask <= 26 ? 26 - $cntTask : $cntTask; /* if($cntTask==0){ $maxRow=29; }elseif($cntTask<=29){ $maxRow=29-$cntTask; }else{ $maxRow=$cntTask; } */ for ($x = 0; $x <= $maxRow; $x++) { $taskCtgKosong[] = ['label' => '', 'id' => '']; } $mrgTaskCtg = ArrayHelper::merge($taskCtg, $taskCtgKosong); for ($x = 0; $x <= $maxRow; $x++) { $taskPICKosong[] = ['label' => '']; } $mrgtaskPIC = ArrayHelper::merge($taskPIC, $taskPICKosong); $rslt = '{ "chart": { "subcaption": "Pilot Project Planned vs Actual", "dateformat": "yyyy-mm-dd", "outputdateformat": "ddds mns yy", "ganttwidthpercent": "70", "ganttPaneDuration": "50", "ganttPaneDurationUnit": "d", "flatScrollBars": "0", "fontsize": "14", "exportEnabled": "1", "plottooltext": "$processName{br} $label starting date $start{br}$label ending date $end", "theme": "fint" }, "categories": [ { "bgcolor": "#33bdda", "align": "middle", "fontcolor": "#ffffff", "fontsize": "12", "category": ' . Json::encode($monthCtg->getModels()) . ' }, { "bgcolor": "#ffffff", "fontcolor": "#1288dd", "fontsize": "11", "isbold": "1", "align": "center", "category": ' . Json::encode($weekCtg->getModels()) . ' } ], "processes": { "headertext": "Pilot Task", "fontcolor": "#000000", "fontsize": "10", "isanimated": "1", "bgcolor": "#6baa01", "headervalign": "middle", "headeralign": "center", "headerbgcolor": "#6baa01", "headerfontcolor": "#ffffff", "headerfontsize": "12", "width":"200", "align": "left", "isbold": "1", "bgalpha": "25", "process": ' . Json::encode($mrgTaskCtg) . ' }, "datatable": { "headervalign": "bottom", "datacolumn": [ { "headertext": "PIC", "fontcolor": "#000000", "fontsize": "10", "isanimated": "1", "bgcolor": "#6baa01", "headervalign": "middle", "headeralign": "center", "headerbgcolor": "#6baa01", "headerfontcolor": "#ffffff", "headerfontsize": "12", "width":"100", "align": "left", "isbold": "1", "bgalpha": "25", "text": ' . Json::encode($mrgtaskPIC) . ' } ] }, "tasks": { "task":' . Json::encode($task) . ' } }'; return json::decode($rslt); }
function sync($chunkSize = 5, $verbose = 1) { // we pull data from this server global $CONF_server_id, $CONF_tmp_path; global $DBGlvl; $this->getFromDB(); // we need to take care for protocol version 2, // in v21 the StartID is the last TM in UTC , we need to start again from the last TM // in case 2 or more actions were preformed on the same second and we only // proccessed them partially // Problem: the last transaction gets pulled again and again !!! // we need to detect if the same transaction ID has been proccessed // at least 2 times, then we can move to the next ID without fear of loosing // transactions made in the same second. // we have enforced RULE #1 on the other server running protocol v2 // RULE #1 // we ensure that no transactions of the same second are split into 2 log batches // thats why we get 100 more entries and stop manually // so the following is not needed nay more , we always start +1 /* if ( $this->getProtocolVersion() == 2 ) $startID=$this->lastPullUpdateID; else // old version $startID=$this->lastPullUpdateID+1; */ $startID = $this->lastPullUpdateID + 1; if ($this->data['isLeo']) { $urlToPull = 'http://' . $this->data['url_base'] . '/sync.php?type=1&version=' . $this->getProtocolVersion(); $urlToPull .= "&c={$chunkSize}&startID={$startID}&format=" . $this->data['sync_format']; $urlToPull .= "&clientID={$CONF_server_id}&clientPass="******"&sync_type=" . $this->data['sync_type'] . "&use_zip=" . $this->data['use_zip']; } else { $urlToPull = 'http://' . $this->data['url_sync'] . "count={$chunkSize}&startID={$startID}"; } if ($verbose) { echo "Getting <strong>" . $this->data['sync_format'] . "</strong> sync-log from {$urlToPull} ... "; } if ($verbose) { flush2Browser(); } if ($verbose) { flush2Browser(); } $timeout = 60 + floor($chunkSize / 5); if ($this->data['sync_type'] & SYNC_INSERT_FLIGHT_LOCAL && $this->data['use_zip']) { $timeout *= 5; } $rssStr = fetchURL($urlToPull, $timeout); if (!$rssStr) { echo "<div class='error'>Cannot get data from server</div><BR>"; return array(-1, "Cannot get data from {$urlToPull}"); } if ($verbose) { echo " <div class='ok'>DONE</div><br>"; } if ($verbose) { flush2Browser(); } if ($this->data['use_zip']) { // we have a zip file in $rssStr, unzip it if ($verbose) { echo "Unziping sync-log ... "; } $tmpZIPfolder = $CONF_tmp_path . '/' . $this->ID . "_" . time(); makeDir($tmpZIPfolder); $zipFile = "{$tmpZIPfolder}/sync_log.zip"; writeFile($zipFile, $rssStr); require_once dirname(__FILE__) . "/lib/pclzip/pclzip.lib.php"; $archive = new PclZip($zipFile); $list = $archive->extract(PCLZIP_OPT_PATH, $tmpZIPfolder, PCLZIP_OPT_REMOVE_ALL_PATH, PCLZIP_OPT_BY_PREG, "/(\\.igc)|(\\.olc)|(\\.txt)\$/i"); if ($list) { if ($verbose) { echo " <div class='ok'>DONE</div><br>"; } echo "<br><b>List of uploaded igc/olc/txt files</b><BR>"; $f_num = 1; foreach ($list as $fileInZip) { echo "{$f_num}) " . $fileInZip['stored_filename'] . ' (' . floor($fileInZip['size'] / 1024) . 'Kb)<br>'; $f_num++; } if ($verbose) { flush2Browser(); } if (is_file($tmpZIPfolder . '/sync.txt')) { $rssStr = implode('', file($tmpZIPfolder . '/sync.txt')); } else { echo "Could not find sync.txt. <div class='error'>Aborting</div>"; delDir($tmpZIPfolder); return array(-2, "Could not find sync.txt"); } //delDir($tmpZIPfolder); //exit; } else { echo " <div class='error'>This is not a zip file (" . $archive->errorInfo() . ")</div><br>"; } } // // getIGC // zip // for debugging json // writeFile(dirname(__FILE__).'/sync.txt',$rssStr); //return; // echo "<PRE>$rssStr</pre>"; if ($this->data['sync_format'] == 'XML') { require_once dirname(__FILE__) . '/lib/miniXML/minixml.inc.php'; $xmlDoc = new MiniXMLDoc(); $xmlDoc->fromString($rssStr); $xmlArray = $xmlDoc->toArray(); //echo "<PRE>"; //print_r($xmlArray); //echo "</PRE>"; if ($xmlArray['log']['item']['_num']) { foreach ($xmlArray['log']['item'] as $i => $logItem) { if (!is_numeric($i)) { continue; } if (!$this->processSyncEntry($this->ID, $logItem)) { // if we got an error break the loop, the admin must solve the error break; } } } else { $this->processSyncEntry($this->ID, $xmlArray['log']['item']); } } else { if ($this->data['sync_format'] == 'JSON') { if ($verbose) { echo "Decoding log from JSON format ..."; } if ($verbose) { flush2Browser(); } require_once dirname(__FILE__) . '/lib/json/CL_json.php'; // is this needed ? // $rssStr=str_replace('\\\\"','\"',$rssStr); // for testing emply log // $rssStr='{ "log": [ ] }'; // for testing bad log // $rssStr='{ "log": [ }'; $arr = json::decode($rssStr); if ($verbose) { echo " <div class='ok'>DONE</div><br>"; } if ($verbose) { flush2Browser(); } if ($DBGlvl > 0) { echo "<PRE>"; print_r($arr); echo "</PRE>"; } //exit; $entriesNum = 0; $entriesNumOK = 0; if (count($arr['log'])) { if ($verbose) { echo "Log Entries: <div class='ok'>" . count($arr['log']) . "</div><br>"; } if ($verbose) { flush2Browser(); } foreach ($arr['log'] as $i => $logItem) { if (!is_numeric($i)) { continue; } echo $entriesNum + 1 . " / {$chunkSize} "; // add path of temp folder into array $logItem['item']['tmpDir'] = $tmpZIPfolder; $entryResult = $this->processSyncEntry($this->ID, $logItem['item'], $verbose); if ($entryResult <= -128) { // if we got an error break the loop, the admin must solve the error echo "<div class'error'>Got fatal Error, will exit</div>"; $errorInProccess = 1; break; } if ($entryResult > 0) { $entriesNumOK++; } $entriesNum++; } } else { if (is_array($arr['log'])) { // no log entries to proccess delDir($tmpZIPfolder); echo "No new log entries to proccess<br />"; return array(0, 0); } if ($verbose) { echo "Sync-log format error:<br />"; print_r($arr); echo "<hr><pre>{$rssStr}</pre>"; } else { echo "Sync-log format error:<br><pre>{$rssStr}</pre><br>"; } delDir($tmpZIPfolder); return array(-4, "Sync-log format error: <pre>{$rssStr}</pre>"); } } } if ($verbose || $entriesNum > 0) { echo "<div class='ok'>Sync-log replication finished</div><br>"; echo "Proccessed {$entriesNum} log entries ({$entriesNumOK} inserted OK) out of {$chunkSize}<br>"; } // clean up delDir($tmpZIPfolder); if ($errorInProccess) { return array(-3, $entriesNum); } else { return array(1, $entriesNum); } }