public function newAction(Request $request)
 {
     $locationType = $this->get('campaignchain.core.form.type.location');
     $locationType->setBundleName('campaignchain/location-website');
     $locationType->setModuleIdentifier('campaignchain-website');
     $form = $this->createFormBuilder()->add('URL', 'url', array('label' => 'Website URL', 'constraints' => array(new Url(array('checkDNS' => true)))))->getForm();
     $form->handleRequest($request);
     if ($form->isValid()) {
         $locationURL = $form->getData()['URL'];
         $locationName = ParserUtil::getHTMLTitle($locationURL, $locationURL);
         $locationService = $this->get('campaignchain.core.location');
         $locationModule = $locationService->getLocationModule('campaignchain/location-website', 'campaignchain-website');
         $location = new Location();
         $location->setLocationModule($locationModule);
         $location->setName($locationName);
         $location->setUrl($locationURL);
         // Get the Website's favicon as Channel image if possible.
         $favicon = ParserUtil::getFavicon($locationURL);
         if ($favicon) {
             $locationImage = $favicon;
         } else {
             //                $locationImage = $this->container->get('templating.helper.assets')
             //                    ->getUrl(
             //                        'bundles/campaignchainlocationwebsite/images/icons/256x256/website.png',
             //                        null
             //                    );
             $locationImage = null;
         }
         $location->setImage($locationImage);
         $wizard = $this->get('campaignchain.core.channel.wizard');
         $wizard->setName($location->getName());
         $repository = $this->getDoctrine()->getRepository('CampaignChainCoreBundle:Location');
         if (!$repository->findBy(array('url' => $location->getUrl()))) {
             $wizard->addLocation($location->getUrl(), $location);
             try {
                 $channel = $wizard->persist();
                 $wizard->end();
                 $this->get('session')->getFlashBag()->add('success', "The Website '" . $location->getUrl() . "' has been connected.");
                 return $this->redirect($this->generateUrl('campaignchain_core_location'));
             } catch (\Exception $e) {
                 $this->addFlash('warning', "An error occured during the creation of the website location");
                 $this->get('logger')->addError($e->getMessage());
             }
         } else {
             $this->addFlash('warning', "The website  '" . $location->getUrl() . "' already exists.");
         }
     }
     //return $this->redirect($this->generateUrl(
     //  'campaignchain_channel_website_page_new',
     //array('id' => $channel->getLocations()[0]->getId())));
     return $this->render('CampaignChainCoreBundle:Base:new.html.twig', array('page_title' => 'Connect Website', 'form' => $form->createView()));
 }
 public function loginAction(Request $request)
 {
     $oauth = $this->get('campaignchain.security.authentication.client.oauth.authentication');
     $status = $oauth->authenticate(self::RESOURCE_OWNER, $this->applicationInfo);
     $profile = $oauth->getProfile();
     if ($status) {
         try {
             $em = $this->getDoctrine()->getManager();
             $em->getConnection()->beginTransaction();
             $wizard = $this->get('campaignchain.core.channel.wizard');
             $wizard->setName($profile->displayName);
             // Get the location module.
             $locationService = $this->get('campaignchain.core.location');
             $locationModule = $locationService->getLocationModule(self::LOCATION_BUNDLE, self::LOCATION_MODULE);
             $location = new Location();
             $location->setIdentifier($profile->identifier);
             $location->setName($profile->displayName);
             $location->setLocationModule($locationModule);
             $wizard->addLocation($location->getIdentifier(), $location);
             $channel = $wizard->persist();
             $wizard->end();
             $oauth->setLocation($channel->getLocations()[0]);
             $user = new CitrixUser();
             $user->setLocation($channel->getLocations()[0]);
             $user->setIdentifier($profile->identifier);
             $user->setDisplayName($profile->displayName);
             $user->setFirstName($profile->firstName);
             $user->setLastName($profile->lastName);
             $user->setEmail($profile->email);
             $em->persist($user);
             $em->flush();
             $em->getConnection()->commit();
             $this->get('session')->getFlashBag()->add('success', 'The Citrix location <a href="#">' . $profile->displayName . '</a> was connected successfully.');
         } catch (\Exception $e) {
             $em->getConnection()->rollback();
             throw $e;
         }
     } else {
         $this->get('session')->getFlashBag()->add('warning', 'A location has already been connected for this Citrix account.');
     }
     return $this->render('CampaignChainChannelCitrixBundle:Create:login.html.twig', array('redirect' => $this->generateUrl('campaignchain_core_location')));
 }
 public function execute(Location $location)
 {
     // Set HTML title as Location name.
     $location->setName('Form on ' . ParserUtil::getHTMLTitle($location->getUrl()));
     // Set the Website page module as the Location module.
     $locationModule = $this->locationService->getLocationModule('campaignchain/location-website', 'campaignchain-website-form');
     $location->setLocationModule($locationModule);
     // Set the image.
     $location->setImage($this->assetsHelper->getUrl('bundles/campaignchainlocationwebsite/images/icons/256x256/form.png', null));
     return $location;
 }
 public function loginAction()
 {
     $oauth = $this->get('campaignchain.security.authentication.client.oauth.authentication');
     $status = $oauth->authenticate(self::RESOURCE_OWNER, $this->applicationInfo);
     $profile = $oauth->getProfile();
     if ($status) {
         try {
             $em = $this->getDoctrine()->getManager();
             $em->getConnection()->beginTransaction();
             $wizard = $this->get('campaignchain.core.channel.wizard');
             $wizard->setName($profile->displayName);
             // Get the location module.
             $locationService = $this->get('campaignchain.core.location');
             $locationModule = $locationService->getLocationModule('campaignchain/location-twitter', 'campaignchain-twitter-user');
             $location = new Location();
             $location->setIdentifier($profile->identifier);
             $location->setName($profile->displayName);
             $location->setLocationModule($locationModule);
             $location->setImage($profile->photoURL);
             $location->setUrl($profile->profileURL);
             $wizard->addLocation($location->getIdentifier(), $location);
             $channel = $wizard->persist();
             $wizard->end();
             $oauth->setLocation($channel->getLocations()[0]);
             $twitterUser = new TwitterUser();
             $twitterUser->setLocation($channel->getLocations()[0]);
             $twitterUser->setIdentifier($profile->identifier);
             $twitterUser->setDisplayName($profile->firstName);
             $twitterUser->setUsername($profile->displayName);
             $twitterUser->setProfileImageUrl($profile->photoURL);
             $twitterUser->setProfileUrl($profile->profileURL);
             $em->persist($twitterUser);
             // schedule job to get metrics from now on
             if ($channel->getLocations()[0]->getLocationModule()->getIdentifier() === 'campaignchain-twitter-user') {
                 $this->get('campaignchain.job.report.location.twitter')->schedule($channel->getLocations()[0]);
             }
             $em->flush();
             $em->getConnection()->commit();
             $this->addFlash('success', 'The Twitter location <a href="#">' . $profile->displayName . '</a> was connected successfully.');
         } catch (\Exception $e) {
             $em->getConnection()->rollback();
             throw $e;
         }
     } else {
         // A channel already exists that has been connected with this Facebook account
         $this->addFlash('warning', 'A location has already been connected for this Twitter account.');
     }
     return $this->render('CampaignChainChannelTwitterBundle:Create:login.html.twig', ['redirect' => $this->generateUrl('campaignchain_core_location')]);
 }
 public function newAction(Request $request)
 {
     $locationType = $this->get('campaignchain.core.form.type.location');
     $locationType->setBundleName('campaignchain/location-ezplatform');
     $locationType->setModuleIdentifier('campaignchain-ezplatform-user');
     $form = $this->createFormBuilder()->add('location_name', 'text', array('label' => 'Location name', 'attr' => array('placeholder' => 'For example, "Our corporate website"')))->add('url', 'url', array('label' => 'REST API base URL', 'attr' => array('placeholder' => 'For example, "http://www.example.com/api/ezp/v2/"')))->add('username', 'text', array('attr' => array('placeholder' => 'An eZ Platform user with access to the REST API')))->add('password', 'repeated', array('required' => false, 'type' => 'password', 'first_name' => 'password', 'second_name' => 'password_again', 'invalid_message' => 'The password fields must match.'))->getForm();
     $form->handleRequest($request);
     try {
         if ($form->isValid()) {
             $em = $this->getDoctrine()->getManager();
             $em->getConnection()->beginTransaction();
             $locationName = $form->getData()['location_name'];
             $url = $form->getData()['url'];
             $username = $form->getData()['username'];
             $password = $form->getData()['password'];
             /*
              * TODO: Check whether URL exists
              * TODO: Check that credentials are correct
              * TODO: Check whether provided URL points to a valid eZ REST API
              */
             $client = $this->container->get('campaignchain.channel.ezplatform.rest.client');
             $connection = $client->connect($url, $username, $password);
             $locationService = $this->get('campaignchain.core.location');
             $locationModule = $locationService->getLocationModule('campaignchain/location-ezplatform', 'campaignchain-ezplatform-user');
             $location = new Location();
             $location->setLocationModule($locationModule);
             $location->setName($locationName);
             $location->setUrl($url);
             $wizard = $this->get('campaignchain.core.channel.wizard');
             $wizard->setName($location->getName());
             $wizard->addLocation($location->getUrl(), $location);
             $channel = $wizard->persist();
             $wizard->end();
             $user = new EZPlatformUser();
             $user->setLocation($channel->getLocations()[0]);
             $user->setUsername($username);
             $user->setPassword($password);
             $em->persist($user);
             $em->flush();
             $em->getConnection()->commit();
             $this->addFlash('success', 'The eZ Platform <a href="' . $url . '">' . $locationName . '</a> was connected successfully.');
             return $this->redirect($this->generateUrl('campaignchain_core_location'));
         }
     } catch (\Exception $e) {
         $em->getConnection()->rollback();
         throw $e;
     }
     return $this->render('CampaignChainCoreBundle:Base:new.html.twig', array('page_title' => 'Connect eZ Platform Instance', 'form' => $form->createView()));
 }
 public function processContentLocation(Location $location, $data)
 {
     $sid = $data['slideshow'];
     $location->setIdentifier($sid);
     $location->setName($this->availableSlideshows[$sid]['title']);
     $location->setUrl($this->availableSlideshows[$sid]['url']);
     return $location;
 }
Esempio n. 7
0
 /**
  * Finds a Location by the URL and automatically creates the Location if it
  * does not exist and if the respective Location module supports auto
  * generation of Locations.
  **
  * @param $url
  * @param $operation Operation
  * @return bool|Location|null|object
  */
 public function findLocationByUrl($url, $operation, $alias = null)
 {
     $url = ParserUtil::sanitizeUrl($url);
     /*
      * If not a Location, then see if the URL is inside a connected
      * Channel's top-level Locations. To do so, check if one of these
      * criteria apply:
      * - The Location URL matches the beginning of the CTA URL
      * - The Location identifier is included in the CTA URL as well
      *   as the domain
      */
     if (ParserUtil::urlExists($url)) {
         $urlParts = parse_url($url);
         if ($urlParts['scheme'] == 'http') {
             $urlAltScheme = str_replace('http://', 'https://', $url);
         } elseif ($urlParts['scheme'] == 'https') {
             $urlAltScheme = str_replace('https://', 'http://', $url);
         }
         $repository = $this->em->getRepository('CampaignChainCoreBundle:Location');
         $query = $repository->createQueryBuilder('location')->where("(:url LIKE CONCAT('%', location.url, '%')) OR " . "(:url_alt_scheme LIKE CONCAT('%', location.url, '%')) OR " . "(" . "location.identifier IS NOT NULL AND " . ":url LIKE CONCAT('%', location.identifier, '%') AND " . "location.url LIKE :host" . ")")->andWhere('location.parent IS NULL')->setParameter('url', $url)->setParameter('url_alt_scheme', $urlAltScheme)->setParameter('host', $urlParts['host'] . '%')->getQuery();
         /** @var Location $matchingLocation */
         $matchingLocation = $query->getOneOrNullResult();
         if ($matchingLocation) {
             /*
              * Create a new Location based on the tracking alias
              * within the matching Location's Channel.
              *
              * If no tracking alias was provided, we take the
              * default LocationModule to create a new Location.
              */
             if (!$alias) {
                 // Done if the URL is exactly the same in the matching Location.
                 if ($matchingLocation->getUrl() == $url || $matchingLocation->getUrl() == $urlAltScheme) {
                     return $matchingLocation;
                 }
                 // Let's move on to create a new Location with the default module.
                 $locationService = $this->container->get('campaignchain.core.location');
                 /** @var LocationModule $locationModule */
                 $locationModule = $locationService->getLocationModule(self::DEFAULT_LOCATION_BUNDLE_NAME, self::DEFAULT_LOCATION_MODULE_IDENTIFIER);
                 if (!$locationModule) {
                     throw new \Exception('No Location module found for bundle "' . $matchingLocation->getChannel()->getBundle()->getName() . ' and module ' . $matchingLocation->getChannel()->getChannelModule()->getIdentifier() . '"');
                 }
             } else {
                 /*
                  * Get the Location module within the matching Location's
                  * Channel and with the given tracking alias.
                  */
                 /** @var LocationModule $locationModule */
                 $locationModule = $this->getLocationModuleByTrackingAlias($matchingLocation->getChannel()->getChannelModule(), $alias);
                 // Done if the matching Location also matches the alias and URL.
                 if ($matchingLocation->getLocationModule() == $locationModule && ($matchingLocation->getUrl() == $url || $matchingLocation->getUrl() == $urlAltScheme)) {
                     return $matchingLocation;
                 }
                 /*
                  * See if there is already another Location that matches the
                  * aliase's Location module and the URL.
                  */
                 $repository = $this->em->getRepository('CampaignChainCoreBundle:Location');
                 $query = $repository->createQueryBuilder('location')->where('location.locationModule = :locationModule')->andWhere('(location.url = :url OR location.url = :url_alt_scheme')->setParameter('locationModule', $locationModule)->setParameter('url', $url)->setParameter('url_alt_scheme', $urlAltScheme)->getQuery();
                 /** @var Location $location */
                 $location = $query->getOneOrNullResult();
                 // We found an existing Location, we're done.
                 if ($location) {
                     return $location;
                 }
                 if (!$locationModule) {
                     throw new \Exception('Cannot map tracking alias "' . $alias . '" to a "' . 'Location module that belongs to Channel module "' . $matchingLocation->getChannel()->getBundle()->getName() . '/' . $matchingLocation->getChannel()->getChannelModule()->getIdentifier() . '"');
                 }
             }
             /*
              * If the matching Location provides auto-generation of Locations,
              * then let's create a new child Location.
              */
             $ctaServiceName = $locationModule->getServices()['job_cta'];
             if ($ctaServiceName) {
                 // Create the new Location
                 $location = new Location();
                 $location->setUrl($url);
                 $location->setOperation($operation);
                 $location->setChannel($matchingLocation->getChannel());
                 $location->setParent($matchingLocation);
                 // Update the Location module to be the current
                 // one.
                 $location->setLocationModule($locationModule);
                 // Let the module's service process the new
                 // Location.
                 $ctaService = $this->container->get($ctaServiceName);
                 return $ctaService->execute($location);
             } else {
                 throw new \Exception('No CTA Job service defined for Location module ' . 'of bundle "' . $locationModule->getBundle()->getName() . '" ' . 'and module "' . $locationModule->getIdentifier() . '"');
             }
         } else {
             return false;
         }
     }
     throw new \Exception('The URL ' . $url . ' does not exist.');
 }
 public function createLocationAction(Request $request)
 {
     $selectedIds = $request->get('google-analytics-profile-id', []);
     if (empty($selectedIds)) {
         $this->addFlash('warning', 'Please select at least one Google Analytics property');
         return $this->redirectToRoute('campaignchain_channel_google_analytics_list_properties');
     }
     /** @var Token $token */
     $token = $request->getSession()->get('token');
     $em = $this->getDoctrine()->getManager();
     $token = $em->merge($token);
     $websiteChannelModule = $em->getRepository('CampaignChainCoreBundle:ChannelModule')->findOneBy(['identifier' => 'campaignchain-website']);
     $googleAnalyticsChannelModule = $em->getRepository('CampaignChainCoreBundle:ChannelModule')->findOneBy(['identifier' => 'campaignchain-google-analytics']);
     foreach ($selectedIds as $analyticsId) {
         list($accountId, $propertyId, $profileId) = explode('|', $analyticsId);
         $analyticsClient = $this->get('campaignchain_report_google_analytics.service_client')->getService($token);
         /** @var \Google_Service_Analytics_Profile $profile */
         $profile = $analyticsClient->management_profiles->get($accountId, $propertyId, $profileId);
         $wizard = $this->get('campaignchain.core.channel.wizard');
         $wizard->start(new Channel(), $googleAnalyticsChannelModule);
         $wizard->setName($profile->getName());
         // Get the location module.
         $locationService = $this->get('campaignchain.core.location');
         $locationModule = $locationService->getLocationModule('campaignchain/location-google-analytics', 'campaignchain-google-analytics');
         $location = new Location();
         $location->setIdentifier($profile->getId());
         $location->setName($profile->getName());
         $location->setLocationModule($locationModule);
         $google_base_url = 'https://www.google.com/analytics/web/#report/visitors-overview/';
         $location->setUrl($google_base_url . 'a' . $profile->getAccountId() . 'w' . $profile->getInternalWebPropertyId() . 'p' . $profile->getId());
         $em->persist($location);
         try {
             $em->flush();
         } catch (UniqueConstraintViolationException $e) {
             //This GA endpoint is already connected
             $this->addFlash('warning', 'The Google Analytics Property <a href="#">' . $profile->getName() . '</a> is already connected.');
             continue;
         }
         $wizard->addLocation($location->getIdentifier(), $location);
         $wizard->persist();
         $wizard->end();
         //Check if the if the belonging website location exists, if not create a new website location
         $website = $em->getRepository('CampaignChainCoreBundle:Location')->findOneByUrl($profile->getWebsiteUrl());
         //Create website location that belongs to the GA location
         if (!$website) {
             $websiteLocationModule = $locationService->getLocationModule('campaignchain/location-website', 'campaignchain-website');
             $websiteLocationName = ParserUtil::getHTMLTitle($profile->getWebsiteUrl());
             $websiteLocation = new Location();
             $websiteLocation->setLocationModule($websiteLocationModule);
             $websiteLocation->setName($websiteLocationName);
             $websiteLocation->setUrl($profile->getWebsiteUrl());
             $em->persist($websiteLocation);
             $wizard->start(new Channel(), $websiteChannelModule);
             $wizard->setName($websiteLocationName);
             $wizard->addLocation($profile->getWebsiteUrl(), $websiteLocation);
             $wizard->persist();
             $website = $websiteLocation;
         }
         $entityToken = clone $token;
         $entityToken->setLocation($location);
         $entityToken->setApplication($token->getApplication());
         $em->persist($entityToken);
         $analyticsProfile = new Profile();
         $analyticsProfile->setAccountId($profile->getAccountId());
         $analyticsProfile->setPropertyId($profile->getWebPropertyId());
         $analyticsProfile->setProfileId($profile->getId());
         $analyticsProfile->setIdentifier($profile->getId());
         $analyticsProfile->setDisplayName($profile->getName());
         $analyticsProfile->setLocation($location);
         $analyticsProfile->setBelongingLocation($website);
         $em->persist($analyticsProfile);
         $em->flush();
         $this->addFlash('success', 'The Google Analytics Property <a href="#">' . $profile->getName() . '</a> was connected successfully.');
     }
     return $this->redirectToRoute('campaignchain_core_location');
 }
 public function processActivityLocation(Location $location)
 {
     $location->setUrl(self::LINK_ADMIN_CAMPAIGNS);
     return $location;
 }
 public function createActivity(Activity $activity, Form $form)
 {
     // Apply context of Activity.
     if (!$activity->getCampaign()) {
         $activity->setCampaign($this->campaign);
     } elseif (!$this->campaign) {
         $this->campaign = $activity->getCampaign();
     }
     if (!$activity->getChannel()) {
         $activity->setChannel($this->channel);
     } elseif (!$this->channel) {
         $this->channel = $activity->getChannel();
     }
     if (!$activity->getLocation()) {
         $activity->setLocation($this->location);
     } elseif (!$this->location) {
         $this->location = $activity->getLocation();
     }
     // The Module's content.
     $content = null;
     // If Activity module is not set, then do it.
     if (!$activity->getActivityModule()) {
         $moduleService = $this->get('campaignchain.core.module');
         $activity->setActivityModule($moduleService->getModule($this->activityBundleName, $this->activityModuleIdentifier));
     }
     // Does the Activity module relate to at least one Channel module?
     $hasChannel = $activity->getActivityModule()->getChannelModules()->count();
     // The Module's content.
     $content = null;
     $operation = new Operation();
     if ($this->parameters['equals_operation']) {
         if ($hasChannel) {
             if (!$activity->getChannel()) {
                 $activity->setChannel($this->channel);
             } elseif (!$this->channel) {
                 $this->channel = $activity->getChannel();
             }
             if (!$activity->getLocation()) {
                 $activity->setLocation($this->location);
             } elseif (!$this->location) {
                 $this->location = $activity->getLocation();
             }
         }
         // Allow the module to change some data based on its custom input.
         if ($form->has($this->contentModuleFormName)) {
             $this->handler->postFormSubmitNewEvent($activity, $form->get($this->contentModuleFormName)->getData());
             // Allow a module's handler to modify the Activity data.
             $activity = $this->handler->processActivity($activity, $form->get($this->contentModuleFormName)->getData());
         }
         // Get the operation module.
         $operationService = $this->get('campaignchain.core.operation');
         $operation = $operationService->newOperationByActivity($activity, $this->contentBundleName, $this->contentModuleIdentifier);
         // Will the Operation create a Location, i.e. the Operation
         // will be accessible through a URL after publishing?
         if ($operation->getOperationModule()->ownsLocation()) {
             // Get the location module.
             $locationService = $this->get('campaignchain.core.location');
             $locationModule = $locationService->getLocationModule($this->locationBundleName, $this->locationModuleIdentifier);
             $contentLocation = new Location();
             $contentLocation->setLocationModule($locationModule);
             $contentLocation->setParent($activity->getLocation());
             $contentLocation->setName($activity->getName());
             $contentLocation->setStatus(Medium::STATUS_UNPUBLISHED);
             $contentLocation->setOperation($operation);
             $operation->addLocation($contentLocation);
             if ($form->has($this->contentModuleFormName)) {
                 // Allow a module's handler to modify the Operation's Location.
                 $contentLocation = $this->handler->processContentLocation($contentLocation, $form->get($this->contentModuleFormName)->getData());
             }
         }
         if ($form->has($this->contentModuleFormName)) {
             // Process the Operation's content.
             $content = $this->handler->processContent($operation, $form->get($this->contentModuleFormName)->getData());
         }
         if ($content) {
             // Link the Operation details with the operation.
             $content->setOperation($operation);
         }
     } elseif (count($this->parameters['operations']) > 1) {
         $content = $this->handler->processMultiOperationMultiContent($activity, $form, $this->parameters['operations']);
     }
     $em = $this->getDoctrine()->getManager();
     // Make sure that data stays intact by using transactions.
     try {
         $em->getConnection()->beginTransaction();
         $em->persist($activity);
         if (!$content) {
             $content = $this->handler->processSingleContentMultiOperation($activity, $form);
         }
         if ($content) {
             $em->persist($content);
         }
         // We need the activity ID for storing the hooks. Hence we must
         // flush here.
         $em->flush();
         $hookService = $this->get('campaignchain.core.hook');
         /** @var Activity $activity */
         $activity = $hookService->processHooks($this->parameters['bundle_name'], $this->parameters['module_identifier'], $activity, $form, true);
         // Check if the content can be executed.
         if (isset($this->validators['operations']) && $content) {
             $isExecutable = $this->validators['operations'][0]->isExecutableByLocation($content, $activity->getStartDate());
             if (!$isExecutable['status']) {
                 throw new \Exception($isExecutable['message']);
             }
             $activity->setMustValidate($this->validators['operations'][0]->mustValidate($content, $activity->getStartDate()));
         }
         $em->flush();
         $em->getConnection()->commit();
     } catch (\Exception $e) {
         $em->getConnection()->rollback();
         throw $e;
     }
     // The module tries to execute the job immediately.
     $this->handler->postPersistNewEvent($operation, $form, $content);
     return $activity;
 }
 public function handleCompanyPageCreation(Location $location)
 {
     $this->channelWizard->setName($location->getName());
     $pagesData = $this->channelWizard->get('pagesData');
     $pageData = $pagesData[$location->getIdentifier()];
     $companyLink = 'https://www.linkedin.com/company/' . $pageData['id'];
     $location->setUrl($companyLink);
     $page = new Page();
     $page->setLocation($location);
     $page->setIdentifier($pageData['id']);
     $page->setDisplayName($pageData['name']);
     $page->setDescription($pageData['description']);
     $page->setLink($companyLink);
     $page->setWebsiteLink($pageData['websiteUrl']);
     // Remember the user object in the Wizard.
     $this->channelWizard->set($page->getIdentifier(), $page);
     $flashBagMsg = $this->channelWizard->get('flashBagMsg');
     $flashBagMsg .= '<li>Page: <a href="' . $page->getLink() . '">' . $page->getDisplayName() . '</a></li>';
     $this->channelWizard->set('flashBagMsg', $flashBagMsg);
 }
 /**
  * After a new Activity was created, this method makes it possible to alter
  * the data of the Content's Location (not the Activity's Location!) as per
  * the data provided for the Content.
  *
  * Called in these views:
  * - new
  *
  * @param Location $location Location of the Content.
  * @param $data Form submit data of the Content.
  * @return Location
  */
 public function processContentLocation(Location $location, $data)
 {
     $connection = $this->getRestApiConnectionByLocation();
     $remoteContentObject = $connection->getContentObject($data['content_object']);
     $location->setIdentifier($remoteContentObject['_id']);
     $location->setName($remoteContentObject['Name']);
     return $location;
 }
 public function processContentLocation(Location $location, $data)
 {
     $location->setIdentifier($this->remoteWebinar['webinarKey']);
     $location->setName($this->remoteWebinar['subject']);
     $location->setUrl($this->remoteWebinar['registrationUrl']);
     return $location;
 }
 public function newAction(Request $request)
 {
     $locationType = $this->get('campaignchain.core.form.type.location');
     $locationType->setBundleName('campaignchain/location-slideshare');
     $locationType->setModuleIdentifier('campaignchain-slideshare');
     $form = $this->createFormBuilder()->add('username', 'text')->add('password', 'repeated', array('required' => false, 'type' => 'password', 'first_name' => 'password', 'second_name' => 'password_again', 'invalid_message' => 'The password fields must match.'))->getForm();
     $form->handleRequest($request);
     try {
         if ($form->isValid()) {
             $em = $this->getDoctrine()->getManager();
             $em->getConnection()->beginTransaction();
             $locationUsername = $form->getData()['username'];
             $locationPassword = $form->getData()['password'];
             /*
             $oauthApp = $this->get('campaignchain.security.authentication.client.oauth.application');
             $application = $oauthApp->getApplication(self::RESOURCE_OWNER);
             $ts = time();
             $client = new \Guzzle\Http\Client;
             $request = $client->createRequest('GET', 'https://www.slideshare.net/api/2/get_user_tags');
             $query = $request->getQuery();
             $query->set('api_key', $application->getKey());
             $query->set('ts',  $ts);
             $query->set('hash', sha1($application->getSecret().$ts));
             $query->set('username', $locationUsername);
             $query->set('password', $locationPassword);
             $response = $request->send();
             
             $xml = $response->xml();
             */
             $oauthApp = $this->get('campaignchain.security.authentication.client.oauth.application');
             $application = $oauthApp->getApplication(self::RESOURCE_OWNER);
             $client = $this->container->get('campaignchain.channel.slideshare.rest.client');
             $connection = $client->connect($application->getKey(), $application->getSecret(), $locationUsername, $locationPassword);
             $xml = $connection->getUserTags();
             if (isset($xml->Message) && strtolower($xml->Message) == 'failed user authentication') {
                 throw new \Exception('The credentials provided are invalid');
             }
             $locationURL = 'http://www.slideshare.net/' . $locationUsername;
             $locationService = $this->get('campaignchain.core.location');
             $locationModule = $locationService->getLocationModule('campaignchain/location-slideshare', 'campaignchain-slideshare-user');
             $location = new Location();
             $location->setLocationModule($locationModule);
             $location->setName($locationUsername);
             $location->setUrl($locationURL);
             /*
              * If user uploaded an image, use that as the Location image,
              * otherwise, take the SlideShare default profile image.
              */
             $slideShareUserImage = 'http://cdn.slidesharecdn.com/profile-photo-' . $locationUsername . '-96x96.jpg';
             try {
                 getimagesize($slideShareUserImage);
             } catch (\Exception $e) {
                 $slideShareUserImage = 'http://public.slidesharecdn.com/b/images/user-96x96.png';
             }
             $location->setImage($slideShareUserImage);
             $wizard = $this->get('campaignchain.core.channel.wizard');
             $wizard->setName($location->getName());
             $wizard->addLocation($location->getUrl(), $location);
             $channel = $wizard->persist();
             $wizard->end();
             $slideshareUser = new SlideShareUser();
             $slideshareUser->setLocation($channel->getLocations()[0]);
             $slideshareUser->setIdentifier($locationUsername);
             $slideshareUser->setPassword($locationPassword);
             $slideshareUser->setDisplayName($locationUsername);
             $em->persist($slideshareUser);
             $em->flush();
             $em->getConnection()->commit();
             $this->get('session')->getFlashBag()->add('success', 'The Slideshare location <a href="#">' . $locationUsername . '</a> was connected successfully.');
             return $this->redirect($this->generateUrl('campaignchain_core_location'));
         }
     } catch (\Exception $e) {
         $em->getConnection()->rollback();
         throw $e;
     }
     return $this->render('CampaignChainCoreBundle:Base:new.html.twig', array('page_title' => 'Connect SlideShare Account', 'form' => $form->createView()));
 }
 public function addLocationAction(Request $request)
 {
     $wizard = $this->get('campaignchain.core.channel.wizard');
     $channel = $wizard->getChannel();
     $profile = $wizard->get('profile');
     $locations = [];
     $locationName = $profile->displayName;
     $username = $profile->username;
     if (!empty($username)) {
         $locationName .= ' (' . $username . ')';
     }
     // Get the location module for the user stream.
     $locationService = $this->get('campaignchain.core.location');
     $locationModuleUser = $locationService->getLocationModule('campaignchain/location-facebook', 'campaignchain-facebook-user');
     // Create the location instance for the user stream.
     $locationUser = new Location();
     $locationUser->setChannel($channel);
     $locationUser->setName($locationName);
     $locationUser->setIdentifier($profile->identifier);
     $locationUser->setImage($profile->photoURL);
     $locationUser->setLocationModule($locationModuleUser);
     $locationModuleUser->addLocation($locationUser);
     $locations[$profile->identifier] = $locationUser;
     // Connect to Facebook to retrieve pages related to the user.
     $tokens = $wizard->get('tokens');
     $client = $this->container->get('campaignchain.channel.facebook.rest.client');
     $connection = $client->connect($tokens[$profile->identifier]->getAccessToken());
     if ($connection) {
         // TODO: Check whether user has manage_pages permission with /me/permissions
         // check if the user owns Facebook pages
         $response = $connection->api('/me/accounts');
         $pagesData = $response['data'];
         if (is_array($pagesData) && count($pagesData)) {
             // TODO: Should we check whether the Facebook page has actually been published (through is_published), because if not, then posting to it won't make sense? Same with can_post and perms from /me/accounts?
             // Get the location module for the page stream.
             $locationModulePage = $locationService->getLocationModule('campaignchain/location-facebook', 'campaignchain-facebook-page');
             // User owns pages, so let's build the form and ask him whether to create channels for each of them
             // with the respective channel name
             foreach ($pagesData as $pageData) {
                 // Save the token in the Wizard.
                 $tokens = $wizard->get('tokens');
                 $newToken = new Token();
                 $newToken->setAccessToken($pageData['access_token']);
                 $application = $tokens[$wizard->get('facebook_user_id')]->getApplication();
                 $newToken->setApplication($application);
                 $tokens[$pageData['id']] = $newToken;
                 $wizard->set('tokens', $tokens);
                 // Get the page picture
                 $pageConnection = $client->connect($pageData['access_token']);
                 $pagePicture = $pageConnection->api('/' . $pageData['id'] . '/picture', 'GET', ['redirect' => false, 'type' => 'large']);
                 $pageData['picture_url'] = $pagePicture['data']['url'];
                 // Create the location instance for the page stream.
                 $locationPage = new Location();
                 $locationPage->setChannel($channel);
                 $locationPage->setName($pageData['name']);
                 $locationPage->setIdentifier($pageData['id']);
                 $locationPage->setImage($pageData['picture_url']);
                 $locationPage->setLocationModule($locationModulePage);
                 $locationModulePage->addLocation($locationPage);
                 $locations[$pageData['id']] = $locationPage;
                 $wizardPages[$pageData['id']] = $pageData;
             }
             $wizard->set('pagesData', $wizardPages);
         }
     }
     $data = [];
     $form = $this->createFormBuilder($data);
     foreach ($locations as $identifier => $location) {
         // Has the page already been added as a location?
         $repository = $this->getDoctrine()->getRepository('CampaignChainCoreBundle:Location');
         $pageExists = $repository->findOneBy(['identifier' => $identifier, 'locationModule' => $location->getLocationModule()]);
         // Compose the checkbox form field.
         $form->add($identifier, CheckboxType::class, ['label' => '<img class="campaignchain-location-image-input-prepend" src="' . $location->getImage() . '"> ' . $location->getName(), 'required' => false, 'data' => true, 'mapped' => false, 'disabled' => $pageExists, 'attr' => ['align_with_widget' => true]]);
         // If a location has already been added before, remove it from this process.
         // TODO: Also assign existing locations to the new FB user.
         if ($pageExists) {
             unset($locations[$identifier]);
         }
     }
     $form = $form->getForm();
     $form->handleRequest($request);
     if ($form->isValid()) {
         // Find out which locations should be added, i.e. which respective checkbox is active.
         foreach ($locations as $identifier => $location) {
             if (!$form->get($identifier)->getData()) {
                 unset($locations[$identifier]);
                 $wizard->removeLocation($identifier);
             }
         }
         // If there's at least one location to be added, then have the user configure it.
         if (is_array($locations) && count($locations)) {
             $wizard->setLocations($locations);
             return $this->redirectToRoute('campaignchain_channel_facebook_location_configure', ['step' => 0]);
         } else {
             $this->addFlash('warning', 'No new location has been added.');
             return $this->redirectToRoute('campaignchain_core_location');
         }
     }
     return $this->render('CampaignChainCoreBundle:Base:new.html.twig', ['page_title' => 'Add Facebook Locations', 'form' => $form->createView()]);
 }
 /**
  * Get facts data per dimension.
  *
  * @param Location $location
  * @param bool $percent
  * @return array
  */
 public function getFacts(Location $location, $percent = false)
 {
     $qb = $this->em->createQueryBuilder();
     $qb->select('r.time, r.value, IDENTITY(r.metric) as metric')->from('CampaignChain\\CoreBundle\\Entity\\ReportAnalyticsLocationFact', 'r')->where('r.location = :locationId')->orderBy('r.time', 'ASC')->setParameter('locationId', $location->getId());
     $query = $qb->getQuery();
     $facts = $query->getArrayResult();
     $factsData = [];
     $tmp = [];
     foreach ($facts as $fact) {
         $tmp[$fact['metric']][] = [$fact['time']->getTimestamp() * 1000, $fact['value']];
     }
     foreach (array_keys($tmp) as $k) {
         $factsData[$k]['data'] = $this->serializer->serialize($tmp[$k], 'json');
         $factsData[$k]['id'] = $k;
         //            if ($percent) {
         //                $factsData[$k]['percent'] = $this->getDimensionPercent($campaign, $activity, $k);
         //            }
     }
     return $factsData;
 }