PHP json_decode Examples

PHP json_decode - 30 examples found. These are the top rated real world PHP examples of json_decode extracted from open source projects. You can rate examples to help us improve the quality of examples.
Example #1
0
 public static function updateObjectsFromWriteResponse($objectsArray, $response)
 {
     $data = json_decode($response->getRawBody(), true);
     if ($response->getStatus() == 200) {
         $newLastModifiedVersion = $response->getHeader("Last-Modified-Version");
         if (isset($data['success'])) {
             foreach ($data['success'] as $ind => $key) {
                 $i = intval($ind);
                 $object = $objectsArray[$i];
                 $objectKey = $object->get('key');
                 if ($objectKey != '' && $objectKey != $key) {
                     throw new Exception("Item key mismatch in multi-write request");
                 }
                 if ($objectKey == '') {
                     $object->set('key', $key);
                 }
                 $object->set('version', $newLastModifiedVersion);
                 $object->synced = true;
                 $object->writeFailure = false;
             }
         }
         if (isset($data['failed'])) {
             foreach ($data['failed'] as $ind => $val) {
                 $i = intval($ind);
                 $object = $objectsArray[$i];
                 $object->writeFailure = $val;
             }
         }
     } elseif ($response->getStatus() == 204) {
         $objectsArray[0]->synced = true;
     }
 }
 private function xmlToArray($data)
 {
     $data = simplexml_load_string($data);
     $data = json_encode($data);
     $data = json_decode($data, true);
     return $data;
 }
Example #3
0
 /**
  * @param bool|true $assoc
  * @return array
  */
 public function load($assoc = true)
 {
     if (!isset(static::$cache[$this->file])) {
         static::$cache[$this->file] = json_decode($this->loadFile(), $assoc);
     }
     return static::$cache[$this->file];
 }
 private function sync()
 {
     if ($this->synchronized) {
         return;
     }
     /** @var ResponseInterface $clientResponse */
     $clientResponse = $this->promise->wait();
     if (200 !== $clientResponse->getStatusCode()) {
         throw new RemoteCallFailedException();
     }
     $data = (string) $clientResponse->getBody();
     // Null (empty response) is expected if only notifications were sent
     $rawResponses = [];
     if ('' !== $data) {
         $rawResponses = json_decode($data, false);
         if (json_last_error() !== JSON_ERROR_NONE) {
             throw ResponseParseException::notAJsonResponse();
         }
     }
     if (!is_array($rawResponses) && $rawResponses instanceof \stdClass) {
         $rawResponses = [$rawResponses];
     }
     $this->responses = [];
     foreach ($rawResponses as $rawResponse) {
         try {
             $response = new SyncResponse($rawResponse);
         } catch (ResponseParseException $exception) {
             //todo: logging??? (@scaytrase)
             continue;
         }
         $this->responses[$response->getId()] = $response;
     }
     $this->synchronized = true;
 }
 private function inflate()
 {
     $this->name = $this->raw['activityTaskScheduledEventAttributes']['activityType']['name'];
     $this->version = $this->raw['activityTaskScheduledEventAttributes']['activityType']['version'];
     $this->control = $this->raw['activityTaskScheduledEventAttributes']['control'];
     $this->inputs = json_decode(base64_decode($this->raw['activityTaskScheduledEventAttributes']['input']), true);
 }
Example #6
0
 public function entries()
 {
     $collection = $this->param("collection", null);
     $entries = [];
     if ($collection) {
         $col = "collection" . $collection["_id"];
         $options = [];
         if ($collection["sortfield"] && $collection["sortorder"]) {
             $options["sort"] = [];
             $options["sort"][$collection["sortfield"]] = $collection["sortorder"];
         }
         if ($filter = $this->param("filter", null)) {
             $options["filter"] = is_string($filter) ? json_decode($filter, true) : $filter;
         }
         if ($limit = $this->param("limit", null)) {
             $options["limit"] = $limit;
         }
         if ($sort = $this->param("sort", null)) {
             $options["sort"] = $sort;
         }
         if ($skip = $this->param("skip", null)) {
             $options["skip"] = $skip;
         }
         $entries = $this->app->db->find("collections/{$col}", $options);
     }
     return json_encode($entries->toArray());
 }
Example #7
0
 /**
  * @param $list
  * @param array $ph
  * @return string
  */
 public function renderJS($list, $ph = array())
 {
     $js = '';
     $scripts = MODX_BASE_PATH . $list;
     if ($this->fs->checkFile($scripts)) {
         $scripts = @file_get_contents($scripts);
         $scripts = $this->DLTemplate->parseChunk('@CODE:' . $scripts, $ph);
         $scripts = json_decode($scripts, true);
         $scripts = isset($scripts['scripts']) ? $scripts['scripts'] : $scripts['styles'];
         foreach ($scripts as $name => $params) {
             if (!isset($this->modx->loadedjscripts[$name])) {
                 if ($this->fs->checkFile($params['src'])) {
                     $this->modx->loadedjscripts[$name] = array('version' => $params['version']);
                     if (end(explode('.', $params['src'])) == 'js') {
                         $js .= '<script type="text/javascript" src="' . $this->modx->config['site_url'] . $params['src'] . '"></script>';
                     } else {
                         $js .= '<link rel="stylesheet" type="text/css" href="' . $this->modx->config['site_url'] . $params['src'] . '">';
                     }
                 } else {
                     $this->modx->logEvent(0, 3, 'Cannot load ' . $params['src'], $this->customTvName);
                 }
             }
         }
     } else {
         if ($list == $this->jsListDefault) {
             $this->modx->logEvent(0, 3, "Cannot load {$this->jsListDefault} .", $this->customTvName);
         } elseif ($list == $this->cssListDefault) {
             $this->modx->logEvent(0, 3, "Cannot load {$this->cssListDefault} .", $this->customTvName);
         }
     }
     return $js;
 }
function loadApi($action)
{
    switch ($action) {
        case 'install':
            if (!isset($_COOKIE['groupid'])) {
                throw new Exception("Error Processing Request");
            }
            $url = Request::get('send_url', '');
            $send_method = Request::get('send_method', 'plugin');
            if (!isset($url[4])) {
                throw new Exception("Error Processing Request");
            }
            $path = 'contents/plugins/';
            if ($send_method == 'template') {
                $path = 'contents/themes/';
            }
            File::downloadModule($url, $path, 'yes');
            break;
        case 'load':
            $queryData = array('send_catid' => Request::get('send_catid', 0), 'is_filter' => Request::get('is_filter', 'no'), 'send_keyword' => Request::get('send_keyword', ''), 'send_page' => Request::get('send_page', 0), 'send_limitshow' => Request::get('send_limitshow', 20), 'send_method' => Request::get('send_method', 'plugin'), 'send_showtype' => Request::get('send_showtype', 'lastest'));
            $loadData = PluginStoreApi::get($queryData);
            $loadData = json_decode($loadData, true);
            if ($loadData['error'] == 'yes') {
                throw new Exception($loadData['message']);
            }
            return $loadData['data'];
            break;
        case 'loadhtml':
            $queryData = array('send_catid' => Request::get('send_catid', 0), 'is_filter' => Request::get('is_filter', 'no'), 'send_keyword' => Request::get('send_keyword', ''), 'send_page' => Request::get('send_page', 0), 'send_limitshow' => Request::get('send_limitshow', 20), 'send_method' => Request::get('send_method', 'plugin'), 'send_showtype' => Request::get('send_showtype', 'lastest'));
            $loadData = PluginStoreApi::getHTML($queryData);
            return $loadData;
            break;
    }
}
Example #9
0
 /**
  * client包格式: writeString(json_encode(array("a"='main/main',"m"=>'main', 'k1'=>'v1')));
  * server包格式:包总长+数据(json_encode)
  * @param $_data
  * @return bool
  */
 public function parse($_data)
 {
     if (!empty($this->_buffer[$this->fd])) {
         $_data = $this->_buffer . $_data;
     }
     $packData = new MessagePacker($_data);
     $packLen = $packData->readInt();
     $dataLen = \strlen($_data);
     if ($packLen > $dataLen) {
         $this->_buffer[$this->fd] = $_data;
         return false;
     } elseif ($packLen < $dataLen) {
         $this->_buffer[$this->fd] = \substr($_data, $packLen, $dataLen - $packLen);
     } else {
         if (!empty($this->_buffer[$this->fd])) {
             unset($this->_buffer[$this->fd]);
         }
     }
     $packData->resetOffset();
     $params = $packData->readString();
     $this->_params = \json_decode($params, true);
     $apn = Config::getField('project', 'ctrl_name', 'a');
     $mpn = Config::getField('project', 'method_name', 'm');
     if (isset($params[$apn])) {
         $this->_ctrl = \str_replace('/', '\\', $params[$apn]);
     }
     if (isset($params[$mpn])) {
         $this->_method = $params[$mpn];
     }
     return $this->_params;
 }
Example #10
0
 /**
  * @param string $url
  * @return array
  */
 public function oembed($url)
 {
     $embedly = new Embedly();
     $response = $embedly->oembed(['url' => $url]);
     $data = json_decode(json_encode(reset($response)), true);
     return $data;
 }
Example #11
0
function getElementsData() {
	$elements_dirname = ADMIN_BASE_PATH.'/components/elements';
	if ($elements_dir = opendir($elements_dirname)) {
		$tmpArray = array();
		while (false !== ($dir = readdir($elements_dir))) {
			if (substr($dir,0,1) != "." && is_dir($elements_dirname . '/' . $dir)) {
				$tmpKey = strtolower($dir);
				if (@file_exists($elements_dirname . '/' . $dir . '/metadata.json')) {
					$tmpValue = json_decode(@file_get_contents($elements_dirname . '/' . $dir . '/metadata.json'));
					if ($tmpValue) {
						$tmpArray["$tmpKey"] = $tmpValue;
					}
				}
			}
		}
		closedir($elements_dir);
		if (count($tmpArray)) {
			return $tmpArray;
		} else {
			return false;
		}
	} else {
		echo 'not dir';
		return false;
	}
}
function getLatandLong($addr, $region)
{
    $url = "http://maps.google.com/maps/api/geocode/json?address=" . $addr . "&region=" . $region . "&sensor=false";
    $response = file_get_contents($url);
    if ($response == false) {
        throw new Exception("Failure to obtain data");
    }
    $places = json_decode($response);
    if (!$places) {
        throw new Exception("Invalid JSON response");
    }
    if (is_array($places->results) && count($places->results)) {
        $result = $places->results[0];
        $geometry = $result->{'geometry'};
        $location = $geometry->{'location'};
        $lat = $location->{'lat'};
        $long = $location->{'lng'};
        ob_start();
        // ensures anything dumped out will be caught
        // do stuff here
        //header( "Location: $url" );
        //return $lat.",".$long;
        // clear out the output buffer
        while (ob_get_status()) {
            ob_end_clean();
        }
    } else {
        return "Unknown";
    }
}
Example #13
0
 public function saveSort($data = array())
 {
     $sort_arr = json_decode(htmlspecialchars_decode($data['sort_string']));
     foreach ($sort_arr as $key => $id) {
         $query = $this->db->query("update aa_certificates set sort='" . $key . "' where id='" . $id . "'");
     }
 }
Example #14
0
function verifyTiezi_send($uid, $tid, $pid, $water = 'StusGame Tieba Cloud Sign Plugin "verifyTiezi"', $device = 4)
{
    if (empty($uid) || empty($tid) || empty($pid)) {
        return array('status' => '1', 'msg' => '');
    }
    $ck = misc::GetCookie($pid);
    $xs = verifyTiezi_gettie($tid, $ck);
    $x = array('BDUSS' => $ck, '_client_id' => 'wappc_136' . rand_int(10) . '_' . rand_int(3), '_client_type' => $device, '_client_version' => '5.0.0', '_phone_imei' => md5(rand_int(16)), 'anonymous' => '0', 'content' => $water, 'fid' => $xs['fid'], 'kw' => $xs['word'], 'net_type' => '3', 'tbs' => $xs['tbs'], 'tid' => $tid, 'title' => '');
    $y = '';
    foreach ($x as $key => $value) {
        $y .= $key . '=' . $value;
    }
    $x['sign'] = strtoupper(md5($y . 'tiebaclient!!!'));
    $c = new wcurl('http://c.tieba.baidu.com/c/c/post/add', array('Content-Type: application/x-www-form-urlencoded'));
    /* //Note:普通的
    	$x = verifyTiezi_gettie($tid,$ck);
    	$c = new wcurl('http://tieba.baidu.com'.$x['__formurl']);
    	unset($x['__formurl']);
    	$x['co'] = $water;
    	*/
    $c->addcookie('BDUSS=' . $ck);
    $return = json_decode($c->post($x), true);
    $c->close();
    if (!empty($return['error_code']) && $return['error_code'] != '1') {
        return array('status' => $return['error_code'], 'msg' => $return['error_msg']);
    } else {
        return array('status' => '1', 'msg' => '');
    }
}
 public function put($url, $body = null)
 {
     curl_setopt($this->_ch, CURLOPT_CUSTOMREQUEST, 'PUT');
     curl_setopt($this->_ch, CURLOPT_URL, $this->_base_uri . $url);
     curl_setopt($this->_ch, CURLOPT_POSTFIELDS, json_encode($body));
     return json_decode(curl_exec($this->_ch));
 }
Example #16
0
 public static function getLiveScore($requester, $request)
 {
     $requestParams = explode(",", $request);
     $scoreAvailable = false;
     $team1 = $requestParams[0];
     $team2 = $requestParams[1];
     $matchList = file_get_contents(self::$cricInfoURL);
     $message = "Sorry, this match information is not available.";
     if ($matchList) {
         $json = json_decode($matchList, true);
         foreach ($json as $value) {
             echo $value['t1'] . '/n';
             echo $value['t2'] . '/n/n';
             if ((stripos($value['t1'], $team1) > -1 || stripos($value['t1'], $team2) > -1) && (stripos($value['t2'], $team1) > -1 || stripos($value['t2'], $team2) > -1)) {
                 $matchScoreURL = self::$cricInfoURL . '?id=' . $value['id'];
                 $matchScore = file_get_contents($matchScoreURL);
                 $matchScore = json_decode($matchScore, true);
                 $score = $matchScore['0']['de'];
                 $scoreAvailable = true;
                 MessaggingController::sendMessage($requester, $score);
             }
         }
     } else {
         $message = "Service temporarily not available, please try after some time";
     }
     if (!$scoreAvailable) {
         MessaggingController::sendMessage($requester, $message);
     }
     PubSub::publish(GenieConstants::$SERVICE_REQUEST_COMPLETE, $requester);
 }
 public function index()
 {
     $courses = LearnHub::all();
     $res = DB::table('LearnHub')->select('category')->groupBy('category')->get();
     $categories = json_decode(json_encode($res), true);
     return view('welcome', ['courses' => $courses, 'categories' => $categories]);
 }
Example #18
0
    /**
     * Test store, update and delete.
     */
    public function testStoreUpdateAndDelete()
    {
        $requestBody = <<<EOT
        {
          "data" : {
            "type" : "pricelists",
            "attributes" : {
              "company_id"   : "1",
              "name": "pricelist_1"
            }
          }
        }
EOT;
        // Create
        $response = $this->callPost(self::API_URL, $requestBody);
        $this->assertEquals(Response::HTTP_CREATED, $response->getStatusCode());
        $this->assertNotNull($obj = json_decode($response->getContent())->data);
        $this->assertNotEmpty($obj->id);
        //$this->assertNotEmpty($obj->headers->get('Location'));
        // re-read and check
        $this->assertNotNull($obj = json_decode($this->callGet(self::API_URL . $obj->id)->getContent())->data);
        $this->assertEquals('pricelist_1', $obj->attributes->name);
        // Update
        $requestBody = "{\n          \"data\" : {\n            \"type\" : \"pricelists\",\n            \"id\"   : \"{$obj->id}\",\n            \"attributes\" : {\n              \"company_id\" : \"1\",\n              \"name\" : \"pricelist_2\"\n            }\n          }\n        }";
        Log::info($requestBody);
        $response = $this->callPatch(self::API_URL . $obj->id, $requestBody);
        Log::info($response);
        $this->assertEquals(Response::HTTP_NO_CONTENT, $response->getStatusCode());
        // re-read and check
        $this->assertNotNull($obj = json_decode($this->callGet(self::API_URL . $obj->id)->getContent())->data);
        $this->assertEquals('pricelist_2', $obj->attributes->name);
        // Delete
        $response = $this->callDelete(self::API_URL . $obj->id);
        $this->assertEquals(Response::HTTP_NO_CONTENT, $response->getStatusCode());
    }
Example #19
0
 public function testViewBody()
 {
     // Arrange
     $r = $this->socket->get('/public/groups/324e1602-3673-4d52-93ee-eadf94cbea67.json', ["domain" => "netherlands", "limit" => 1]);
     // The call should return something
     $this->assertNotEquals($r, false);
     $r = json_decode($r, true);
     $this->checkBasics($r);
     // check if the content is ok
     $this->assertTrue(isset($r['body']['group']), 'Group should be set in the body');
     $g = $r['body']['group'];
     $this->assertFalse(empty($g), 'Group should not be empty');
     $this->assertTrue(isset($g['uuid']), 'Group uuid should not be empty');
     $this->assertTrue(isset($g['serial']), 'Group uuid should not be empty');
     $this->assertTrue(isset($g['created']), 'Group creation date should not be empty');
     $this->assertTrue(isset($g['modified']), 'Group modification should not be empty');
     $this->assertTrue(isset($g['name']), 'Group name should not be empty');
     $this->assertTrue(isset($g['mission']), 'Group mission should not be empty');
     $this->assertTrue(isset($g['description']), 'Group description should not be empty');
     $this->assertTrue(isset($g['picture']), 'Group picture should not be empty');
     $this->assertTrue(isset($g['group_type']), 'Group type should not be empty');
     $this->assertTrue(isset($g['location']), 'Group location should not be empty');
     $this->checkLocation($g['location']);
     $this->assertTrue(isset($g['tags']), 'Group tags should not be empty');
     // $this->assertTrue(isset($g['url']), 'URL should not be empty'); // GREEN-3436
 }
Example #20
0
 public function get($language)
 {
     if (!$this->languages instanceof stdClass && !is_array($this->languages)) {
         $this->languages = json_decode($this->languages);
     }
     return !empty($this->languages->{$language->code}) ? $this->languages->{$language->code} : '';
 }
 /**
  * Config
  */
 public function __construct()
 {
     $posts = json_decode(file_get_contents(dirname(__FILE__) . '/posts.json'), true);
     foreach ($posts as $key => $post) {
         $this->posts[$key] = (object) $post;
     }
 }
 /**
  * 文档保存成功后执行行为
  * @param  array  $data     文档数据
  * @param  array  $catecory 分类数据
  */
 public function documentSaveComplete($param)
 {
     if (MODULE_NAME == 'Home') {
         list($data, $category) = $param;
         /* 附件默认配置项 */
         $default = C('ATTACHMENT_DEFAULT');
         /* 合并当前配置 */
         $config = $category['extend']['attachment'];
         $config = empty($config) ? $default : array_merge($default, $config);
         $attach = I('post.attachment');
         /* 该分类不允许上传附件 */
         if (!$config['is_upload'] || !in_array($attach['type'], str2arr($config['allow_type']))) {
             return;
         }
         switch ($attach['type']) {
             case 1:
                 //外链
                 # code...
                 break;
             case 2:
                 //文件
                 $info = json_decode(think_decrypt($attach['info']), true);
                 if (!empty($info)) {
                     $Attachment = D('Addons://Attachment/Attachment');
                     $Attachment->saveFile($info['name'], $info, $data['id']);
                 } else {
                     return;
                     //TODO:非法附件上传,可记录日志
                 }
                 break;
         }
     }
 }
 public function testGetImage()
 {
     $client = static::makeClient(true);
     $file = __DIR__ . "/Fixtures/files/uploadtest.png";
     $originalFilename = 'uploadtest.png';
     $mimeType = "image/png";
     $image = new UploadedFile($file, $originalFilename, $mimeType, filesize($file));
     $client->request('POST', '/api/temp_images/upload', array(), array('userfile' => $image));
     $response = json_decode($client->getResponse()->getContent());
     $property = "@id";
     $imageId = $response->image->{$property};
     $uri = $imageId . "/getImage";
     $client->request('GET', $uri);
     $this->assertEquals("image/png", $client->getResponse()->headers->get("Content-Type"));
     $imageSize = getimagesizefromstring($client->getResponse()->getContent());
     $this->assertEquals(51, $imageSize[0]);
     $this->assertEquals(23, $imageSize[1]);
     $iriConverter = $this->getContainer()->get("api.iri_converter");
     $image = $iriConverter->getItemFromIri($imageId);
     /**
      * @var $image TempImage
      */
     $this->getContainer()->get("partkeepr_image_service")->delete($image);
     $client->request('GET', $uri);
     $this->assertEquals(404, $client->getResponse()->getStatusCode());
 }
Example #24
0
 /**
  * Execute API Call
  *
  * @param   string $apiCall    API Call
  * @param   string $method     Http Method
  * @param   array  $parameters API call parameters
  *
  * @return array
  */
 public static function makeApiCall($apiCall, $method = 'GET', $parameters = array())
 {
     self::getHttp();
     $apiEndpoint = NenoSettings::get('api_server_url');
     $licenseCode = NenoSettings::get('license_code');
     $response = null;
     $responseStatus = false;
     if (!empty($apiEndpoint) && !empty($licenseCode)) {
         $method = strtolower($method);
         if (method_exists(self::$httpClient, $method)) {
             if ($method === 'get') {
                 if (!empty($parameters)) {
                     $query = implode('/', $parameters);
                     $apiCall = $apiCall . '/' . $query;
                 }
                 $apiResponse = self::$httpClient->{$method}($apiEndpoint . $apiCall, array('Authorization' => $licenseCode));
             } else {
                 $apiResponse = self::$httpClient->{$method}($apiEndpoint . $apiCall, json_encode($parameters), array('Content-Type' => 'application/json', 'Authorization' => $licenseCode));
             }
             /* @var $apiResponse JHttpResponse */
             $data = $apiResponse->body;
             if ($apiResponse->headers['Content-Type'] === 'application/json') {
                 $data = json_decode($data, true);
             }
             $response = $data;
             if ($apiResponse->code == 200) {
                 $responseStatus = true;
             }
         }
     }
     return array($responseStatus, $response);
 }
Example #25
0
 /**
  * 我的兑换 do_personal_index
  */
 public function do_personal_index()
 {
     /* 初始化变量 */
     $user_id = I('get.user_id');
     $page_num = I('get.page_num');
     $page_num = empty($page_num) || $page_num < 0 ? 1 : $page_num;
     /* 查询条件 */
     $field = 'pay_order.trade_no,pay_order.shop_coupon_info,pay_order.shop_id,pay_order.trade_state,shop.title as shop_title';
     $where['pay_order.user_id'] = array('EQ', $user_id);
     $where['pay_order.display'] = array('EQ', 1);
     $order = 'pay_order.id desc';
     /* 查询数据 */
     $list = $this->alias('pay_order')->field($field)->where($where)->join('LEFT JOIN __SHOP__ shop on pay_order.shop_id = shop.id')->order($order)->limit(C('PAGE_NUM'))->page($page_num)->select();
     foreach ($list as $k => $v) {
         $shop_coupon_info = json_decode($v['shop_coupon_info'], true);
         $list[$k]['coupon_id'] = $shop_coupon_info['id'];
         $list[$k]['coupon_title'] = $shop_coupon_info['title'];
         if ($shop_coupon_info['coupon_type'] == 1) {
             $list[$k]['coupon_tag'] = strval(0);
         } else {
             $list[$k]['coupon_tag'] = $shop_coupon_info['coupon_worth'];
         }
         $list[$k]['coupon_content'] = $shop_coupon_info['content'];
         unset($list[$k]['shop_coupon_info']);
         /* 过滤数据 */
         if (!empty($v['coupon_title'])) {
             $list[$k]['coupon_title'] = htmlspecialchars_decode($v['coupon_title']);
         }
     }
     /* 读取json */
     $list = empty($list) ? array() : $list;
     $jsonInfo['list'] = arr_content_replace($list);
     return $jsonInfo;
 }
Example #26
0
 public function createDefaultGroup()
 {
     $defaultgroups = json_decode(MONITIS_ADMIN_CONTACT_GROUPS, true);
     $existedGroups = MonitisApi::getContactGroupList();
     // existed monitis groups
     foreach ($defaultgroups as $mType => $groupName) {
         $group = MonitisHelper::in_array($existedGroups, 'id', MonitisConf::$settings['groups'][$mType]['groupId']);
         $alerts = json_decode(MONITIS_NOTIFICATION_RULE, true);
         if ($mType == 'internal') {
             $alerts['minFailedLocationCount'] = null;
         }
         $groupId = $group['id'] ? $group['id'] : 0;
         $notifByTypeGroup = MonitisApiHelper::getNotificationRuleByType($mType, $groupId);
         $alertRulesDefault = $notifByTypeGroup ? $notifByTypeGroup : $alerts;
         if ($group) {
             MonitisConf::$settings['groups'][$mType]['groupId'] = $group['id'];
             MonitisConf::$settings['groups'][$mType]['groupName'] = $group['name'];
             MonitisConf::$settings['groups'][$mType]['alert'] = $alertRulesDefault;
         } else {
             $newGroupName = $groupName;
             $resp = MonitisApi::addContactGroup(1, $newGroupName);
             if ($resp['status'] == 'ok') {
                 MonitisConf::$settings['groups'][$mType]['groupId'] = $resp['data'];
                 MonitisConf::$settings['groups'][$mType]['groupName'] = $newGroupName;
                 MonitisConf::$settings['groups'][$mType]['alert'] = $alertRulesDefault;
             } else {
                 // error
                 return array('status' => 'error', 'msg' => 'Add contact group error ' . $resp['error']);
             }
         }
         // $r = $this->addContacts(ucfirst($mType), MonitisConf::$settings['groups'][$mType]['groupId']);
     }
     MonitisConf::update_settings(json_encode(MonitisConf::$settings));
     return array('status' => 'ok', 'msg' => 'External, internal groups sets success');
 }
 /**
  * Method to get an array of rock artists from last.fm
  */
 public static function get_lastfm_rock_stations()
 {
     $api_key = config('app.api_key_lastfm');
     $client = new \GuzzleHttp\Client();
     $res = $client->get('http://ws.audioscrobbler.com/2.0', ['query' => ['method' => 'tag.getTopArtists', 'tag' => 'rock', 'format' => 'json', 'limit' => 5, 'api_key' => $api_key]]);
     if ($res->getStatusCode() != 200) {
         return false;
     }
     $stations = json_decode((string) $res->getBody(), true);
     if ($stations == NULL) {
         return false;
     }
     $rock_stations = array();
     if ($stations != NULL && isset($stations['topartists']['artist'])) {
         foreach ($stations['topartists']['artist'] as $rock_station) {
             $obj = new \stdClass();
             $obj->id = md5($rock_station['mbid']);
             if (isset($rock_station['name'])) {
                 $obj->name = $rock_station['name'];
             }
             if (isset($rock_station['image'][2]['#text'])) {
                 $obj->thumb_url = $rock_station['image'][2]['#text'];
             }
             if (isset($rock_station['url'])) {
                 $obj->website = $rock_station['url'];
             }
             $rock_stations[md5($rock_station['mbid'])] = $obj;
         }
     }
     return $rock_stations;
 }
Example #28
0
 public function getUserInfo()
 {
     $url = 'https://api.github.com/user?' . http_build_query(array('access_token' => $this->token->access_token));
     // Create a curl handle to a non-existing location
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     //Set curl to return the data instead of printing it to the browser.
     curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
     # timeout after 10 seconds, you can increase it
     curl_setopt($ch, CURLOPT_URL, $url);
     #set the url and get string together
     curl_setopt($ch, CURLOPT_USERAGENT, 'dukt-oauth');
     #set the url and get string together
     $json = '';
     if (($json = curl_exec($ch)) === false) {
         throw new \Exception(curl_error($ch));
     }
     curl_close($ch);
     $user = json_decode($json);
     if (!isset($user->id)) {
         throw new \Exception($json);
     }
     // Create a response from the request
     return array('uid' => $user->id, 'nickname' => $user->login, 'name' => $user->name, 'email' => $user->email, 'urls' => array('GitHub' => 'http://github.com/' . $user->login, 'Blog' => $user->blog));
 }
Example #29
0
 public function get($limit = 1024)
 {
     header('Content-Type: application/json');
     $dates = json_decode(file_get_contents('hoa://Application/Database/Dates.json'), true);
     echo json_encode(array_slice($dates, 0, $limit));
     return;
 }
Example #30
0
 public static function useConfigurationFile($path)
 {
     if (is_readable($path)) {
         $config = json_decode(file_get_contents($path), true);
         self::$_cachedConfig = array_merge(self::$_cachedConfig, $config);
     }
 }