function testSearch() { $team1 = $this->objFromFixture('GridFieldTest_Team', 'team1'); $team2 = $this->objFromFixture('GridFieldTest_Team', 'team2'); $response = $this->get('GridFieldAddExistingAutocompleterTest_Controller'); $this->assertFalse($response->isError()); $parser = new CSSContentParser($response->getBody()); $btns = $parser->getBySelector('.ss-gridfield #action_gridfield_relationfind'); $response = $this->post( 'GridFieldAddExistingAutocompleterTest_Controller/Form/field/testfield/search/Team 2', array( (string)$btns[0]['name'] => 1 ) ); $this->assertFalse($response->isError()); $result = Convert::json2array($response->getBody()); $this->assertEquals(1, count($result)); $this->assertEquals(array($team2->ID => 'Team 2'), $result); $response = $this->post( 'GridFieldAddExistingAutocompleterTest_Controller/Form/field/testfield/search/Unknown', array( (string)$btns[0]['name'] => 1 ) ); $this->assertFalse($response->isError()); $result = Convert::json2array($response->getBody()); $this->assertEmpty($result, 'The output is either an empty array or boolean FALSE'); }
/** * @todo Test the results of a publication better */ public function testPublish() { $page1 = $this->objFromFixture('Page', "page1"); $page2 = $this->objFromFixture('Page', "page2"); $this->session()->inst_set('loggedInAs', $this->idFromFixture('Member', 'admin')); $response = $this->get('admin/pages/publishall?confirm=1'); $this->assertContains('Done: Published 30 pages', $response->getBody()); $actions = CMSBatchActionHandler::config()->batch_actions; // Some modules (e.g., cmsworkflow) will remove this action $actions = CMSBatchActionHandler::config()->batch_actions; if (isset($actions['publish'])) { $response = $this->get('admin/pages/batchactions/publish?ajax=1&csvIDs=' . implode(',', array($page1->ID, $page2->ID))); $responseData = Convert::json2array($response->getBody()); $this->assertArrayHasKey($page1->ID, $responseData['modified']); $this->assertArrayHasKey($page2->ID, $responseData['modified']); } // Get the latest version of the redirector page $pageID = $this->idFromFixture('RedirectorPage', 'page5'); $latestID = DB::prepared_query('select max("Version") from "RedirectorPage_versions" where "RecordID" = ?', array($pageID))->value(); $dsCount = DB::prepared_query('select count("Version") from "RedirectorPage_versions" where "RecordID" = ? and "Version"= ?', array($pageID, $latestID))->value(); $this->assertEquals(1, $dsCount, "Published page has no duplicate version records: it has " . $dsCount . " for version " . $latestID); $this->session()->clear('loggedInAs'); //$this->assertRegexp('/Done: Published 4 pages/', $response->getBody()) /* $response = Director::test("admin/pages/publishitems", array( 'ID' => '' 'Title' => '' 'action_publish' => 'Save and publish', ), $session); $this->assertRegexp('/Done: Published 4 pages/', $response->getBody()) */ }
public function Weather() { if (!$this->Location) { return false; } $rnd = time(); $url = "http://query.yahooapis.com/v1/public/yql?format=json&rnd={$rnd}&diagnostics=true&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&q="; $query = urlencode("select * from weather.forecast where location in (select id from weather.search where query=\"{$this->Location}\") and u=\"{$this->Units}\""); $response = file_get_contents($url . $query); if ($response) { $result = Convert::json2array($response); if (!$result["query"]["results"]) { return false; } $days = ArrayList::create(array()); $channel = isset($result["query"]["results"]["channel"][0]) ? $result["query"]["results"]["channel"][0] : $result["query"]["results"]["channel"]; $label = $channel["title"]; $link = $channel["link"]; $forecast = $channel["item"]["forecast"]; for ($i = 0; $i < 2; $i++) { $item = $forecast[$i]; $days->push(ArrayData::create(array('High' => $item["high"], 'Low' => $item["low"], 'ImageURL' => "http://l.yimg.com/a/i/us/we/52/" . $item["code"] . ".gif", 'Label' => $i == 0 ? _t('Dashboard.TODAY', 'Today') : _t('Dashboard.TOMORROW', 'Tomorrow')))); } $html = $this->customise(array('Location' => str_replace("Yahoo! Weather - ", "", $label), 'Link' => $link, 'Days' => $days))->renderWith('DashboardWeatherContent'); $this->WeatherHTML = $html; $this->write(); return $html; } return $this->WeatherHTML; }
public function testEnablePluginsByArrayWithPaths() { Config::inst()->update('Director', 'alternate_base_url', 'http://mysite.com/subdir'); $c = new TinyMCEConfig(); $c->setTheme('modern'); $c->setOption('language', 'es'); $c->disablePlugins('table', 'emoticons', 'paste', 'code', 'link', 'importcss'); $c->enablePlugins(array('plugin1' => 'mypath/plugin1.js', 'plugin2' => '/anotherbase/mypath/plugin2.js', 'plugin3' => 'https://www.google.com/plugin.js', 'plugin4' => null, 'plugin5' => null)); $attributes = $c->getAttributes(); $config = Convert::json2array($attributes['data-config']); $plugins = $config['external_plugins']; $this->assertNotEmpty($plugins); // Plugin specified via relative url $this->assertContains('plugin1', array_keys($plugins)); $this->assertEquals('http://mysite.com/subdir/mypath/plugin1.js', $plugins['plugin1']); // Plugin specified via root-relative url $this->assertContains('plugin2', array_keys($plugins)); $this->assertEquals('http://mysite.com/anotherbase/mypath/plugin2.js', $plugins['plugin2']); // Plugin specified with absolute url $this->assertContains('plugin3', array_keys($plugins)); $this->assertEquals('https://www.google.com/plugin.js', $plugins['plugin3']); // Plugin specified with standard location $this->assertContains('plugin4', array_keys($plugins)); $this->assertEquals('http://mysite.com/subdir/framework/thirdparty/tinymce/plugins/plugin4/plugin.min.js', $plugins['plugin4']); // Check that internal plugins are extractable separately $this->assertEquals(['plugin4', 'plugin5'], $c->getInternalPlugins()); // Test plugins included via gzip compresser Config::inst()->update('HTMLEditorField', 'use_gzip', true); $this->assertEquals('framework/thirdparty/tinymce/tiny_mce_gzip.php?js=1&plugins=plugin4,plugin5&themes=modern&languages=es&diskcache=true&src=true', $c->getScriptURL()); // If gzip is disabled only the core plugin is loaded Config::inst()->remove('HTMLEditorField', 'use_gzip'); $this->assertEquals('framework/thirdparty/tinymce/tinymce.min.js', $c->getScriptURL()); }
function recordInbound() { $strJson = file_get_contents("php://input"); try { $arrResponse = Convert::json2array($strJson); if ($savedMessage = PostmarkMessage::get()->filter('MessageID', $arrResponse['MessageID'])->first()) { return; } $hash = $arrResponse['ToFull'][0]['MailboxHash']; $hashParts = explode('+', $hash); $lastMessage = PostmarkMessage::get()->filter(array('UserHash' => $hashParts[0], 'MessageHash' => $hashParts[1]))->first(); $fromCustomer = PostmarkHelper::find_or_make_client($arrResponse['From']); $inboundSignature = null; if ($lastMessage) { $inboundSignature = $lastMessage->From(); } else { if (!$lastMessage && isset($arrResponse['To'])) { $inboundSignature = PostmarkSignature::get()->filter('Email', $arrResponse['To'])->first(); } } if (!$inboundSignature) { $inboundSignature = PostmarkSignature::get()->filter('IsDefault', 1)->first(); } $message = new PostmarkMessage(array('Subject' => $arrResponse['Subject'], 'Message' => $arrResponse['HtmlBody'], 'ToID' => 0, 'MessageID' => $arrResponse['MessageID'], 'InReplyToID' => $lastMessage ? $lastMessage->ID : 0, 'FromCustomerID' => $fromCustomer ? $fromCustomer->ID : 0, 'InboundToID' => $inboundSignature ? $inboundSignature->ID : 0)); $message->write(); if (isset($arrResponse['Attachments']) && count($arrResponse['Attachments'])) { foreach ($arrResponse['Attachments'] as $attachment) { $attachmentObject = new Attachment(array('Content' => $attachment['Content'], 'FileName' => $attachment['Name'], 'ContentType' => $attachment['ContentType'], 'Length' => $attachment['ContentLength'], 'ContentID' => $attachment['ContentID'], 'PostmarkMessageID' => $message->ID)); $attachmentObject->write(); } } } catch (Exception $e) { } return 'OK'; }
/** * @todo Test the results of a publication better */ function testPublish() { $page1 = $this->objFromFixture('Page', "page1"); $page2 = $this->objFromFixture('Page', "page2"); $this->session()->inst_set('loggedInAs', $this->idFromFixture('Member', 'admin')); $response = $this->get("admin/cms/publishall?confirm=1"); $this->assertContains(sprintf(_t('CMSMain.PUBPAGES', "Done: Published %d pages"), 30), $response->getBody()); // Some modules (e.g., cmsworkflow) will remove this action if (isset(CMSBatchActionHandler::$batch_actions['publish'])) { $response = Director::test("admin/cms/batchactions/publish", array('csvIDs' => implode(',', array($page1->ID, $page2->ID)), 'ajax' => 1), $this->session()); $responseData = Convert::json2array($response->getBody()); $this->assertTrue(property_exists($responseData['modified'], $page1->ID)); $this->assertTrue(property_exists($responseData['modified'], $page2->ID)); } // Get the latest version of the redirector page $pageID = $this->idFromFixture('RedirectorPage', 'page5'); $latestID = DB::query('select max("Version") from "RedirectorPage_versions" where "RecordID"=' . $pageID)->value(); $dsCount = DB::query('select count("Version") from "RedirectorPage_versions" where "RecordID"=' . $pageID . ' and "Version"=' . $latestID)->value(); $this->assertEquals(1, $dsCount, "Published page has no duplicate version records: it has " . $dsCount . " for version " . $latestID); $this->session()->clear('loggedInAs'); //$this->assertRegexp('/Done: Published 4 pages/', $response->getBody()) /* $response = Director::test("admin/publishitems", array( 'ID' => '' 'Title' => '' 'action_publish' => 'Save and publish', ), $session); $this->assertRegexp('/Done: Published 4 pages/', $response->getBody()) */ }
public function updateAddress() { $RestfulService = new RestfulService("https://www.odeon.co.uk/cinemas/odeon/", 315360); $Response = $RestfulService->request($this->ID); if (!$Response->isError()) { $html = HtmlDomParser::str_get_html($Response->getBody()); $cinema = $html->find('div[id="gethere"]', 0); foreach ($cinema->find('.span4') as $span4) { foreach ($span4->find('p.description') as $description) { $address = implode(', ', preg_split('/\\s+\\s+/', trim($description->plaintext))); $RestfulService = new RestfulService("http://maps.google.com/maps/api/geocode/json?address={$address}"); $RestfulService_geo = $RestfulService->request(); if (!$RestfulService_geo->isError()) { $body = Convert::json2array($RestfulService_geo->getBody()); if (isset($body['results'][0]['geometry']['location']['lat']) && isset($body['results'][0]['geometry']['location']['lng'])) { $this->Address = $address; $this->lat = $body['results'][0]['geometry']['location']['lat']; $this->lng = $body['results'][0]['geometry']['location']['lng']; $this->write(); } } } } } }
function testJSON2Array() { $val = '{"Joe":"Bloggs","Tom":"Jones","My":{"Complicated":"Structure"}}'; $decoded = Convert::json2array($val); $this->assertEquals(3, count($decoded), '3 items in the decoded array'); $this->assertContains('Bloggs', $decoded, 'Contains "Bloggs" value in decoded array'); $this->assertContains('Jones', $decoded, 'Contains "Jones" value in decoded array'); }
/** * @return string */ public function process() { if (isset($_POST['SourceURL'])) { $sourceURL = $_POST['SourceURL']; $bIsCloudinary = CloudinaryVideo::isCloudinary($sourceURL); $bIsYoutube = YoutubeVideo::is_youtube($sourceURL); $bIsVimeo = VimeoVideo::is_vimeo($sourceURL); $video = null; if ($bIsYoutube || $bIsVimeo || $bIsCloudinary) { if ($bIsCloudinary) { $filterClass = 'CloudinaryVideo'; $fileType = 'video'; } elseif ($bIsYoutube) { $filterClass = 'YoutubeVideo'; $fileType = 'youtube'; } else { $filterClass = 'VimeoVideo'; $fileType = 'vimeo'; } $funcForID = $bIsYoutube ? 'youtube_id_from_url' : 'vimeo_id_from_url'; $funcForDetails = $bIsYoutube ? 'youtube_video_details' : 'vimeo_video_details'; if ($bIsCloudinary) { $arr = Config::inst()->get('CloudinaryConfigs', 'settings'); if (isset($arr['CloudName']) && !empty($arr['CloudName'])) { $arrPieces = explode('/', $sourceURL); $arrFileName = array_slice($arrPieces, 7); $fileName = implode('/', $arrFileName); $publicID = substr($fileName, 0, strrpos($fileName, '.')); $video = $filterClass::get()->filterAny(array('URL' => $sourceURL, 'PublicID' => $publicID))->first(); if (!$video) { $api = new \Cloudinary\Api(); $resource = $api->resource($publicID, array("resource_type" => "video")); //qoogjqs9ksyez7ch8sh5 $json = json_encode($resource); $arrResource = Convert::json2array($json); $video = new $filterClass(array('Title' => $arrResource['public_id'] . '.' . $arrResource['format'], 'PublicID' => $arrResource['public_id'], 'Version' => $arrResource['version'], 'URL' => $arrResource['url'], 'SecureURL' => $arrResource['secure_url'], 'FileType' => $arrResource['resource_type'], 'FileSize' => $arrResource['bytes'], 'Format' => $arrResource['format'], 'Signature' => isset($arrResource['signature']) ? $arrResource['signature'] : '')); $video->write(); } } } else { $video = $filterClass::get()->filter('URL', $sourceURL)->first(); if (!$video) { $sourceID = $filterClass::$funcForID($sourceURL); $details = $filterClass::$funcForDetails($sourceID); $video = new $filterClass(array('Title' => $details['title'], 'Duration' => $details['duration'], 'URL' => $sourceURL, 'secure_url' => $sourceURL, 'PublicID' => $sourceID, 'FileType' => $fileType)); $video->write(); } } if ($video) { $this->value = $iVideoID = $video->ID; $file = $this->customiseCloudinaryFile($video); return Convert::array2json(array('colorselect_url' => $file->UploadFieldImageURL, 'thumbnail_url' => $file->UploadFieldThumbnailURL, 'fieldname' => $this->getName(), 'id' => $file->ID, 'url' => $file->URL, 'buttons' => $file->UploadFieldFileButtons, 'more_files' => $this->canUploadMany(), 'field_id' => $this->ID())); } } } return Convert::array2json(array()); }
/** * Handles responses from the MailChimp API. * * @param MailChimp $mailChimp * @return Array */ public function handleMailChimpResponse($mailChimp) { $response = $mailChimp->getLastResponse(); if (!$mailChimp->success()) { $message = $response && array_key_exists($response['errors']) ? $response['errors'][0]['message'] : 'Error connecting to MailChimp API'; user_error($message, E_USER_ERROR); } return Convert::json2array($response['body']); }
/** * @covers EventInvitationField::loadfromtime() */ public function testLoadFromDatetime() { $request = new SS_HTTPRequest('GET', null, array('PastTimeID' => $this->idFromFixture('Group', 'group'))); $field = new EventInvitationField(new RegistrableEvent(), 'Invitations'); $response = $field->loadfromtime($request); $data = Convert::json2array($response->getBody()); $expect = array((object) array('name' => 'First Registration', 'email' => '*****@*****.**'), (object) array('name' => 'Second Registration', 'email' => '*****@*****.**')); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals($expect, $data); }
/** * Removes a presentation from the user's random list * @param int $id The presentation ID */ public function removePresentation($id) { if (!$this->owner->PresentationList) { return; } $ids = Convert::json2array($this->owner->PresentationList); unset($ids[$id]); $this->owner->PresentationList = Convert::array2json($ids); $this->owner->write(); }
/** * */ public function run() { SapphireTransactionManager::getInstance()->transaction(function () { $pageToken = null; while (true) { if ($this->videosUpdated >= SummitVideoApp::config()->popular_video_limit) { break; } // Prevent an infinite loop if the YouTube service is acting strange if ($this->sanityCheck === 5) { $e = new Exeception('Task has run too many times. Seems to be an infinite loop. Could be something wrong with the YouTube service?'); SS_Log::log($e, SS_Log::ERR); throw $e; } try { $response = $this->api->getPopularVideos($pageToken); } catch (\Exception $e) { SS_Log::log("YouTube Search failed" . $e->getMessage(), SS_Log::ERR); } $this->sanityCheck++; $body = $response->getBody()->getContents(); $data = Convert::json2array($body); $nextPageToken = @$data['nextPageToken']; $ids = []; foreach ($data['items'] as $item) { if ($item['id']['kind'] === 'youtube#video') { $ids[] = $item['id']['videoId']; } } try { $response = $this->api->getVideoStatsById($ids); } catch (\Exception $e) { SS_Log::log("YouTube video stats failed" . $e->getMessage(), SS_Log::ERR); } $body = $response->getBody()->getContents(); $data = Convert::json2array($body); foreach ($data['items'] as $v) { $video = PresentationVideo::get()->filter(['YouTubeID' => $v['id']])->first(); if ($video) { $video->Views = $v['statistics']['viewCount']; $video->write(); $this->videosUpdated++; } } // If there are no more pages, then bail if ($nextPageToken === $pageToken) { break; } $pageToken = $nextPageToken; } echo "{$this->videosUpdated} videos updated.\n"; }); }
protected function callRestfulService($endpoint, $query = array()) { $req = $this->restfulService; $req->httpHeader("Accept-Charset: utf-8"); $query['api_key'] = $this->apiKey; $query['format'] = $this->format; $req->setQueryString($query); $response = $req->request($endpoint); if (!$response) { return false; } return Convert::json2array($response->getBody(), true); }
public function getLocation($ip, $ipNumber) { $api = Config::inst()->get('DBIP_IpParser', 'api'); $url = "http://api.db-ip.com/v2/{$api}/{$ip}"; try { $json = file_get_contents($url); $data = Convert::json2array($json); $location = new ArrayData(array('Country' => $data['countryCode'], 'Region' => $data['stateProv'], 'City' => $data['city'], 'Type' => ContinentalContentUtils::IPType($ip))); $this->debugLocation($location); return $location; } catch (Exception $e) { } }
/** * */ public function run() { SapphireTransactionManager::getInstance()->transaction(function () { $unprocessedVideos = PresentationVideo::get()->filter(['Processed' => false])->limit(50); if (!$unprocessedVideos->exists()) { return; } $summit = Summit::get_active(); $dateUTC = $summit->convertDateFromTimeZone2UTC(SS_DateTime::now()->Rfc2822()); $dateUTCTimestamp = strtotime($dateUTC); $maxAge = SummitVideoApp::config()->abandon_unprocessed_videos_after; $ids = []; foreach ($unprocessedVideos as $video) { $age = $dateUTCTimestamp - strtotime($video->DateUploaded); if ($age > $maxAge) { SS_Log::log("Video {$video->Title} has been unprocessed for a long time. ({$age} seconds). It should be deleted.", SS_Log::WARN); continue; } $ids[] = $video->YouTubeID; } try { $response = $this->api->getVideoStatusById($ids); } catch (\Exception $e) { SS_Log::log("YouTube check for status failed" . $e->getMessage(), SS_Log::ERR); return; } $body = $response->getBody()->getContents(); $data = Convert::json2array($body); $items = $data['items']; if (empty($items)) { echo "No videos are marked as processing. Exiting.\n"; return; } foreach ($items as $item) { $currentStatus = $item['status']['uploadStatus']; if ($currentStatus == 'processed') { $video = PresentationVideo::get()->filter(['YouTubeID' => $item['id']])->first(); if (!$video) { SS_Log::log("Tried to update processing status for " . $item['id'] . " but no PresentationVideo with that YouTubeID was found.", SS_Log::WARN); continue; } $video->Processed = true; $video->write(); $this->videosUpdated++; } } echo "{$this->videosUpdated} videos updated.\n"; }); }
/** * Wrapper method to configure the RestfulService, make the call, and handle errors * @param string $url * @param array $params * @param string $method * @return array JSON */ protected function callRestfulService($url, $params = [], $method = 'GET') { $this->restfulService->setQueryString($params); $response = $this->restfulService->request($url, $method, $params); if (!$response) { SS_Log::log('No response from workable API endpoint ' . $url, SS_Log::WARN); return false; } else { if ($response->getStatusCode() !== 200) { SS_Log::log("Received non-200 status code {$response->getStatusCode()} from workable API", SS_Log::WARN); return false; } } return Convert::json2array($response->getBody()); }
/** * Upload the given file, and import or start preview. * @param SS_HTTPRequest $request * @return string */ public function upload(SS_HTTPRequest $request) { $field = $this->getUploadField(); $uploadResponse = $field->upload($request); //decode response body. ugly hack ;o $body = Convert::json2array($uploadResponse->getBody()); $body = array_shift($body); //add extra data $body['import_url'] = Controller::join_links($this->Link('preview'), $body['id'], "?BackURL=" . $this->getBackURL($request)); //don't return buttons at all unset($body['buttons']); //re-encode $response = new SS_HTTPResponse(Convert::raw2json(array($body))); return $response; }
public function write() { $writableData = array_intersect_key($this->record, $this->db()); $id = $this->getID(); if ($id) { $result = self::service()->request('/RestDataObject/' . $id, 'PUT', Convert::array2json($writableData)); if ($result->getStatusCode() == 200) { } } else { $result = self::service()->request('/RestDataObject/', 'POST', Convert::array2json($writableData)); if ($result->getStatusCode() == 201) { $data = Convert::json2array($result->getBody()); $this->record['ID'] = $data["ID"]; $this->getID(); } } return $this->ID; }
public function getEvents($calendarId = '*****@*****.**', $options = array()) { $detaults = array('key' => $_ENV['GOOGLE_API_KEY'], 'maxResults' => 1000, 'singleEvents' => 'true', 'orderBy' => 'startTime', 'timeMax' => date(DateTime::RFC3339, strtotime('+90 days')), 'timeMin' => date(DateTime::RFC3339, strtotime('-1 day')), 'pageToken' => null); $query = array_merge($detaults, $options); // Remove null values foreach ($query as $key => $value) { if ($value === null) { unset($query[$key]); } } $url = self::BASE_URL . "{$calendarId}/events"; $service = new RestfulService($url, 60); $service->checkErrors = false; $service->setQueryString($query); $res = $service->request(); $data = Convert::json2array($res->getBody()); return $data; }
public function testEnablePluginsByArrayWithPaths() { Config::inst()->update('Director', 'alternate_base_url', 'http://mysite.com/subdir'); $c = new TinyMCEConfig(); $c->enablePlugins(array('plugin1' => 'mypath/plugin1.js', 'plugin2' => '/anotherbase/mypath/plugin2.js', 'plugin3' => 'https://www.google.com/plugin.js', 'plugin4' => null)); $attributes = $c->getAttributes(); $config = Convert::json2array($attributes['data-config']); $plugins = $config['external_plugins']; $this->assertNotEmpty($plugins); // Plugin specified via relative url $this->assertContains('plugin1', array_keys($plugins)); $this->assertEquals('http://mysite.com/subdir/mypath/plugin1.js', $plugins['plugin1']); // Plugin specified via root-relative url $this->assertContains('plugin2', array_keys($plugins)); $this->assertEquals('http://mysite.com/anotherbase/mypath/plugin2.js', $plugins['plugin2']); // Plugin specified with absolute url $this->assertContains('plugin3', array_keys($plugins)); $this->assertEquals('https://www.google.com/plugin.js', $plugins['plugin3']); // Plugin specified with standard location $this->assertContains('plugin4', array_keys($plugins)); $this->assertEquals('http://mysite.com/subdir/framework/thirdparty/tinymce/plugins/plugin4/plugin.min.js', $plugins['plugin4']); }
function testSearch() { $team1 = $this->objFromFixture('GridFieldTest_Team', 'team1'); $team2 = $this->objFromFixture('GridFieldTest_Team', 'team2'); $response = $this->get('GridFieldAddExistingAutocompleterTest_Controller'); $this->assertFalse($response->isError()); $parser = new CSSContentParser($response->getBody()); $btns = $parser->getBySelector('.grid-field .action_gridfield_relationfind'); $response = $this->post('GridFieldAddExistingAutocompleterTest_Controller/Form/field/testfield/search' . '/?gridfield_relationsearch=Team 2', array((string) $btns[0]['name'] => 1)); $this->assertFalse($response->isError()); $result = Convert::json2array($response->getBody()); $this->assertEquals(1, count($result)); $this->assertEquals(array(array('label' => 'Team 2', 'value' => 'Team 2', 'id' => $team2->ID)), $result); $response = $this->post('GridFieldAddExistingAutocompleterTest_Controller/Form/field/testfield/' . 'search/?gridfield_relationsearch=Heather', array((string) $btns[0]['name'] => 1)); $this->assertFalse($response->isError()); $result = Convert::json2array($response->getBody()); $this->assertEquals(1, count($result), "The relational filter did not work"); $response = $this->post('GridFieldAddExistingAutocompleterTest_Controller/Form/field/testfield/search' . '/?gridfield_relationsearch=Unknown', array((string) $btns[0]['name'] => 1)); $this->assertFalse($response->isError()); $result = Convert::json2array($response->getBody()); $this->assertEmpty($result, 'The output is either an empty array or boolean FALSE'); }
/** * Test that UploadField:overwriteWarning cannot overwrite Upload:replaceFile */ public function testConfigOverwriteWarningCannotRelaceFiles() { Upload::config()->replaceFile = false; UploadField::config()->defaultConfig = array_merge(UploadField::config()->defaultConfig, array('overwriteWarning' => true)); $tmpFileName = 'testUploadBasic.txt'; $response = $this->mockFileUpload('NoRelationField', $tmpFileName); $this->assertFalse($response->isError()); $responseData = Convert::json2array($response->getBody()); $uploadedFile = DataObject::get_by_id('File', (int) $responseData[0]['id']); $this->assertTrue(is_object($uploadedFile), 'The file object is created'); $this->assertFileExists(AssetStoreTest_SpyStore::getLocalPath($uploadedFile)); $tmpFileName = 'testUploadBasic.txt'; $response = $this->mockFileUpload('NoRelationField', $tmpFileName); $this->assertFalse($response->isError()); $responseData = Convert::json2array($response->getBody()); $uploadedFile2 = DataObject::get_by_id('File', (int) $responseData[0]['id']); $this->assertTrue(is_object($uploadedFile2), 'The file object is created'); $this->assertFileExists(AssetStoreTest_SpyStore::getLocalPath($uploadedFile2)); $this->assertTrue($uploadedFile->Filename !== $uploadedFile2->Filename, 'Filename is not the same'); $this->assertTrue($uploadedFile->ID !== $uploadedFile2->ID, 'File database record is not the same'); }
public function convertStringToArray($strData) { return Convert::json2array($strData); }
/** * Gets the default settings in the actual Javascript object so that * the config JSON doesn't get polluted with default settings * * @return array */ protected function getDefaults() { $file_path = BASE_PATH . '/' . DROPZONE_DIR . '/' . $this->config()->default_config_path; if (!file_exists($file_path)) { throw new Exception("FileAttachmentField::getDefaults() - There is no config json file at {$file_path}"); } return Convert::json2array(file_get_contents($file_path)); }
/** * Parse the corresponding APIwesome JSON input, returning a formatted array of data objects and relationships. * * @parameter <{APIWESOME_JSON}> JSON * @return array */ public function parseJSON($JSON) { // Convert the corresponding JSON to a formatted array of data objects. $temporary = Convert::json2array($JSON); $objects = isset($temporary['APIwesome']['DataObjects']) ? $temporary['APIwesome']['DataObjects'] : null; return $objects; }
/** * @param $id * @return array */ public function getVideoDetail($id) { $video = PresentationVideo::get()->filter(['Presentation.Slug' => $id, 'DisplayOnSite' => true, 'Processed' => true])->first(); if (!$video) { $video = PresentationVideo::get()->filter(['ID' => $id, 'DisplayOnSite' => true, 'Processed' => true])->first(); } if ($video) { $cutoff = time() - SummitVideoApp::config()->video_view_staleness; $videoStaleness = strtotime($video->ViewsLastUpdated); // Refresh the views if they're not of acceptable staleness if (!$video->ViewsLastUpdated || $videoStaleness < $cutoff) { // Set the last updated regardless of the outcome, so we don't get // unthrottled failures. $video->ViewsLastUpdated = SS_DateTime::now()->Rfc2822(); try { $response = $this->youTube->getVideoStatsById($video->YouTubeID); if ($response) { $data = Convert::json2array($response->getBody()->getContents()); if (!empty($data['items'])) { $videoData = $data['items'][0]; $video->Views = $videoData['statistics']['viewCount']; } } } catch (Exception $e) { SS_Log::log("Summit video app tried to get video {$video->YouTubeID}: {$e->getMessage()}", SS_Log::ERR); } $video->write(); } $json = $this->createVideoJSON($video); $json['description'] = $video->Presentation()->ShortDescription ?: $video->Presentation()->Description; return $json; } }
/** * Compile the metadata into a readable list of key/value pairs. * * @return string */ public function DebugOutput() { $data = Convert::json2array("{" . $this->Metadata() . "}"); $ret = ""; foreach ($data as $k => $v) { $ret .= "<div><strong>{$k}</strong>: {$v}</div>"; } $ret .= "<div><strong>Directory</strong>: " . $this->getUploadFolder() . "</div>"; return $ret; }
/** * Process upload through UploadField, * creates new record and link newly uploaded file * adds record to GrifField relation list * and return image/file data and record edit form * * @param SS_HTTPRequest $request * @return string json */ public function upload(SS_HTTPRequest $request) { //create record $recordClass = $this->gridField->list->dataClass; $record = Object::create($recordClass); $record->write(); // passes the current gridfield-instance to a call-back method on the new object $record->extend("onBulkUpload", $this->gridField); if ($record->hasMethod('onBulkImageUpload')) { Deprecation::notice('2.0', '"onBulkImageUpload" callback is deprecated, use "onBulkUpload" instead.'); $record->extend("onBulkImageUpload", $this->gridField); } //get uploadField and process upload $uploadField = $this->getUploadField(); $uploadField->setRecord($record); $fileRelationName = $uploadField->getName(); $uploadResponse = $uploadField->upload($request); //get uploaded File response datas $uploadResponse = Convert::json2array($uploadResponse->getBody()); $uploadResponse = array_shift($uploadResponse); // Attach the file to record. $record->{"{$fileRelationName}ID"} = $uploadResponse['id']; $record->write(); // attached record to gridField relation $this->gridField->list->add($record->ID); // JS Template Data $responseData = $this->newRecordJSTemplateData($record, $uploadResponse); $response = new SS_HTTPResponse(Convert::raw2json(array($responseData))); $this->contentTypeNegotiation($response); return $response; }
function testPageTypesBlacklistInCMSMain() { $editor = $this->objFromFixture('Member', 'editor'); Session::set("loggedInAs", $editor->ID); $cmsmain = new CMSMain(); $s1 = $this->objFromFixture('Subsite', 'domaintest1'); $s2 = $this->objFromFixture('Subsite', 'domaintest2'); $s1->PageTypeBlacklist = 'SiteTreeSubsitesTest_ClassA,ErrorPage'; $s1->write(); Subsite::changeSubsite($s1); $hints = Convert::json2array($cmsmain->SiteTreeHints()); $classes = $hints['Root']['disallowedChildren']; $this->assertContains('ErrorPage', $classes); $this->assertContains('SiteTreeSubsitesTest_ClassA', $classes); $this->assertNotContains('SiteTreeSubsitesTest_ClassB', $classes); Subsite::changeSubsite($s2); $hints = Convert::json2array($cmsmain->SiteTreeHints()); $classes = $hints['Root']['disallowedChildren']; $this->assertNotContains('ErrorPage', $classes); $this->assertNotContains('SiteTreeSubsitesTest_ClassA', $classes); $this->assertNotContains('SiteTreeSubsitesTest_ClassB', $classes); }