public function placeOrder(SS_HTTPRequest $request)
 {
     $eventbrite_event_header = $request->getHeader('X-Eventbrite-Event');
     if (!$eventbrite_event_header) {
         return $this->httpError(403);
     }
     if ($eventbrite_event_header !== 'order.placed') {
         return $this->httpError(403);
     }
     if (!$this->isJson()) {
         return $this->httpError(403);
     }
     $json_request = $this->getJsonRequest();
     if (!isset($json_request['config']) || !isset($json_request['api_url'])) {
         return $this->httpError(403);
     }
     $config = $json_request['config'];
     if (!isset($config['action']) || $config['action'] !== 'order.placed') {
         return $this->httpError(403);
     }
     $current_local_url = Controller::join_links(Director::absoluteBaseURL(), $request->getURL());
     if (!isset($config['endpoint_url']) || $config['endpoint_url'] !== $current_local_url) {
         return $this->httpError(403);
     }
     try {
         $this->manager->registerEvent('ORDER_PLACED', $json_request['api_url']);
     } catch (Exception $ex) {
         SS_Log::log($ex->getMessage(), SS_Log::ERR);
         return $this->httpError(500);
     }
     return true;
 }
 public function InstaTagMedia($tag = false, $num = false, $shuffle = true)
 {
     $instagram = new Instagram(array('apiKey' => $this->InstagramApiKey, 'apiSecret' => $this->InstagramApiSecret, 'apiCallback' => $this->InstagramApiCallback));
     $media = false;
     $output = false;
     $out = array();
     if (!$tag) {
         $tag = $this->InstagramSearchTerm;
     }
     if (!$num) {
         $num = $this->InstagramItemsCount;
     }
     try {
         $media = $instagram->getTagMedia($tag, 50);
     } catch (Exception $e) {
         SS_Log::log(new Exception(print_r($e, true)), SS_Log::ERR);
     }
     if (is_object($media) && isset($media->data)) {
         foreach ($media->data as $data) {
             if (is_object($data)) {
                 $item = array('caption' => $data->caption ? $data->caption->text : "", 'thumb' => $data->images->thumbnail->url, 'image' => $data->images->standard_resolution->url, 'username' => $data->user->username);
                 array_push($out, $item);
             }
         }
         if ($shuffle) {
             shuffle($out);
         }
         $output = ArrayList::create($out);
         $output = $output->limit($num);
     }
     return $output;
 }
 public function stageChildren($showAll = false)
 {
     $children = new ArrayList();
     $repo = $this->source->getRemoteRepository();
     try {
         if ($repo->isConnected()) {
             $ssId = $this->getSS_ID();
             if (!$ssId) {
                 $ssId = '0';
             }
             $kids = $repo->getChildren(array('ClassName' => ClassInfo::baseDataClass($this->getType()), 'ParentID' => $this->getSS_ID()));
             if (!$kids) {
                 throw new Exception("No kids and null object returned for children of " . $this->getSS_ID());
             }
             // Even though it returns actual dataobjects, we need to wrap them for sanity and safety's sake
             foreach ($kids as $childItem) {
                 $item = $this->source->getObject($childItem);
                 $children->push($item);
             }
         }
     } catch (Exception $fre) {
         SS_Log::log($fre, SS_Log::WARN);
         return $children;
     }
     return $children;
 }
 /** Send the email out to the Recipient */
 public function send($newsletter = null, $recipient = null)
 {
     // fetch from database again to make sure the sent flag is not set yet
     if (!$this->ID || self::get()->byID($this->ID)->Status != 'Sent') {
         if (empty($newsletter)) {
             $newsletter = $this->Newsletter();
         }
         if (empty($recipient)) {
             $recipient = $this->Recipient();
         }
         //check recipient not blacklisted and verified
         if ($recipient && empty($recipient->Blacklisted) && !empty($recipient->Verified)) {
             $email = new NewsLetterEmail($newsletter, $recipient);
             if (!empty($newsletter->ReplyTo)) {
                 $email->addCustomHeader('Reply-To', $newsletter->ReplyTo);
             }
             $success = $email->send();
             if ($success) {
                 $this->Status = 'Sent';
                 $recipient->ReceivedCount = $recipient->ReceivedCount + 1;
             } else {
                 $this->Status = 'Failed';
                 $recipient->BouncedCount = $recipient->BouncedCount + 1;
             }
             $recipient->write();
         } else {
             $this->Status = 'BlackListed';
         }
         $this->write();
     } else {
         SS_Log::log(new Exception("prevented sending of SendRecipientQueue #{$this->ID} because it has already been sent"), SS_Log::ERR);
     }
 }
 /**
  * Get the logger currently in use, or create a new
  * one if it doesn't exist.
  * 
  * @return object
  */
 public static function get_logger()
 {
     if (!self::$logger) {
         self::$logger = new self::$logger_class();
     }
     return self::$logger;
 }
 public function process()
 {
     $post = $this->getObject();
     if ($post) {
         $author = $post->Owner();
         $balance = $author->Balance;
         if (self::$api_key && $post->Content != self::SPAM_CONTENT) {
             require_once Director::baseFolder() . '/microblog/thirdparty/defensio/Defensio.php';
             $defensio = new Defensio(self::$api_key);
             $document = array('type' => 'comment', 'content' => $post->Content, 'platform' => 'silverstripe_microblog', 'client' => 'MicroBlog Defensio-PHP | 0.1 | Marcus Nyeholt | marcus@silverstripe.com.au', 'async' => 'false');
             try {
                 $result = $defensio->postDocument($document);
                 if ($result && isset($result[1])) {
                     if ($result[1]->allow == 'false') {
                         $post->Content = self::SPAM_CONTENT;
                         $post->Down += self::SPAM_DOWN;
                         $post->write();
                         $author->Down += self::SPAM_DOWN;
                         $author->write();
                     }
                 }
             } catch (Exception $e) {
                 SS_Log::log($e, SS_Log::WARN);
             }
         }
         if ($post->Content != self::SPAM_CONTENT) {
             $post->analyseContent();
             $post->write();
         }
     }
     $this->isComplete = true;
 }
 public function getLocationsByDay(SS_HTTPRequest $request)
 {
     try {
         $query_string = $request->getVars();
         $summit_id = intval($request->param('SUMMIT_ID'));
         $day = strtolower(Convert::raw2sql($query_string['day']));
         $summit = $this->summit_repository->getById($summit_id);
         if (is_null($summit)) {
             throw new NotFoundEntityException('Summit', sprintf(' id %s', $summit_id));
         }
         if (!$summit->isDayBelongs($day)) {
             throw new EntityValidationException(sprintf('day %s does not belongs to summit id %s', $day, $summit_id));
         }
         $response = array('day' => $day, 'summit_id' => intval($summit_id), 'locations' => array());
         foreach ($summit->getTopVenues() as $venue) {
             $class_name = $venue->ClassName;
             if ($class_name != 'SummitVenue' && $class_name != 'SummitExternalLocation' && $class_name != 'SummitHotel') {
                 continue;
             }
             $count = $summit->getPublishedEventsCountByDateLocation($day, $venue);
             array_push($response['locations'], array('id' => intval($venue->ID), 'events_count' => intval($count)));
             if ($class_name == 'SummitVenue') {
                 foreach ($venue->Rooms() as $room) {
                     $count = $summit->getPublishedEventsCountByDateLocation($day, $room);
                     array_push($response['locations'], array('id' => intval($room->ID), 'events_count' => intval($count)));
                 }
             }
         }
         return $this->ok($response);
     } catch (Exception $ex) {
         SS_Log::log($ex->getMessage(), SS_Log::ERR);
         return $this->serverError();
     }
 }
 /**
  *	Attempt to regenerate the current security token.
  */
 public function regenerateToken()
 {
     // Restrict this functionality to administrators.
     $user = Member::currentUserID();
     if (Permission::checkMember($user, 'ADMIN')) {
         // Attempt to create a random hash.
         $regeneration = $this->service->generateHash();
         if ($regeneration) {
             // Instantiate the new security token.
             $token = APIwesomeToken::create();
             $token->Hash = $regeneration['hash'];
             $token->AdministratorID = $user;
             $token->write();
             // Temporarily use the session to display the new security token key.
             Session::set('APIwesomeToken', "{$regeneration['key']}:{$regeneration['salt']}");
         } else {
             // Log the failed security token regeneration.
             SS_Log::log('APIwesome security token regeneration failed.', SS_Log::ERR);
             Session::set('APIwesomeToken', -1);
         }
         // Determine where the request came from.
         $from = $this->getRequest()->getVar('from');
         $redirect = $from ? $from : 'admin/json-xml/';
         return $this->redirect($redirect);
     } else {
         return $this->httpError(404);
     }
 }
 /**
  * Send a notification directly to a single user
  *
  * @param SystemNotification $notification
  * @param string $email
  * @param array $data
  */
 public function sendToUser($notification, $context, $user, $data)
 {
     $subject = $notification->format($notification->Title, $context, $user, $data);
     if (Config::inst()->get('SystemNotification', 'html_notifications')) {
         $message = $notification->format($notification->NotificationContent(), $context, $user, $data);
     } else {
         $message = $notification->format(nl2br($notification->NotificationContent()), $context, $user, $data);
     }
     if ($template = $notification->getTemplate()) {
         $templateData = $notification->getTemplateData($context, $user, $data);
         $templateData->setField('Body', $message);
         try {
             $body = $templateData->renderWith($template);
         } catch (Exception $e) {
             $body = $message;
         }
     } else {
         $body = $message;
     }
     $from = $this->config()->get('send_notifications_from');
     $to = $user->Email;
     if (!$to && method_exists($user, 'getEmailAddress')) {
         $to = $user->getEmailAddress();
     }
     // log
     $message = "Sending {$subject} to {$to}";
     SS_Log::log($message, SS_Log::NOTICE);
     // send
     $email = new Email($from, $to, $subject);
     $email->setBody($body);
     $this->extend('onBeforeSendToUser', $email);
     $email->send();
 }
 function StartSurvey($data, $form)
 {
     try {
         $data = SQLDataCleaner::clean($data);
         $data['MembershipType'] = 'community';
         Session::set("FormInfo.{$form->FormName()}.data", $data);
         $profile_page = EditProfilePage::get()->first();
         $member = $this->member_manager->registerMobile($data, new MemberRegistrationSenderService());
         //Get profile page
         if (!is_null($profile_page)) {
             //Redirect to profile page with success message
             Session::clear("FormInfo.{$form->FormName()}.data");
             $request = Controller::curr()->getRequest();
             $back_url = $request->postVar('BackURL');
             $link = $profile_page->Link('?success=1');
             if (!empty($back_url)) {
                 $link .= "&BackURL=" . $back_url;
             }
             return OpenStackIdCommon::loginMember($member, $link);
         }
     } catch (EntityValidationException $ex1) {
         Form::messageForForm($form->FormName(), $ex1->getMessage(), 'bad');
         //Return back to form
         SS_Log::log($ex1->getMessage(), SS_Log::WARN);
         return Controller::curr()->redirectBack();
     } catch (Exception $ex) {
         Form::messageForForm($form->FormName(), "There was an error with your request, please contact your admin.", 'bad');
         //Return back to form
         SS_Log::log($ex->getMessage(), SS_Log::ERR);
         return Controller::curr()->redirectBack();
     }
 }
 protected function addressFromIP($ip)
 {
     $geocoder = AddressGeocoding::get_geocoder();
     $geodata = array();
     try {
         if ($ip) {
             $geodata = $geocoder->geocode($ip)->toArray();
         }
     } catch (Exception $e) {
         SS_Log::log($e, SS_Log::ERR);
     }
     $geodata = array_filter($geodata);
     $datamap = array('Country' => 'countryCode', 'County' => 'county', 'State' => 'region', 'PostalCode' => 'zipcode', 'Latitude' => 'latitude', 'Longitude' => 'longitude');
     $mappeddata = array();
     foreach ($datamap as $addressfield => $geofield) {
         if (is_array($geofield)) {
             if ($data = implode(" ", array_intersect_key($geodata, array_combine($geofield, $geofield)))) {
                 $mappeddata[$addressfield] = $data;
             }
         } elseif (isset($geodata[$geofield])) {
             $mappeddata[$addressfield] = $geodata[$geofield];
         }
     }
     return $mappeddata;
 }
 /**
  * Store the contents of a folder on a CDN. 
  * 
  * If processReferences is set, relative URL references are attempted to be 
  * detected and stored remotely as well, with the file to be stored rewritten 
  * to refer to the CDN value. This really is only useful for CSS 
  *
  * @param string $folder
  * @param boolean $processReferences 
  */
 public function storeThemeFile($toCdn, $file, $forceUpdate = false, $processReferences = false)
 {
     $mtime = @filemtime($file);
     $relativeName = self::CDN_THEME_PREFIX . '/' . $mtime . '/' . trim(str_replace(Director::baseFolder(), '', $file), '/');
     if (!$forceUpdate) {
         // see if the file already exists, if not we do NOT do an update
         $reader = $this->contentService->findReaderFor($toCdn, $relativeName);
         if ($reader && $reader->exists()) {
             return $reader->getURL();
         }
     }
     $clear = false;
     if ($processReferences) {
         $clear = true;
         $file = $this->processFileReferences($toCdn, $file, $forceUpdate);
     }
     // otherwise, lets get a content writer
     $writer = $this->contentService->getWriter($toCdn);
     try {
         $writer->write($file, $relativeName);
     } catch (Exception $e) {
         SS_Log::log($e, SS_Log::WARN);
     }
     if ($clear && strpos($file, '.cdn') > 0) {
         @unlink($file);
     }
     $id = $writer->getContentId();
     return $writer->getReader()->getURL();
 }
 /**
  * @return void
  */
 public function run()
 {
     try {
         $init_time = time();
         $processed_events = 0;
         $events = array();
         $current_summit = Summit::get_active();
         if ($current_summit) {
             $events = $current_summit->getSchedule();
         }
         foreach ($events as $event) {
             $processed_events++;
             $rate_sum = 0;
             $rate_count = 0;
             foreach ($event->Feedback as $feedback) {
                 $rate_count++;
                 $rate_sum = $rate_sum + $feedback->Rate;
             }
             $rate_avg = $rate_count > 0 ? $rate_sum / $rate_count : 0;
             try {
                 $event->setAvgRate(round($rate_avg, 2));
                 $event->write(true);
             } catch (Exception $ex) {
                 SS_Log::log($ex, SS_Log::ERR);
                 echo $ex->getMessage();
             }
         }
         $finish_time = time() - $init_time;
         echo 'processed events ' . $processed_events . ' - time elapsed : ' . $finish_time . ' seconds.';
     } catch (Exception $ex) {
         SS_Log::log($ex->getMessage(), SS_Log::ERR);
     }
 }
 function run()
 {
     try {
         $election_input_path = Director::baseFolder() . '/' . ELECTION_VOTERS_INGEST_PATH;
         $files = scandir($election_input_path);
         $manager = new ElectionManager(new SapphireElectionRepository(), new SapphireFoundationMemberRepository(), new SapphireVoteRepository(), new SapphireVoterFileRepository(), new VoteFactory(), new VoterFileFactory(), new ElectionFactory(), SapphireTransactionManager::getInstance());
         foreach ($files as $file_name) {
             if ($this->isCSV($file_name) && (list($election_id, $open_date, $close_date) = $this->isValidElectionFileName($file_name))) {
                 try {
                     echo printf('processing file %s' . PHP_EOL, $file_name);
                     list($count, $not_processed) = $manager->ingestVotersForElection($election_input_path . '/' . $file_name, $election_id, $open_date, $close_date);
                     echo printf('file %s - processed %d rows - not processed %d rows' . PHP_EOL, $file_name, $count, count($not_processed));
                     if (count($not_processed) > 0) {
                         echo 'not processed details ... ' . PHP_EOL;
                         echo var_dump($not_processed) . PHP_EOL;
                     }
                     echo printf('deleting file %s ...' . PHP_EOL, $file_name);
                     unlink($election_input_path . '/' . $file_name);
                 } catch (Exception $ex) {
                     SS_Log::log($ex, SS_Log::ERR);
                     echo $ex->getMessage();
                 }
             }
         }
         return 'OK';
     } catch (Exception $ex) {
         SS_Log::log($ex, SS_Log::ERR);
         echo $ex->getMessage();
     }
 }
 /**
  * Implement this method in the task subclass to
  * execute via the TaskRunner
  */
 public function run($request)
 {
     if (!($adminEmail = $this->config()->get('administrator_email'))) {
         $contenders = $this->extend('feedMeAdminEmail') ?: [];
         $adminEmail = reset($contenders);
     }
     if ($adminEmail) {
         SS_Log::add_writer(new SS_LogEmailWriter($adminEmail, SS_Log::INFO));
     }
     // anything like a warning or above
     SS_Log::add_writer(new SS_LogEmailWriter(Security::findAnAdministrator()->Email), SS_Log::WARN);
     $excludedFeedClasses = $this->config()->get('excluded_feed_class_names');
     // for each implementor of the FeedMeFeedInterface check if it's not excluded then for each
     // instance of that model call feedMeImport on it.
     $implementors = ClassInfo::implementorsOf('FeedMeFeedModelInterface');
     foreach ($implementors as $className) {
         // chance to disable a feed by setting config.excluded_feed_class_names
         if (!in_array($className, $excludedFeedClasses)) {
             /** @var FeedMeFeedModelExtension $feedModel */
             foreach ($className::get() as $feedModel) {
                 $feedModel->feedMeImport();
             }
         }
     }
 }
 /**
  * @return void
  */
 public function run()
 {
     try {
         $batch_size = 100;
         $init_time = time();
         $summit = null;
         if (isset($_GET['batch_size'])) {
             $batch_size = intval(trim(Convert::raw2sql($_GET['batch_size'])));
             echo sprintf('batch_size set to %s', $batch_size) . PHP_EOL;
         }
         if (isset($_GET['summit_id'])) {
             $summit = Summit::get()->byID(intval($_GET['summit_id']));
         }
         if (is_null($summit)) {
             throw new Exception('summit_id is not valid!');
         }
         $manager = Injector::inst()->get('SpeakerSecondBreakoutAnnouncementSenderManager');
         if (!$manager instanceof ISpeakerSecondBreakoutAnnouncementSenderManager) {
             return;
         }
         $processed = $manager->send($summit, $batch_size);
         $finish_time = time() - $init_time;
         echo 'processed records ' . $processed . ' - time elapsed : ' . $finish_time . ' seconds.';
     } catch (Exception $ex) {
         SS_Log::log($ex->getMessage(), SS_Log::ERR);
     }
 }
 /**
  *
  * @param array $data
  * @param array $services
  */
 public function sendToSocialMedia(array $data, array $services = array('facebook', 'twitter'))
 {
     // init output
     $ids = array('facebook' => null, 'twitter' => null);
     // Facebook
     if (in_array('facebook', $services) && $this->confirmFacebookAccess()) {
         $facebook = new Facebook(array('appId' => static::$conf->FacebookAppId, 'secret' => static::$conf->FacebookAppSecret));
         $facebook->setAccessToken(static::$conf->FacebookPageAccessToken);
         try {
             $post_id = $facebook->api("/" . static::$conf->FacebookPageId . "/feed", "post", $data);
             $ids['facebook'] = $post_id['id'];
         } catch (FacebookApiException $e) {
             SS_Log::log('Error ' . $e->getCode() . ' : ' . $e->getFile() . ' Line ' . $e->getLine() . ' : ' . $e->getMessage() . "\n" . 'BackTrace: ' . "\n" . $e->getTraceAsString(), SS_Log::ERR);
         }
     }
     // Twitter
     if (in_array('twitter', $services) && $this->confirmTwitterAccess()) {
         $connection = new tmhOAuth(array('consumer_key' => static::$conf->TwitterConsumerKey, 'consumer_secret' => static::$conf->TwitterConsumerSecret, 'user_token' => static::$conf->TwitterOAuthToken, 'user_secret' => static::$conf->TwitterOAuthSecret));
         $tweet = $data['name'] . ": " . $data['link'];
         $code = $connection->request('POST', $connection->url('1.1/statuses/update'), array('status' => $tweet));
         if ($code == 200) {
             $data = json_decode($connection->response['response']);
             $ids['twitter'] = $data->id_str;
         }
     }
     return $ids;
 }
 public function transform($item, $parentObject, $duplicateStrategy)
 {
     $newFile = $this->getTypeForFile($item->Name);
     $folderPath = $parentObject->getRelativePath();
     $parentId = $parentObject ? $parentObject->ID : 0;
     $filter = 'ParentID = \'' . Convert::raw2sql($parentId) . '\' and Title = \'' . Convert::raw2sql($item->Name) . '\'';
     $existing = DataObject::get_one('File', $filter);
     if ($existing && $duplicateStrategy == ExternalContentTransformer::DS_SKIP) {
         // just return the existing children
         return new TransformResult($existing, null);
     } else {
         if ($existing && $duplicateStrategy == ExternalContentTransformer::DS_OVERWRITE) {
             $newFile = $existing;
         }
     }
     //
     $newFile->Name = $item->Name;
     $newFile->Title = $item->Name;
     $newFile->MenuTitle = $item->Name;
     //
     $size = filesize($item->FilePath);
     $details = array('size' => $size, 'name' => $item->Name, 'tmp_name' => $item->FilePath);
     $upload = new FileLoader();
     $folderPath = trim(substr($folderPath, strpos($folderPath, '/')), '/');
     try {
         $upload->loadIntoFile($details, $newFile, $folderPath);
     } catch (ValidationException $ve) {
         // ignore for now, there should really be a proper error reporting mechanism though...
         SS_Log::log("File import failed: " . $ve->getMessage(), SS_Log::WARN);
     }
     return new TransformResult($newFile, null);
 }
 public function confirm()
 {
     parent::init();
     try {
         $token = Session::get('SummitConfirmSpeakerPage.Token');
         if (isset($_REQUEST['t'])) {
             $token = base64_decode($_REQUEST['t']);
             Session::set('SummitConfirmSpeakerPage.Token', $token);
             return $this->redirect($this->Link('confirm'));
         }
         if (empty($token)) {
             throw new InvalidArgumentException('missing token!');
         }
         $request = PresentationSpeakerSummitAssistanceConfirmationRequest::get()->filter('ConfirmationHash', PresentationSpeakerSummitAssistanceConfirmationRequest::HashConfirmationToken($token))->first();
         if (is_null($request)) {
             throw new NotFoundEntityException('PresentationSpeakerSummitAssistanceConfirmationRequest', '');
         }
         if (!$request->alreadyConfirmed()) {
             $request->confirm($token);
             $request->write();
         }
         $data['Speaker'] = $request->Speaker();
         $data['Summit'] = $request->Summit();
         Session::set('Current.PresentationSpeakerSummitAssistanceConfirmationRequest', $request);
         return $this->customise($data)->renderWith(array('SummitConfirmSpeakerPage', 'SummitPage'), $this->parent);
     } catch (Exception $ex) {
         SS_Log::log($ex->getMessage(), SS_Log::WARN);
         return $this->httpError(404, 'Sorry, this speaker confirmation token does not seem to be correct.');
     }
 }
 public function init()
 {
     parent::init();
     global $databaseConfig;
     SS_Log::log(new Exception(print_r($databaseConfig, true)), SS_Log::NOTICE);
     $this->dbType = $databaseConfig['type'];
     $_REQUEST['showqueries'] = 1;
 }
 public function testLogsError()
 {
     $logger = new TestWorkableLogger();
     SS_Log::add_writer($logger);
     $result = Workable::create()->getJobs(['state' => 'fail']);
     $this->assertNotNull($logger->event);
     SS_Log::remove_writer($logger);
 }
 function log($message, $level = null)
 {
     if (!$level) {
         $level = SS_Log::NOTICE;
     }
     $message = array('errno' => '', 'errstr' => $message, 'errfile' => dirname(__FILE__), 'errline' => '', 'errcontext' => '');
     SS_Log::log($message, $level);
 }
 public function connect()
 {
     // check we have a valid session
     $appId = Config::inst()->get('FacebookControllerExtension', 'app_id');
     $secret = Config::inst()->get('FacebookControllerExtension', 'api_secret');
     $session = $this->getFacebookHelper()->getSessionFromRedirect();
     if ($session) {
         $token = $session->getAccessToken();
         // get a long lived token by default. Access token is saved in
         // session.
         try {
             $long = $token->extend($appId, $secret);
             if ($long) {
                 $accessTokenValue = (string) $long;
             } else {
                 $accessTokenValue = (string) $token;
             }
         } catch (Exception $e) {
             $accessTokenValue = (string) $token;
         }
         try {
             Session::set(FacebookControllerExtension::FACEBOOK_ACCESS_TOKEN, $accessTokenValue);
             $fields = Config::inst()->get('FacebookControllerExtension', 'facebook_fields');
             $user = (new FacebookRequest($session, 'GET', '/me', array('fields' => implode(',', $fields))))->execute()->getGraphObject(GraphUser::className());
             if (!($member = Member::currentUser())) {
                 // member is not currently logged into SilverStripe. Look up
                 // for a member with the UID which matches first.
                 $member = Member::get()->filter(array("FacebookUID" => $user->getId()))->first();
                 if (!$member) {
                     // see if we have a match based on email. From a
                     // security point of view, users have to confirm their
                     // email address in facebook so doing a match up is fine
                     $email = $user->getProperty('email');
                     if ($email) {
                         $member = Member::get()->filter(array('Email' => $email))->first();
                     }
                 }
                 if (!$member) {
                     $member = Injector::inst()->create('Member');
                 }
             }
             $member->syncFacebookDetails($user);
             $member->logIn();
             // redirect the user to the provided url, otherwise take them
             // back to the route of the website.
             if ($url = Session::get(FacebookControllerExtension::SESSION_REDIRECT_URL_FLAG)) {
                 return $this->redirect($url);
             } else {
                 return $this->redirect(Director::absoluteBaseUrl());
             }
         } catch (Exception $e) {
             SS_Log::log($e, SS_Log::ERR);
         }
     } else {
         return $this->httpError(400);
     }
     return $this->httpError(400);
 }
 /**
  * Logs with an arbitrary level.
  *
  * @param mixed   $level    PSR-3 log level constant, or equivalent string
  * @param string  $message  Message to log, may contain a { placeholder }
  * @param array   $context  Variables to replace { placeholder }
  * @return null
  */
 public function log($level, $message, array $context = array())
 {
     parent::log($level, $message, $context);
     // if we have a stack context which is the Exception that was thrown,
     // send that to SS_Log so writers can use that for reporting the error.
     if (!empty($context['stack'])) {
         SS_Log::log($context['stack'], $this->convertLevel($level));
     }
 }
 function up()
 {
     echo "Starting Migration Proc ...<BR>";
     //check if migration already had ran ...
     $migration = Migration::get()->filter('Name', $this->title)->first();
     $promo_code_type = isset($_REQUEST['promo_code_type']) ? intval($_REQUEST['promo_code_type']) : null;
     $promo_code_file = isset($_REQUEST['promo_code_file']) ? $_REQUEST['promo_code_file'] : null;
     if (is_null($promo_code_type)) {
         echo 'ERROR - promo_code_type param missing!';
         exit;
     }
     if (is_null($promo_code_file)) {
         echo 'ERROR - promo_code_file param missing!';
         exit;
     }
     $base_path = ASSETS_PATH;
     $file_path = $base_path . '/' . $promo_code_file;
     $type = explode(".", $file_path);
     if (!strtolower(end($type)) == 'csv') {
         echo 'ERROR - file hast not a csv extension!';
         exit;
     }
     if (!file_exists($file_path)) {
         echo sprintf('ERROR - %s file does not exists!', $file_path);
         exit;
     }
     $reader = new CSVReader($file_path);
     $row = 0;
     do {
         $line = $reader->getLine();
         if ($line) {
             ++$row;
             if ($row === 1) {
                 continue;
             }
             // skip header ...
             switch ($promo_code_type) {
                 case 1:
                     $type = 'ACCEPTED';
                     break;
                 case 2:
                     $type = 'ALTERNATE';
                     break;
             }
             $code = new SpeakerSummitRegistrationPromoCode();
             $code->Code = $line[0];
             $code->Type = $type;
             $code->SummitID = Summit::get_active()->ID;
             try {
                 $code->write();
             } catch (Exception $ex) {
                 SS_Log::log($ex->getMessage(), SS_Log::ERR);
             }
         }
     } while ($line);
     echo "Ending  Migration Proc ...<BR>";
 }
 function loadDataFrom($data, $clearMissingFields = false, $fieldList = null)
 {
     $res = parent::loadDataFrom($data, $clearMissingFields, $fieldList);
     // Check if the honeypot has been filled out
     if (is_array($data) && isset($data[self::FieldName]) && $data[self::FieldName] != '') {
         SS_Log::log(sprintf('honeypot triggered (data: %s)', http_build_query($data)), SS_Log::NOTICE);
         return $this->httpError(403);
     }
     return $res;
 }
 public static function current($request)
 {
     try {
         $token = AuthFactory::get_token($request);
         return self::get_member_from_token($token);
     } catch (\Exception $e) {
         \SS_Log::log($e->getMessage(), \SS_Log::INFO);
     }
     return false;
 }
 function run()
 {
     try {
         $manager = new JobRegistrationRequestManager(new SapphireJobRegistrationRequestRepository(), new SapphireJobRepository(), new SapphireJobAlertEmailRepository(), new JobFactory(), new JobsValidationFactory(), new SapphireJobPublishingService(), SapphireTransactionManager::getInstance());
         $manager->makePurge();
         return 'OK';
     } catch (Exception $ex) {
         SS_Log::log($ex, SS_Log::ERR);
         echo $ex->getMessage();
     }
 }
 function testRemoveWriter()
 {
     SS_Log::remove_writer($this->testEmailWriter);
     $writers = SS_Log::get_writers();
     $this->assertType('array', $writers);
     $this->assertEquals(1, count($writers));
     SS_Log::remove_writer($this->testFileWriter);
     $writers = SS_Log::get_writers();
     $this->assertType('array', $writers);
     $this->assertEquals(0, count($writers));
 }
 /**
  * @return void
  */
 public function run()
 {
     try {
         $init_time = time();
         $processed = $this->manager->processFiles();
         $finish_time = time() - $init_time;
         echo 'processed records ' . $processed . ' - time elapsed : ' . $finish_time . ' seconds.';
     } catch (Exception $ex) {
         SS_Log::log($ex->getMessage(), SS_Log::ERR);
     }
 }