Exemplo n.º 1
0
 public function getCik()
 {
     if (!$this->ticker) {
         return;
     }
     $url = 'http://finance.yahoo.com/q/sec?s=' . urlencode($this->ticker) . '+SEC+Filings';
     $cik = null;
     $sic = null;
     $browser = new sfWebBrowser();
     if (!$browser->get($url)->responseIsError()) {
         $text = $browser->getResponseText();
         //get CIK document codes
         preg_match('/cik\\=(\\d+)>/', $text, $matches);
         if ($matches) {
             $this->sec_cik = $matches[1];
             $this->save();
             return true;
         }
     }
     $url2 = 'http://www.sec.gov/cgi-bin/browse-edgar?company=&match=&CIK=' . urlencode($this->ticker) . '&filenum=&State=&Country=&SIC=&owner=exclude&Find=Find+Companies&action=getcompany';
     if (!$browser->get($url2)->responseIsError()) {
         $text = $browser->getResponseText();
         preg_match('/CIK\\=(\\d+)[^\\d]/', $text, $matches);
         if ($matches) {
             $this->sec_cik = $matches[1];
             $this->save();
             return true;
         }
     }
     return false;
 }
Exemplo n.º 2
0
 public function executeDocumentation($request)
 {
     $browser = new sfWebBrowser();
     $this->prefix = $request->getUriPrefix();
     if ($extraPrefix = $request->getParameter('prefix')) {
         $this->prefix .= $extraPrefix;
     }
     if (!($apiKey = sfConfig::get('app_documentation_admin_key'))) {
         return $this->renderText("Something's broken! Can't display API documentation.");
     }
     $orgId = 1;
     $personId = 1164;
     $relationshipId = 23;
     $listId = 23;
     $this->uris = array('entity_basic' => $this->prefix . '/entity/' . $orgId . '.xml', 'entity_details' => $this->prefix . '/entity/' . $orgId . '/details.xml', 'entity_batch' => $this->prefix . '/batch/entities.xml?ids=1,2,3,1201,28219,35306&details=1', 'entity_aliases' => $this->prefix . '/entity/' . $orgId . '/aliases.xml', 'entity_relationships' => $this->prefix . '/entity/' . $orgId . '/relationships.xml?cat_ids=1,7', 'entity_related' => $this->prefix . '/entity/' . $orgId . '/related.xml?cat_ids=1&order=2&is_current=1', 'entity_leadership' => $this->prefix . '/entity/' . $orgId . '/leadership.xml?is_current=1', 'entity_orgs' => $this->prefix . '/entity/' . $personId . '/orgs.xml', 'entity_degree2' => $this->prefix . '/entity/' . $orgId . '/related/degree2.xml?cat1_ids=1&cat2_ids=1&order1=2&order2=1', 'entity_lists' => $this->prefix . '/entity/' . $orgId . '/lists.xml', 'entity_childorgs' => $this->prefix . '/entity/' . $orgId . '/child-orgs.xml', 'entity_images' => $this->prefix . '/entity/' . $orgId . '/images.xml', 'entity_references' => $this->prefix . '/entity/' . $orgId . '/references.xml', 'entity_rel_references' => $this->prefix . '/entity/' . $orgId . '/relationships/references.xml?cat_ids=1,7', 'relationship_basic' => $this->prefix . '/relationship/' . $relationshipId . '.xml', 'relationship_details' => $this->prefix . '/relationship/' . $relationshipId . '/details.xml', 'relationship_batch' => $this->prefix . '/batch/relationships.xml?ids=' . implode(',', range(74, 95)) . '&details=1', 'relationship_references' => $this->prefix . '/relationship/' . $relationshipId . '/references.xml', 'list_basic' => $this->prefix . '/list/' . $listId . '.xml', 'list_entities' => $this->prefix . '/list/' . $listId . '/entities.xml?type_ids=29', 'entity_search' => $this->prefix . '/entities.xml?q=treasury&type_ids=35', 'entity_lookup' => $this->prefix . '/entities/bioguide_id/O000167.xml', 'entity_chains' => $this->prefix . '/entities/chains/1;2.xml', 'relationship_search' => $this->prefix . '/relationships/1026;1.xml?cat_ids=1', 'list_search' => $this->prefix . '/lists.xml?q=forbes');
     $this->responses = array();
     foreach ($this->uris as $key => $uri) {
         $uri = $this->addKeyToUri($uri, $apiKey);
         if ($browser->get($uri)->responseIsError()) {
             throw new Exception("Couldn't get example URI: " . $uri);
         }
         $text = $browser->getResponseText();
         $this->responses[$key] = LsDataFormat::formatXmlString($text);
     }
 }
Exemplo n.º 3
0
 /**
  * /robokassa/init
  * Инициализация транзакции и возврат json-обекта
  *
  * @param sfWebRequest $request
  */
 public function executeInit(sfWebRequest $request)
 {
     $userId = $this->getUser()->getUserRecord()->getId();
     // В качестве параметра ожидаем ID услуги (POST параметр service)
     $serviceId = (int) $request->getParameter("service", 0);
     $term = (int) $request->getParameter("term", 1);
     // Получаем стоимость услуги
     $service = Doctrine::getTable('Service')->find($serviceId);
     $this->forward404Unless($service);
     $price = $service->getPrice();
     // Инициализация транзакции
     $transaction = new BillingTransaction();
     $transaction->setUserId($userId);
     $transaction->setPaysystem('robokassa');
     $transaction->setServiceId($serviceId);
     $transaction->setPrice($price);
     $transaction->setTerm($term);
     $total = round($term * $price, 2);
     $transaction->setTotal($total);
     $transaction->save();
     $url = Robokassa::getScriptURL($transaction);
     $b = new sfWebBrowser();
     $b->get($url);
     $text = $b->getResponseText();
     $matches = array();
     preg_match_all("/^(.*)document.write\\(\\'(.*)\\'\\)/isu", $text, $matches);
     $return = array("result" => array("script" => html_entity_decode(trim($matches[1][0])), "html" => html_entity_decode(trim($matches[2][0]))));
     $this->getResponse()->setHttpHeader('Content-Type', 'application/json');
     return $this->renderText(json_encode($return));
 }
Exemplo n.º 4
0
 public static function test()
 {
     $url = 'http://www.nytimes.com/2010/11/02/us/politics/02campaign.html?hp';
     $browser = new sfWebBrowser();
     $text = $browser->get($url)->getResponseText();
     $ret = self::getEntityNames($text, array('Person', 'Org'));
     //var_dump($ret);
 }
Exemplo n.º 5
0
 public function executeIndex(sfWebRequest $request)
 {
     if ($this->getUser()->isAuthenticated() && $this->getUser()->getGuardUser()->account_type != 'Trial') {
         $this->getUser()->setFlash('notice', 'You are already registered and signed in!');
         $this->redirect('/project');
     }
     if ($this->getUser()->isAuthenticated()) {
         $user = $this->getUser()->getGuardUser();
         $user->email_address = '';
         $user->account_type = 'Free';
         $this->form = new sfGuardRegisterForm($user);
     } else {
         $this->form = new sfGuardRegisterForm();
         if ($this->getUser()->getAttribute('google_token')) {
             $google_token = json_decode($this->getUser()->getAttribute('google_token'));
             $browser = new sfWebBrowser(array(), null, array('ssl_verify_host' => false, 'ssl_verify' => false));
             $result = $browser->get('https://www.googleapis.com/oauth2/v1/userinfo?access_token=' . $google_token->access_token);
             if ($result->getResponseCode() == 200) {
                 $response_text = json_decode($result->getResponseText());
                 if (property_exists($response_text, 'email')) {
                     $user_exists = sfGuardUserTable::getInstance()->createQuery('u')->where('email_address = ?', $response_text->email)->fetchOne();
                     if (is_object($user_exists)) {
                         $this->getUser()->setAttribute('google_token', null);
                         if ($user_exists->is_active) {
                             $this->getUser()->signIn($user_exists);
                             $this->redirect('/project');
                         } else {
                             $this->getUser()->setFlash('notice', 'Check your e-mail! You should verify your email address.');
                             $this->redirect('@sf_guard_signin');
                         }
                     }
                     $this->getUser()->setAttribute('google_token_info', array($response_text->email => array('given_name' => $response_text->given_name, 'family_name' => $response_text->family_name)));
                     $this->form->setDefault('email_address', $response_text->email);
                     //            $this->form->getWidget('email_address')->setAttribute('readonly', 'readonly');
                 }
             }
         }
     }
     if ($request->isMethod('post')) {
         $this->form->bind($request->getParameter($this->form->getName()));
         if ($this->form->isValid()) {
             $user = $this->form->save();
             $google_token_info = $this->getUser()->getAttribute('google_token_info');
             $this->getUser()->setAttribute('google_token', null);
             $this->getUser()->setAttribute('google_token_info', null);
             if (is_array($google_token_info) && array_key_exists($user->email_address, $google_token_info)) {
                 $user->first_name = $google_token_info[$user->email_address]['given_name'];
                 $user->last_name = $google_token_info[$user->email_address]['family_name'];
                 $user->is_active = true;
                 @$user->save();
                 $this->getUser()->signIn($user);
                 $this->redirect('/project');
             } else {
                 $this->sendConfirmationEmail($user);
             }
         }
     }
 }
Exemplo n.º 6
0
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
 public function executeIndex(sfWebRequest $request)
 {
     $b = new sfWebBrowser();
     $b->get(sfConfig::get('sf_takutomo_get_attend_event_url'), array('guid' => 'DEBUG,sample_member_001'));
     //xmlを連想配列に変換
     $options = array('complexType' => 'array');
     $Unserializer = new XML_Unserializer($options);
     $status = $Unserializer->unserialize($b->getResponseText());
     //if ($status === true) {
     $this->get_attend_event_list = $Unserializer->getUnserializedData();
 }
Exemplo n.º 7
0
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
 public function executeIndex(sfWebRequest $request)
 {
     //$mixi_persistence = $persistence->entry->{'mixi.jp:'.MixiAppMobileApi::$ownerId};
     $b = new sfWebBrowser();
     $b->get(sfConfig::get('sf_takutomo_get_attend_event_url'), array('guid' => 'mixi,' . MixiAppMobileApi::$ownerId));
     //xmlを連想配列に変換
     $options = array('complexType' => 'array');
     $Unserializer = new XML_Unserializer($options);
     $status = $Unserializer->unserialize($b->getResponseText());
     //if ($status === true) {
     $this->get_attend_event_list = $Unserializer->getUnserializedData();
 }
Exemplo n.º 8
0
 /**
  * 相乗りリストを返す 
  * errorの場合 null
  */
 private function getAttendEventList()
 {
     $b = new sfWebBrowser();
     $b->get(sfConfig::get('sf_takutomo_get_attend_event_url'), array('guid' => 'mixi,' . MixiAppMobileApi::$ownerId));
     //xmlを連想配列に変換
     $options = array('complexType' => 'array');
     $Unserializer = new XML_Unserializer($options);
     $status = $Unserializer->unserialize($b->getResponseText());
     if ($status === true) {
         return $Unserializer->getUnserializedData();
     } else {
         return null;
     }
 }
 /**
  * Retrieve a new sfFeed implementation instance, populated from a web feed.
  * The class of the returned instance depends on the nature of the web feed.
  * This method uses the sfWebBrowser plugin.
  *
  * @param string A web feed URI
  *
  * @return sfFeed A sfFeed implementation instance
  */
 public static function createFromWeb($uri, $options = array())
 {
     if (isset($options['adapter'])) {
         $browser = new sfWebBrowser(array(), $options['adapter'], isset($options['adapter_options']) ? $options['adapter_options'] : array());
     } else {
         $browser = new sfWebBrowser();
     }
     $browser->setUserAgent(isset($options['userAgent']) ? $options['userAgent'] : 'sfFeedReader/0.9');
     if ($browser->get($uri)->responseIsError()) {
         $error = 'The given URL (%s) returns an error (%s: %s)';
         $error = sprintf($error, $uri, $browser->getResponseCode(), $browser->getResponseMessage());
         throw new Exception($error);
     }
     $feedString = $browser->getResponseText();
     return self::createFromXml($feedString, $uri);
 }
 function writeTmpFile($source, $debug = false, $localdir = false)
 {
     $defaultHeaders = array('User-Agent' => 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.1) Gecko/20061205 Iceweasel/2.0.0.1 (Debian-2.0.0.1+dfsg-2)');
     $b = new sfWebBrowser($defaultHeaders, 'sfCurlAdapter', array('cookies' => true));
     if ($b->get($source)->responseIsError()) {
         return false;
     }
     $fileData = $b->getResponseText();
     unset($b);
     $filePath = $this->getLocalPath($source, $localdir);
     $localFile = fopen($filePath, 'w+b');
     fwrite($localFile, $fileData);
     if ($debug) {
         print "SAVED LOCAL: " . $source . " [" . sha1($source) . "] [" . strlen($fileData) . "]\n";
     }
     if (!fclose($localFile)) {
         throw new Exception("Couldn't close file: " . $filePath);
     }
 }
Exemplo n.º 11
0
 public function executeOnePercentSearch($request)
 {
     $this->search_form = new OnePercentSearchForm();
     if ($request->isMethod('post')) {
         $searchParams = $request->getParameter('onepercent');
         $url = $searchParams['url'];
         $text = $searchParams['text'];
         $this->search_form->bind($searchParams);
         if (!$this->search_form->isValid()) {
             return;
         }
         if ($url) {
             $browser = new sfWebBrowser();
             if (!$browser->get($url)->responseIsError()) {
                 $text = $browser->getResponseText();
             }
         }
         if ($text) {
             $html = stripos($text, "<html");
             $entity_types = 'people';
             $names = array();
             if ($html !== false) {
                 $names = LsTextAnalysis::getHtmlEntityNames($text, $entity_types);
             } else {
                 $names = LsTextAnalysis::getTextEntityNames($text, $entity_types);
             }
             $this->matches = array();
             foreach ($names as $name) {
                 $name_terms = $name;
                 $name_parts = preg_split('/\\s+/', $name);
                 if (count($name_parts) > 1) {
                     $name_terms = PersonTable::nameSearch($name);
                 }
                 $pager = EntityTable::getSphinxPager($terms, $page = 1, $num = 20, $listIds = null, $aliases = true, $primary_ext = "Person");
                 $match['name'] = $name;
                 $match['search_results'] = $pager->execute();
                 $this->matches[] = $match;
             }
         }
     }
 }
Exemplo n.º 12
0
 protected function execute($arguments = array(), $options = array())
 {
     $databaseManager = new sfDatabaseManager($this->configuration);
     $connection = $databaseManager->getDatabase($options['connection'])->getConnection();
     $web = new sfWebBrowser();
     $latest = Doctrine::getTable('Position')->createQuery('p')->limit(1)->orderBy('p.timestamp DESC')->fetchOne();
     $this->logSection($this->namespace, 'Getting latest instamapper positions');
     $instamapper = $web->get('http://www.instamapper.com/api?action=getPositions&key=' . sfConfig::get('app_instamapper_api_key') . '&num=1000' . ($latest instanceof Position ? '&from_ts=' . $latest->getTimestamp() : '') . '&format=json');
     try {
         if (!$instamapper->responseIsError()) {
             $json = json_decode($instamapper->getResponseText());
             foreach ($json->positions as $gps) {
                 if (!$latest instanceof Position || $gps->timestamp >= $latest->getTimestamp()) {
                     $position = new Position();
                     $position->setDeviceKey($gps->device_key);
                     $position->setDeviceLabel($gps->device_label);
                     $position->setTimestamp($gps->timestamp);
                     $position->setLatitude($gps->latitude);
                     $position->setLongitude($gps->longitude);
                     $position->setAltitude($gps->altitude);
                     $position->setSpeed($gps->speed);
                     $position->setHeading($gps->heading);
                     $position->save();
                     echo '.';
                     $this->new++;
                 }
             }
         } else {
             // Error response (eg. 404, 500, etc)
         }
     } catch (Exception $e) {
         // Adapter error (eg. Host not found)
     }
     echo "\n";
     $this->logSection($this->namespace, 'Done: ' . $this->new . ' added.');
 }
Exemplo n.º 13
0
 static function parseV3($str)
 {
     $str = preg_replace('/[\\n\\r]/', ' ', $str);
     $url = 'http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=' . urlencode($str);
     $c = new sfWebBrowser();
     try {
         if (!$c->get($url)->responseIsError()) {
             $c->setResponseText(iconv('ISO-8859-1', 'UTF-8', $c->getResponseText()));
             $json = $c->getResponseText();
             $result = json_decode($json, true);
         } else {
             return null;
         }
     } catch (Exception $e) {
         // Adapter error (eg. Host not found)
         throw $e;
     }
     if ($result['status'] == 'OK') {
         $address = self::parseGeoArray($result);
         return $address;
     } else {
         return false;
     }
 }
Exemplo n.º 14
0
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
 public function executeIndex(sfWebRequest $request)
 {
     $this->form = new AddEventForm();
     $b = new sfWebBrowser();
     $now = strtotime('+15 minute');
     $depart_date = array('year' => date('Y', $now), 'month' => date('n', $now), 'day' => date('j', $now));
     $depart_time = array('hour' => date('G', $now), 'minute' => (int) date('i', $now));
     if ($request->isMethod('get')) {
         $request->setParameter('lat', str_replace('+', '', $this->getRequestParameter('lat')));
         $request->setParameter('lon', str_replace('+', '', $this->getRequestParameter('lon')));
         $b->get(sfConfig::get('sf_google_geo_url'), array('output' => 'xml', 'hl' => 'ja', 'key' => sfConfig::get('sf_google_key'), 'oe' => 'UTF-8', 'll' => $this->getRequestParameter('lat') . ',' . $this->getRequestParameter('lon')));
         $xml = new SimpleXMLElement($b->getResponseText());
         $from_address = (string) $xml->Response->Placemark[0]->AddressDetails->Country->AdministrativeArea->AdministrativeAreaName;
         $from_address .= (string) $xml->Response->Placemark[0]->AddressDetails->Country->AdministrativeArea->Locality->LocalityName;
         $from_address .= (string) $xml->Response->Placemark[0]->AddressDetails->Country->AdministrativeArea->Locality->DependentLocality->DependentLocalityName;
         $from_address .= (string) $xml->Response->Placemark[0]->AddressDetails->Country->AdministrativeArea->Locality->DependentLocality->Thoroughfare->ThoroughfareName;
         //初期値設定
         $this->form->setDefault('from_address', $from_address);
         $this->form->setDefault('from_lat', $this->getRequestParameter('lat'));
         $this->form->setDefault('from_lon', $this->getRequestParameter('lon'));
         $this->form->setDefault('depart_date', $depart_date);
         $this->form->setDefault('depart_time', $depart_time);
     } else {
         if ($request->isMethod('post')) {
             //出発地
             if ($request->getParameter('departure') != '') {
                 $b->get(sfConfig::get('sf_google_geo_url'), array('output' => 'xml', 'sensor' => 'false', 'key' => sfConfig::get('sf_google_key'), 'q' => $request->getParameter('from_address')));
                 //print (string)$b->getResponseText();
                 //print "<br>";
                 $xml = new SimpleXMLElement($b->getResponseText());
                 if (count($xml->Response->Placemark) > 1) {
                     $this->form->getErrorSchema()->addError(new sfValidatorError(new sfValidatorPass(), '出発地が複数あります、詳しく入力してください。', array('from_address')));
                 } else {
                 }
                 $split = explode(',', (string) $xml->Response->Placemark[0]->Point->coordinates);
                 $this->form->setDefault('from_address', $request->getParameter('from_address'));
                 $this->form->setDefault('from_lat', $split[1]);
                 $this->form->setDefault('from_lon', $split[0]);
                 $this->form->setDefault('to_address', $request->getParameter('to_address'));
                 $this->form->setDefault('to_lat', $request->getParameter('to_lat'));
                 $this->form->setDefault('to_lon', $request->getParameter('to_lon'));
                 $this->form->setDefault('depart_date', $depart_date);
                 $this->form->setDefault('depart_time', $depart_time);
                 //目的地
             } else {
                 if ($request->getParameter('destination') != '') {
                     $b->get(sfConfig::get('sf_google_geo_url'), array('output' => 'xml', 'sensor' => 'false', 'key' => sfConfig::get('sf_google_key'), 'q' => $request->getParameter('to_address')));
                     $xml = new SimpleXMLElement($b->getResponseText());
                     if (count($xml->Response->Placemark) > 1) {
                         $this->form->getErrorSchema()->addError(new sfValidatorError(new sfValidatorPass(), '目的地が複数あります、詳しく入力してください。', array('to_address')));
                     }
                     $split = explode(',', (string) $xml->Response->Placemark[0]->Point->coordinates);
                     $this->form->setDefault('to_address', $request->getParameter('to_address'));
                     $this->form->setDefault('to_lat', $split[1]);
                     $this->form->setDefault('to_lon', $split[0]);
                     $this->form->setDefault('from_address', $request->getParameter('from_address'));
                     $this->form->setDefault('from_lat', $request->getParameter('from_lat'));
                     $this->form->setDefault('from_lon', $request->getParameter('from_lon'));
                     $this->form->setDefault('depart_date', $depart_date);
                     $this->form->setDefault('depart_time', $depart_time);
                 } else {
                     $this->form->bind($request->getParameterHolder()->getAll());
                     if ($this->form->isValid()) {
                         $depart_date = $this->getRequestParameter('depart_date');
                         $depart_time = $this->getRequestParameter('depart_time');
                         $b->post(sfConfig::get('sf_takutomo_add_event_url'), array('guid' => 'DEBUG,sample_member_001', 'from_address' => $this->getRequestParameter('from_address'), 'from_lat' => $this->getRequestParameter('from_lat'), 'from_lon' => $this->getRequestParameter('from_lon'), 'to_address' => $this->getRequestParameter('to_address'), 'to_lat' => $this->getRequestParameter('to_lat'), 'to_lon' => $this->getRequestParameter('to_lon'), 'depart_date' => $depart_date['year'] . sprintf('%02d', $depart_date['month']) . sprintf('%02d', $depart_date['day']), 'depart_hour' => $depart_time['hour'], 'depart_min' => $depart_time['minute'], 'detail' => $this->getRequestParameter('detail')));
                         $xml = new SimpleXMLElement($b->getResponseText());
                         //print $b->getResponseText();
                         //print((string)$xml->status->code);
                         if ((int) $xml->status->code >= 1000) {
                             $this->form->getErrorSchema()->addError(new sfValidatorError(new sfValidatorPass(), (string) $xml->status->description));
                         } else {
                             //検索条件をsessionに格納
                             $this->getUser()->setToAddress($this->getRequestParameter('to_address'));
                             $this->getUser()->setToLon($this->getRequestParameter('to_lon'));
                             $this->getUser()->setToLat($this->getRequestParameter('to_lat'));
                             $this->getUser()->setFromAddress($this->getRequestParameter('from_address'));
                             $this->getUser()->setFromLon($this->getRequestParameter('from_lon'));
                             $this->getUser()->setFromLat($this->getRequestParameter('from_lat'));
                             $this->setTemplate('submit');
                         }
                         $this->display_description = (string) $xml->status->description;
                     }
                 }
             }
         }
     }
 }
 /**
  * Populate a digital object from a resource pointed to by a URI
  * This is for, eg. importing encoded digital objects from XML
  *
  * @param string  $uri  URI pointing to the resource
  * @return boolean  success or failure
  */
 public function importFromURI($uri, $options = array())
 {
     // Parse URL into components and get file/base name
     $uriComponents = parse_url($uri);
     // Initialize web browser
     $browser = new sfWebBrowser(array(), null, array('Timeout' => 10));
     // Add asset to digital object assets array
     if (true !== $browser->get($uri)->responseIsError() && 0 < strlen($filename = basename($uriComponents['path']))) {
         $asset = new QubitAsset($uri, $browser->getResponseText());
         $this->assets[] = $asset;
     } else {
         throw new sfException('Encountered error fetching external resource.');
     }
     // Set digital object as external URI
     $this->usageId = QubitTerm::EXTERNAL_URI_ID;
     // Save filestream temporary, because sfImageMagickAdapter does not support load data from streams
     $this->localPath = Qubit::saveTemporaryFile($filename, $asset->getContents());
     $this->name = $filename;
     $this->path = $uri;
     $this->checksum = $asset->getChecksum();
     $this->checksumType = $asset->getChecksumAlgorithm();
     $this->byteSize = strlen($browser->getResponseText());
     $this->setMimeAndMediaType();
 }
Exemplo n.º 16
0
 /*******************/
 $t->diag('Browser restart');
 $b->restart();
 try {
     $b->reload();
     $t->fail('restart() reinitializes the browser history');
 } catch (Exception $e) {
     $t->pass('restart() reinitializes the browser history');
 }
 $t->is($b->getResponseText(), '', 'restart() reinitializes the response');
 /*************/
 /* Redirects */
 /*************/
 $t->diag('Redirects');
 $b = new sfWebBrowser(array(), $adapter);
 $b->get('http://www.symfony-project.com/trac/wiki/sfUJSPlugin');
 $t->like($b->getResponseText(), '/learn more about the unobtrusive approach/', 'follows 302 redirect after a GET');
 $b = new myTestWebBrowser(array(), $adapter);
 $b->call($askeet_params['url'] . '/index.php/login', 'POST', array('nickname' => $askeet_params['login'], 'password' => $askeet_params['password']));
 //$t->like($b->getResponseText(), '/url='.preg_quote($askeet_params['url'], '/').'\/index\.php/', 'does NOT follow a 302 redirect after a POST');
 $t->like($b->getResponseText(), '/featured questions/', 'follows 302 redirect after POST ****** DESPITE THE HTTP SPEC ******');
 $t->is($b->getRequestMethod(), 'GET', 'request method is changed to GET after POST for 302 redirect ***** DESPITE THE HTTP SPEC *****');
 $t->todo('request method is changed to GET after POST for 303 redirect');
 /***********/
 /* Cookies */
 /***********/
 $t->diag('Cookies');
 if ($adapter == 'sfCurlAdapter') {
     $b = new sfWebBrowser(array(), $adapter, array('cookies' => true, 'cookies_file' => $cookies_file, 'cookies_dir' => $cookies_dir));
     $b->call($askeet_params['url'] . '/login', 'POST', array('nickname' => $askeet_params['login'], 'password' => $askeet_params['password']));
     $t->like($b->getResponseBody(), '/' . $askeet_params['login'] . ' profile/', 'Cookies can be added to the request');
Exemplo n.º 17
0
 static function createFiles($filePath, $originalFilename = '')
 {
     //generate filename
     $filename = self::generateFilename($originalFilename);
     $originalFilePath = $filePath;
     //if remote path, create temporary local copy
     if (preg_match('#http(s)?://#i', $filePath)) {
         $url = $filePath;
         $defaultHeaders = array('User-Agent' => 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.1) Gecko/20061205 Iceweasel/2.0.0.1 (Debian-2.0.0.1+dfsg-2)');
         $b = new sfWebBrowser($defaultHeaders, 'sfCurlAdapter', array('cookies' => true));
         if ($b->get($url)->responseIsError()) {
             return false;
         }
         $fileData = $b->getResponseText();
         unset($b);
         $filePath = sfConfig::get('sf_temp_dir') . DIRECTORY_SEPARATOR . $filename;
         $localImage = fopen($filePath, 'wb');
         fwrite($localImage, $fileData);
         if (!fclose($localImage)) {
             throw new Exception("Couldn't close file: " . $filePath);
         }
         if (strtolower(substr($originalFilePath, -3, 3)) == "svg") {
             if (self::imageMagickInstalled()) {
                 $svgFilepath = sfConfig::get('sf_temp_dir') . DIRECTORY_SEPARATOR . substr($filename, 0 - 3) . ".svg";
                 $origFilepath = sfConfig::get('sf_temp_dir') . DIRECTORY_SEPARATOR . $filename;
                 rename($origFilepath, $svgFilepath);
                 exec("{$convert} {$svgFilepath} {$origFilepath}");
             }
         }
     }
     //create full size file up to 1024x1024
     if (!self::createFile($filename, $filePath, 'large', 1024, 1024)) {
         return false;
     }
     //create profile size
     if (!self::createFile($filename, $filePath, 'profile', 200, 200)) {
         unlink(sfConfig::get('sf_image_dir') . DIRECTORY_SEPARATOR . 'large' . DIRECTORY_SEPARATOR . $filename);
         return false;
     }
     //create small size
     if (!self::createFile($filename, $filePath, 'small', null, 50)) {
         unlink(sfConfig::get('sf_image_dir') . DIRECTORY_SEPARATOR . 'large' . DIRECTORY_SEPARATOR . $filename);
         unlink(sfConfig::get('sf_image_dir') . DIRECTORY_SEPARATOR . 'profile' . DIRECTORY_SEPARATOR . $filename);
         return false;
     }
     /*
     if (!self::createSquareFile($filename, $filePath, 'square', 300))
     {
       unlink(sfConfig::get('sf_image_dir') . DIRECTORY_SEPARATOR . 'large' . DIRECTORY_SEPARATOR . $filename);
       unlink(sfConfig::get('sf_image_dir') . DIRECTORY_SEPARATOR . 'profile' . DIRECTORY_SEPARATOR . $filename);
       unlink(sfConfig::get('sf_image_dir') . DIRECTORY_SEPARATOR . 'small' . DIRECTORY_SEPARATOR . $filename);
       return false;    
     }
     */
     //remove temporary file
     if (isset($url)) {
         unlink($filePath);
     }
     return $filename;
 }
Exemplo n.º 18
0
 public function testClickLink()
 {
     $browser = new sfWebBrowser(array(), 'MockAdapter', array('test_file' => dirname(__FILE__) . '/Html/test_click.html'));
     $browser->get('http://localhost');
     $browser->click('Go');
 }
$t->diag('sfWebRPCPlugin XMLRPC');
// build the xmlrpc client
require_once $project_rootdir . '/plugins/sfWebRPCPlugin/lib/vendor/IXR_Library.inc.php';
$client = new IXR_Client($project_baseurl . "/sfWebRPCPluginDemo/RPC2");
// query remote neoip-casti to pull cast_mdata
$succeed = $client->query('add', 3, 7);
$t->is($client->query('add', 3, 7), true, 'call to sfWebRPCPluginDemo::add succeed');
// if it failed, notify the error
//if(! $succeed )	throw new Exception("Error doing xmlrpc to casti_srv_uri due to ".$client->getErrorMessage());
$t->is($client->getResponse(), 10, 'add 3+7 is 10');
$t->is($client->query('fctnamej_which_doesnt_exist'), false, 'call to unexisting function fails as expected');
/************************************************************************/
/*		Test handler JSON					*/
/************************************************************************/
$t->diag('sfWebRPCPlugin JSON');
$b->get($project_baseurl . "/sfWebRPCPluginDemo/JSON?method=add&arg0=3&arg1=2");
$t->is($b->getResponseCode(), 200, 'http code 200 on "add" JSON handler');
$t->is($b->getResponseHeader("Content-Type"), "application/json", "mimetype is application/json on json call");
$t->is($b->getResponseText(), 5, "response is 5 (as expected for add(3,2))");
$b->get($project_baseurl . "/sfWebRPCPluginDemo/JSON?method=add&arg0=3");
$t->isnt($b->getResponseCode(), 200, 'http code NOT 200 "add" when wrong number of parameters');
/************************************************************************/
/*		Test handler JSONP					*/
/************************************************************************/
$t->diag('sfWebRPCPlugin JSONP');
$b->get($project_baseurl . "/sfWebRPCPluginDemo/JSON?callback=cbsample&method=add&arg0=3&arg1=2");
$t->is($b->getResponseCode(), 200, 'http code 200 on "add" JSON handler');
$t->like($b->getResponseHeader("Content-Type"), "/text\\/javascript/", "mimetype is text/javascript on JSONP call");
$t->is($b->getResponseText(), 'cbsample("5")', 'response is cbsample("5")');
/************************************************************************/
/*		Test handler XDOMRPC					*/
Exemplo n.º 20
0
    $t->fail('no test application url set in test.yml, please check the README file');
    return;
}
$t->pass("Configuration validated");
exit;
// sfWebBrowser using sfCurlAdapter, cookies enabled for sandbox authentication
$web_browser = new sfWebBrowser(array(), "sfCurlAdapter", array('cookies' => true));
// delete the cookies if exist
if (is_file($file = sfConfig::get('sf_data_dir') . '/sfWebBrowserPlugin/sfCurlAdapter/cookies.txt')) {
    unlink($file);
}
/**
 * Login to sandbox
 */
$t->comment('sfPaymentPayPal/sample');
$web_browser->get($sf_payment_paypal_test['application_url'] . '/sfPaymentPayPal/sample');
$t->comment('Pay with PayPal');
$web_browser->click('Pay with PayPal');
$t->comment('PayPal Sandbox');
$web_browser->click('PayPal Sandbox');
$t->comment('Login to sandbox');
$web_browser->setField('login_email', $sf_payment_paypal_test['developer_email'])->setField('login_password', $sf_payment_paypal_test['developer_password'])->click('Log In');
if (eregi("field_label_error", $web_browser->getResponseText()) || eregi('<span class="error">The email address or password you have entered does not match our records. Please try again.</span>', $web_browser->getResponseText())) {
    $t->fail('Could not login to paypal sandbox');
    return;
} else {
    $t->pass('Login successful');
}
/*
 * Go back to site
 */
    foreach ($feeds as $feedurl) {
        $feed = sfFeedPeer::createFromWeb($feedurl);
        $items = $feed->getItems();
        foreach ($items as $item) {
            $pages[] = $item->getLink();
        }
    }
    $cache->set('pages', 'my_cache_dir', $pages);
}
$images = $cache->get('images', 'my_cache_dir');
if ($images === null) {
    $images = array();
    $numofpages = count($pages);
    foreach ($pages as $pageindex => $url) {
        $path = substr($url, 0, strrpos($url, '/') + 1);
        $b = new sfWebBrowser();
        $b->get($url);
        echo "Parsing " . $url . " [" . $pageindex . " of " . $numofpages . "]\n";
        $result = preg_match_all('/\\<img src="(.*?)"/is', $b->getResponseText(), $matches);
        if ($result !== FALSE && $result > 0) {
            foreach ($matches[1] as $matchindex => $match) {
                if ($matchindex == 0) {
                    continue;
                }
                $match = strtolower($match);
                $images[$url][] = $path . $match;
            }
        }
    }
    $cache->set('images', 'my_cache_dir', $images);
}
Exemplo n.º 22
0
 protected function execute($arguments = array(), $options = array())
 {
     $databaseManager = new sfDatabaseManager($this->configuration);
     $connection = $databaseManager->getDatabase($options['connection'])->getConnection();
     $web = new sfWebBrowser();
     $this->logSection($this->namespace, 'Getting latest tweets for @' . sfConfig::get('app_twitter_username'));
     $atom = $web->get('http://search.twitter.com/search.atom?q=from:' . sfConfig::get('app_twitter_username') . '&rpp=5');
     try {
         if (!$atom->responseIsError()) {
             $feed = new SimpleXMLElement($atom->getResponseText());
             foreach ($feed->entry as $rss) {
                 $id = preg_replace('/[^0-9]+/', '', $rss->link[0]['href']);
                 $tweet = Doctrine::getTable('Tweet')->find($id);
                 $namespaces = $rss->getNameSpaces(true);
                 if ($tweet instanceof Tweet) {
                     if (strtotime($rss->updated) <= strtotime($tweet->getUpdatedAt())) {
                         continue;
                     } else {
                         $this->updated++;
                     }
                 } else {
                     $tweet = new Tweet();
                     $this->new++;
                 }
                 $file = $web->get('http://api.twitter.com/1/statuses/show/' . $id . '.json');
                 try {
                     if (!$file->responseIsError()) {
                         $json = json_decode($file->getResponseText());
                         $tweet->setId($id);
                         $tweet->setText($rss->title);
                         $tweet->setHTML(html_entity_decode($rss->content));
                         $tweet->setUri($rss->link[0]['href']);
                         if (isset($json->in_reply_to_status_id)) {
                             $tweet->setReplyId($json->in_reply_to_status_id);
                         }
                         if (isset($json->in_reply_to_user_id)) {
                             $tweet->setReplyUserId($json->in_reply_to_user_id);
                             $tweet->setReplyUsername($json->in_reply_to_screen_name);
                         }
                         if (isset($json->geo, $json->geo->coordinates)) {
                             $tweet->setLatitude($json->geo->coordinates[0]);
                             $tweet->setLongitude($json->geo->coordinates[1]);
                         }
                         $tweet->setLanguage($rss->children($namespaces['twitter'])->lang);
                         $tweet->setSource(html_entity_decode($rss->children($namespaces['twitter'])->source));
                         $tweet->setCreatedAt($rss->published);
                         $tweet->setUpdatedAt($rss->updated);
                         $tweet->save();
                         echo '.';
                     } else {
                         // Error response (eg. 404, 500, etc)
                     }
                 } catch (Exception $e) {
                     // Adapter error (eg. Host not found)
                 }
             }
         } else {
             // Error response (eg. 404, 500, etc)
         }
     } catch (Exception $e) {
         // Adapter error (eg. Host not found)
     }
     echo "\n";
     $this->logSection($this->namespace, 'Done: ' . $this->new . ' new, ' . $this->updated . ' updated.');
 }
Exemplo n.º 23
0
 public function executeTo(sfWebRequest $request)
 {
     $this->form = new sfForm();
     if ($request->isMethod('post')) {
         if ($request->getParameter('to_address') == "") {
             $this->form->getErrorSchema()->addError(new sfValidatorError(new sfValidatorPass(), $this->from_error));
         } else {
             $b = new sfWebBrowser();
             $b->get(sfConfig::get('sf_google_geo_url'), array('output' => 'xml', 'sensor' => 'false', 'key' => sfConfig::get('sf_google_key'), 'q' => $request->getParameter('to_address')));
             $this->viewList($request, $b, "toConfirm");
             return sfView::SUCCESS;
         }
     } else {
         if ($request->getParameter('lat') != "" && $request->getParameter('lon') != "") {
             $lon = GpsConverter::dmsToDegree($this->getRequestParameter('lon'));
             $lat = GpsConverter::dmsToDegree($this->getRequestParameter('lat'));
             $b = new sfWebBrowser();
             $b->get(sfConfig::get('sf_google_geo_url'), array('output' => 'xml', 'sensor' => 'false', 'key' => sfConfig::get('sf_google_key'), 'll' => $lat . ',' . $lon));
             $this->viewList($request, $b, "toConfirm");
             return sfView::SUCCESS;
         }
     }
 }
Exemplo n.º 24
0
        if (array_key_exists($activity, $meta_activities)) {
            $item->addChild('activity', $meta_activities[$activity]);
        }
    }
    $item->addChild('original_outing_id', $id);
    $item->addChild('url', "http://www.camptocamp.org/outings/{$id}/{$lang}/" . make_slug(htmlspecialchars($object->get('name'))));
}
if (!$n) {
    exit;
    // it's better to keep the script mute if not necessary, thus avoiding cron to send useless mails
}
// debug info :
//echo "XML created : \n" . $xml->asXML() . " \n";
$b = new sfWebBrowser();
try {
    if (!$b->get($meta_url)->responseIsError()) {
        // Successful response (eg. 200, 201, etc)
        //echo "Pushing $n outing(s) ... \n";
        $b->post($meta_url . 'outings/push', array('metaengine_user_id' => $user_id, 'metaengine_user_key' => $user_key, 'metaengine_xml' => urlencode($xml->asXML())));
        $response = $b->getResponseXml();
        if ($response->status == 1) {
            //echo "Push succeeded. \n";
        } else {
            // now, what append ???
            // try to get more info on what could make it fail
            //var_dump($xml->asXML());
            //var_dump($response);
            foreach ($response->errors->error as $error) {
                if (!isset($complaint)) {
                    echo "Push failed for outings:\n";
                    $complaint = 1;
Exemplo n.º 25
0
 public function executeTo(sfWebRequest $request)
 {
     $this->form = new sfForm();
     if ($request->isMethod('post')) {
         if ($this->validate($request->getParameter('to_address'), '目的地')) {
             $b = new sfWebBrowser();
             $b->get(sfConfig::get('sf_google_geo_url'), array('output' => 'xml', 'sensor' => 'false', 'key' => sfConfig::get('sf_google_key'), 'q' => $request->getParameter('to_address')));
             $xml = new SimpleXMLElement($b->getResponseText());
             if ($this->geoCodeValidate($xml)) {
                 $this->viewList($request, $b, "toConfirm");
             }
         }
     } else {
         if ($request->getParameter('lat') != "" && $request->getParameter('lon') != "") {
             $lon = GpsConverter::dmsToDegree($this->getRequestParameter('lon'));
             $lat = GpsConverter::dmsToDegree($this->getRequestParameter('lat'));
             $b = new sfWebBrowser();
             $b->get(sfConfig::get('sf_google_geo_url'), array('output' => 'xml', 'sensor' => 'false', 'key' => sfConfig::get('sf_google_key'), 'll' => $lat . ',' . $lon));
             $this->viewList($request, $b, "toConfirm");
         }
     }
 }
Exemplo n.º 26
0
 public function executeAddBulk($request)
 {
     $this->checkEntity($request, false, false);
     $this->reference_form = new ReferenceForm();
     $this->reference_form->setSelectObject($this->entity);
     $this->add_bulk_form = new AddBulkForm();
     //get possible default categories
     $this->categories = LsDoctrineQuery::create()->select('c.name, c.name')->from('RelationshipCategory c')->orderBy('c.id')->fetchAll(PDO::FETCH_KEY_PAIR);
     array_unshift($this->categories, '');
     if ($request->isMethod('post') && in_array($request->getParameter('commit'), array('Begin', 'Continue'))) {
         if ($request->hasParameter('ref_id')) {
             $this->ref_id = $request->getParameter('ref_id');
         } else {
             $refParams = $request->getParameter('reference');
             $this->reference_form->bind($refParams);
             $restOfParams = (array) $request->getParameterHolder();
             $restOfParams = array_shift($restOfParams);
             $this->add_bulk_form->bind($restOfParams, $request->getFiles());
             if (!$this->reference_form->isValid() || !$this->add_bulk_form->isValid()) {
                 return;
             }
             if ($this->ref_id = $refParams['existing_source']) {
                 $ref = Doctrine::getTable('Reference')->find($this->ref_id);
                 $url = $ref->source;
             } else {
                 $ref = new Reference();
                 $ref->object_model = 'Entity';
                 $ref->object_id = $this->entity->id;
                 $ref->source = $refParams['source'];
                 $ref->name = $refParams['name'];
                 $ref->source_detail = $refParams['source_detail'];
                 $ref->publication_date = $refParams['publication_date'];
                 $ref->save();
             }
             $this->ref_id = $ref->id;
             $this->reference = $ref;
         }
         $verify_method = $request->getParameter('verify_method');
         if ($this->add_method = $request->getParameter('add_method')) {
             if ($this->add_method == 'scrape') {
                 //scrape ref url
                 //set names to confirm
                 $browser = new sfWebBrowser();
                 $entity_types = $request->getParameter('entity_types');
                 //FIND NAMES AT URL USING COMBO OF OPENCALAIS & LS CUSTOM HTML PARSING
                 if (!$browser->get($ref->source)->responseIsError()) {
                     $text = $browser->getResponseText();
                     $this->names = LsTextAnalysis::getHtmlEntityNames($text, $entity_types);
                     $text = LsHtml::findParagraphs($text);
                     $this->text = preg_replace('/<[^b][^>]*>/is', " ", $text);
                     $this->confirm_names = true;
                     return;
                 } else {
                     $request->setError('csv', 'problems finding names at that url');
                 }
             } else {
                 if ($this->add_method == 'upload') {
                     $file = $this->add_bulk_form->getValue('file');
                     $filename = 'uploaded_' . sha1($file->getOriginalName());
                     $extension = $file->getExtension($file->getOriginalExtension());
                     $filePath = sfConfig::get('sf_temp_dir') . '/' . $filename . $extension;
                     $file->save($filePath);
                     if ($filePath) {
                         if ($spreadsheetArr = LsSpreadsheet::parse($filePath)) {
                             $names = $spreadsheetArr['rows'];
                             if (!in_array('name', $spreadsheetArr['headers'])) {
                                 $request->setError('file', 'The file you uploaded could not be parsed properly because there is no "name" column.');
                                 return;
                             }
                             if (in_array('summary', $spreadsheetArr['headers'])) {
                                 foreach ($names as &$name) {
                                     $name['summary'] = str_replace(array('?', "'"), "'", $name['summary']);
                                     $name['summary'] = str_replace(array('?', '?', '"'), '"', $name['summary']);
                                     if (isset($name['title'])) {
                                         $name['description1'] = $name['title'];
                                     }
                                 }
                                 unset($name);
                             }
                         } else {
                             $request->setError('file', 'The file you uploaded could not be parsed properly.');
                             return;
                         }
                     } else {
                         $request->setError('file', 'You need to upload a file.');
                         return;
                     }
                 } else {
                     if ($this->add_method == 'summary') {
                         //parse summary for names
                         $this->text = $this->entity->summary;
                         $entity_types = $request->getParameter('entity_types');
                         $this->names = LsTextAnalysis::getTextEntityNames($this->text, $entity_types);
                         $this->confirm_names = true;
                         return;
                     } else {
                         if ($this->add_method == 'text') {
                             $manual_names = $request->getParameter('manual_names');
                             if ($manual_names && $manual_names != "") {
                                 $manual_names = preg_split('#[\\r\\n]+#', $manual_names);
                                 $manual_names = array_map('trim', $manual_names);
                                 $names = array();
                                 foreach ($manual_names as $name) {
                                     $names[] = array('name' => $name);
                                 }
                             } else {
                                 $request->setError('csv', 'You did not add names properly.');
                                 return;
                             }
                         } else {
                             if ($this->add_method == 'db_search') {
                                 $this->db_search = true;
                             }
                         }
                     }
                 }
             }
         }
         //intermediate scrape page -- takes confirmed names, builds names arr
         if ($confirmed_names = $request->getParameter('confirmed_names')) {
             $restOfParams = (array) $request->getParameterHolder();
             $restOfParams = array_shift($restOfParams);
             $this->add_bulk_form->bind($restOfParams, $request->getFiles());
             if (!$this->add_bulk_form->isValid()) {
                 $this->reference = Doctrine::getTable('reference')->find($this->ref_id);
                 $this->names = unserialize(stripslashes($request->getParameter('names')));
                 $this->confirm_names = true;
                 return;
             }
             $names = array();
             foreach ($confirmed_names as $cn) {
                 $names[] = array('name' => $cn);
             }
             $manual_names = $request->getParameter('manual_names');
             if ($manual_names && $manual_names != "") {
                 $manual_names = preg_split('#[\\r\\n]+#', $manual_names);
                 $manual_names = array_map('trim', $manual_names);
                 foreach ($manual_names as $name) {
                     $names[] = array('name' => $name);
                 }
             }
         }
         // LOAD IN RELATIONSHIP DEFAULTS
         if (isset($verify_method)) {
             $defaults = $request->getParameter('relationship');
             if ($verify_method == 'enmasse') {
                 $this->default_type = $request->getParameter('default_type');
                 $this->order = $request->getParameter('order');
                 $category_name = $request->getParameter('relationship_category_all');
                 $this->extensions = ExtensionDefinitionTable::getByTier(2, $this->default_type);
                 $extensions_arr = array();
                 foreach ($this->extensions as $ext) {
                     $extensions_arr[] = $ext->name;
                 }
             } else {
                 $category_name = $request->getParameter('relationship_category_one');
             }
             if ($category_name) {
                 $this->category_name = $category_name;
                 if (!($category = Doctrine::getTable('RelationshipCategory')->findOneByName($category_name))) {
                     $request->setError('csv', 'You did not select a relationship category.');
                     return;
                 }
                 $formClass = $category_name . 'Form';
                 $categoryForm = new $formClass(new Relationship());
                 $categoryForm->setDefaults($defaults);
                 $this->form_schema = $categoryForm->getFormFieldSchema();
                 if (in_array($category_name, array('Position', 'Education', 'Membership', 'Donation', 'Lobbying', 'Ownership'))) {
                     $this->field_names = array('description1', 'start_date', 'end_date', 'is_current');
                 } else {
                     $this->field_names = array('description1', 'description2', 'start_date', 'end_date', 'is_current');
                 }
                 $extraFields = array('Position' => array('is_board', 'is_executive'), 'Education' => array('degree_id'), 'Donation' => array('amount'), 'Transaction' => array('amount'), 'Lobbying' => array('amount'), 'Ownership' => array('percent_stake', 'shares'));
                 if (isset($extraFields[$category_name])) {
                     $this->field_names = array_merge($this->field_names, $extraFields[$category_name]);
                 }
             }
             $this->matches = array();
             // BOOT TO TOOLBAR OR LOOK FOR MATCHES FOR ENMASSE ADD
             if (isset($names) && count($names) > 0 || isset($this->db_search)) {
                 if ($verify_method == 'onebyone') {
                     if (isset($category_name)) {
                         $defaults['category'] = $category_name;
                     }
                     $toolbar_names = array();
                     foreach ($names as $name) {
                         $toolbar_names[] = $name['name'];
                     }
                     $this->getUser()->setAttribute('toolbar_names', $toolbar_names);
                     $this->getUser()->setAttribute('toolbar_entity', $this->entity->id);
                     $this->getUser()->setAttribute('toolbar_defaults', $defaults);
                     $this->getUser()->setAttribute('toolbar_ref', $this->ref_id);
                     $this->redirect('relationship/toolbar');
                 } else {
                     $this->category_name = $category_name;
                     if (isset($this->db_search)) {
                         $num = $request->getParameter('num', 10);
                         $page = $request->getParameter('page', 1);
                         $q = LsDoctrineQuery::create()->from('Entity e')->where('(e.summary rlike ? or e.blurb rlike ?)', array('[[:<:]]' . $this->entity->name . '[[:>:]]', '[[:<:]]' . $this->entity->name . '[[:>:]]'));
                         foreach ($this->entity->Alias as $alias) {
                             $q->orWhere('(e.summary rlike ? or e.blurb rlike ?)', array('[[:<:]]' . $alias->name . '[[:>:]]', '[[:<:]]' . $alias->name . '[[:>:]]'));
                         }
                         $q->setHydrationMode(Doctrine::HYDRATE_ARRAY);
                         $cat_id = constant('RelationshipTable::' . strtoupper($category_name) . '_CATEGORY');
                         $q->whereParenWrap();
                         $q->andWhere('NOT EXISTS (SELECT DISTINCT l.relationship_id FROM Link l ' . 'WHERE l.entity1_id = e.id AND l.entity2_id = ? AND l.category_id = ?)', array($this->entity['id'], $cat_id));
                         $summary_matches = $q->execute();
                         foreach ($summary_matches as $summary_match) {
                             $aliases = array();
                             foreach ($this->entity->Alias as $alias) {
                                 $aliases[] = LsString::escapeStringForRegex($alias->name);
                             }
                             $aliases = implode("|", $aliases);
                             $summary_match['summary'] = preg_replace('/(' . $aliases . ')/is', '<strong>$1</strong>', $summary_match['summary']);
                             $this->matches[] = array('search_results' => array($summary_match));
                         }
                     } else {
                         for ($i = 0; $i < count($names); $i++) {
                             if (isset($names[$i]['name']) && trim($names[$i]['name']) != '') {
                                 $name = $names[$i]['name'];
                                 $name_terms = $name;
                                 if ($this->default_type == 'Person') {
                                     $name_parts = preg_split('/\\s+/', $name);
                                     if (count($name_parts) > 1) {
                                         $name_terms = PersonTable::nameSearch($name);
                                     }
                                     $terms = $name_terms;
                                     $primary_ext = "Person";
                                 } else {
                                     if ($this->default_type == 'Org') {
                                         $name_terms = OrgTable::nameSearch($name);
                                         $terms = $name_terms;
                                         $primary_ext = "Org";
                                     } else {
                                         $terms = $name_terms;
                                         $primary_ext = null;
                                     }
                                 }
                                 $pager = EntityTable::getSphinxPager($terms, $page = 1, $num = 20, $listIds = null, $aliases = true, $primary_ext);
                                 $match = $names[$i];
                                 $match['search_results'] = $pager->execute();
                                 if (isset($names[$i]['types'])) {
                                     $types = explode(',', $names[$i]['types']);
                                     $types = array_map('trim', $types);
                                     $match['types'] = array();
                                     foreach ($types as $type) {
                                         if (in_array($type, $extensions_arr)) {
                                             $match['types'][] = $type;
                                         }
                                     }
                                 }
                                 $this->matches[] = $match;
                             }
                         }
                     }
                 }
             }
         }
     } else {
         if ($page = $this->getRequestParameter('page')) {
             $this->page = $page;
             $this->num = $this->getRequestParameter('num', 50);
         } else {
             if ($request->isMethod('post') && $request->getParameter('commit') == 'Submit') {
                 $this->ref_id = $this->getRequestParameter('ref_id');
                 $entity_ids = array();
                 $relationship_category = $this->getRequestParameter('category_name');
                 $order = $this->getRequestParameter('order');
                 $default_type = $request->getParameter('default_type');
                 $default_ref = Doctrine::getTable('Reference')->find($request->getParameter('ref_id'));
                 for ($i = 0; $i < $this->getRequestParameter('count'); $i++) {
                     if ($entity_id = $request->getParameter('entity_' . $i)) {
                         $selected_entity_id = null;
                         $relParams = $request->getParameter("relationship_" . $i);
                         if ($relParams['ref_name']) {
                             $ref['source'] = $relParams['ref_source'];
                             $ref['name'] = $relParams['ref_name'];
                         }
                         if ($entity_id == 'new') {
                             $name = $request->getParameter('new_name_' . $i);
                             if ($default_type == 'Person') {
                                 $new_entity = PersonTable::parseFlatName($name);
                             } else {
                                 $new_entity = new Entity();
                                 $new_entity->addExtension('Org');
                                 $new_entity->name = trim($name);
                             }
                             $new_entity->save();
                             $new_entity->blurb = $request->getParameter('new_blurb_' . $i);
                             $new_entity->summary = $request->getParameter('new_summary_' . $i);
                             if (!$ref) {
                                 $ref = $default_ref;
                             }
                             $new_entity->addReference($ref['source'], null, null, $ref['name']);
                             if ($types = $request->getParameter('new_extensions_' . $i)) {
                                 foreach ($types as $type) {
                                     $new_entity->addExtension($type);
                                 }
                             }
                             $new_entity->save();
                             $selected_entity_id = $new_entity->id;
                         } else {
                             if ($entity_id > 0) {
                                 $selected_entity_id = $entity_id;
                                 LsCache::clearEntityCacheById($selected_entity_id);
                             }
                         }
                         if ($selected_entity_id) {
                             $startDate = $relParams['start_date'];
                             $endDate = $relParams['end_date'];
                             unset($relParams['start_date'], $relParams['end_date'], $relParams['ref_name'], $relParams['ref_url']);
                             $rel = new Relationship();
                             $rel->setCategory($relationship_category);
                             if ($order == '1') {
                                 $rel->entity1_id = $this->entity['id'];
                                 $rel->entity2_id = $selected_entity_id;
                             } else {
                                 $rel->entity2_id = $this->entity['id'];
                                 $rel->entity1_id = $selected_entity_id;
                             }
                             //only set dates if valid
                             if ($startDate && preg_match('#^\\d{4}-\\d{2}-\\d{2}$#', Dateable::convertForDb($startDate))) {
                                 $rel->start_date = Dateable::convertForDb($startDate);
                             }
                             if ($endDate && preg_match('#^\\d{4}-\\d{2}-\\d{2}$#', Dateable::convertForDb($endDate))) {
                                 $rel->end_date = Dateable::convertForDb($endDate);
                             }
                             $rel->fromArray($relParams, null, $hydrateCategory = true);
                             if ($request->hasParameter('add_method') && $request->getParameter('add_method') == 'db_search') {
                                 $refs = EntityTable::getSummaryReferences($selected_entity_id);
                                 if (count($refs)) {
                                     $ref = $refs[0];
                                 } else {
                                     $refs = EntityTable::getAllReferencesById($selected_entity_id);
                                     if (count($refs)) {
                                         $ref = $refs[0];
                                     }
                                 }
                             }
                             if (!$ref) {
                                 $ref = $default_ref;
                             }
                             $rel->saveWithRequiredReference(array('source' => $ref['source'], 'name' => $ref['name']));
                             $ref = null;
                         }
                     }
                 }
                 $this->clearCache($this->entity);
                 $this->redirect($this->entity->getInternalUrl());
             } else {
                 if ($request->isMethod('post') && $request->getParameter('commit') == 'Cancel') {
                     $this->redirect($this->entity->getInternalUrl());
                 }
             }
         }
     }
 }
Exemplo n.º 27
0
 protected static function get($url)
 {
     $request = sfContext::getInstance()->request;
     $browser = new sfWebBrowser();
     try {
         if (true !== $browser->get($request->getUriPrefix() . $url)->responseIsError()) {
             // Successful response (e.g. 200, 201, etc.)
             return $browser->getResponseText();
         } else {
             // Error response (e.g. 404, 500, etc.)
             return false;
         }
     } catch (Exception $e) {
         // Adapter error [curl,fopen,fsockopen] (e.g. Host not found)
         return false;
     }
 }
Exemplo n.º 28
-1
 /**
  * Loads an image from a file or URL and creates an internal thumbnail out of it
  *
  * @param string filename (with absolute path) of the image to load. If the filename is a http(s) URL, then an attempt to download the file will be made.
  *
  * @return boolean True if the image was properly loaded
  * @throws Exception If the image cannot be loaded, or if its mime type is not supported
  */
 public function loadFile($image)
 {
     if (preg_match('/http(s)?:\\//i', $image)) {
         if (class_exists('sfWebBrowser')) {
             if (!is_null($this->tempFile)) {
                 unlink($this->tempFile);
             }
             $this->tempFile = tempnam('/tmp', 'sfThumbnailPlugin');
             $b = new sfWebBrowser();
             try {
                 $b->get($image);
                 if ($b->getResponseCode() != 200) {
                     throw new Exception(sprintf('%s returned error code %s', $image, $b->getResponseCode()));
                 }
                 file_put_contents($this->tempFile, $b->getResponseText());
                 if (!filesize($this->tempFile)) {
                     throw new Exception('downloaded file is empty');
                 } else {
                     $image = $this->tempFile;
                 }
             } catch (Exception $e) {
                 throw new Exception("Source image is a URL but it cannot be used because " . $e->getMessage());
             }
         } else {
             throw new Exception("Source image is a URL but sfWebBrowserPlugin is not installed");
         }
     } else {
         if (!is_readable($image)) {
             throw new Exception(sprintf('The file "%s" is not readable.', $image));
         }
     }
     $this->adapter->loadFile($this, $image);
 }