public function control()
 {
     $this->redirectToSternIndiaEndpoint('forgot.php');
     $config = Config::getInstance();
     //$this->addToView('is_registration_open', $config->getValue('is_registration_open'));
     // if (isset($_POST['email']) && $_POST['Submit'] == 'Send Reset') {
     // /$_POST['email'] = '*****@*****.**';
     if (isset($_POST['email'])) {
         $this->disableCaching();
         $dao = DAOFactory::getDAO('UserDAO');
         $user = $dao->getByEmail($_POST['email']);
         if (isset($user)) {
             $token = $user->setPasswordRecoveryToken();
             $es = new ViewManager();
             $es->caching = false;
             //$es->assign('apptitle', $config->getValue('app_title_prefix')."ThinkUp" );
             $es->assign('first_name', $user->first_name);
             $es->assign('recovery_url', "session/reset.php?token={$token}");
             $es->assign('application_url', Utils::getApplicationURL(false));
             $es->assign('site_root_path', $config->getValue('site_root_path'));
             $message = $es->fetch('_email.forgotpassword.tpl');
             $subject = $config->getValue('app_title_prefix') . "Stern India Password Recovery";
             //Will put the things in queue to mail the things.
             Resque::enqueue('user_mail', 'Mailer', array($_POST['email'], $subject, $message));
             $this->addToView('link_sent', true);
         } else {
             $this->addErrorMessage('Error: account does not exist.');
         }
     }
     $this->setViewTemplate('Session/forgot.tpl');
     return $this->generateView();
 }
Ejemplo n.º 2
0
 /**
  * Report installation version back to thinkup.com. If usage reporting is enabled, include instance username
  * and network.
  * @param Instance $instance
  * @return array ($report_back_url, $referer_url, $status, $contents)
  */
 public static function reportVersion(Instance $instance)
 {
     //Build URLs with appropriate parameters
     $config = Config::getInstance();
     $report_back_url = 'http://thinkup.com/version.php?v=' . $config->getValue('THINKUP_VERSION');
     //Explicity set referer for when this is called by a command line script
     $referer_url = Utils::getApplicationURL();
     //If user hasn't opted out, report back username and network
     if ($config->getValue('is_opted_out_usage_stats') === true) {
         $report_back_url .= '&usage=n';
     } else {
         $referer_url .= "?u=" . urlencode($instance->network_username) . "&n=" . urlencode($instance->network);
     }
     $in_test_mode = isset($_SESSION["MODE"]) && $_SESSION["MODE"] == "TESTS" || getenv("MODE") == "TESTS";
     if (!$in_test_mode) {
         //only make live request if we're not running the test suite
         //Make the cURL request
         $c = curl_init();
         curl_setopt($c, CURLOPT_URL, $report_back_url);
         curl_setopt($c, CURLOPT_REFERER, $referer_url);
         curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
         $contents = curl_exec($c);
         $status = curl_getinfo($c, CURLINFO_HTTP_CODE);
         curl_close($c);
     } else {
         $contents = '';
         $status = 200;
     }
     return array($report_back_url, $referer_url, $status, $contents);
 }
 public function authControl()
 {
     $config = Config::getInstance();
     Loader::definePathConstants();
     $this->setViewTemplate(THINKUP_WEBAPP_PATH . 'plugins/geoencoder/view/geoencoder.account.index.tpl');
     $this->view_mgr->addHelp('geoencoder', 'userguide/settings/plugins/geoencoder');
     $this->addToView('message', 'This is the GeoEncoder plugin configuration page for ' . $this->owner->email . '.');
     /** set option fields **/
     // gmaps_api_key text field
     $name_field = array('name' => 'gmaps_api_key', 'label' => 'Google Maps API Key', 'size' => 55);
     $this->addPluginOption(self::FORM_TEXT_ELEMENT, $name_field);
     $this->addPluginOptionRequiredMessage('gmaps_api_key', 'Please enter your Google Maps API Key');
     // distance_unit radio field
     $distance_unit_field = array('name' => 'distance_unit', 'label' => 'Unit of Distance');
     $distance_unit_field['values'] = array('Kilometers' => 'km', 'Miles' => 'mi');
     $distance_unit_field['default_value'] = 'km';
     $this->addPluginOption(self::FORM_RADIO_ELEMENT, $distance_unit_field);
     $plugin = new GeoEncoderPlugin();
     if (!$plugin->isConfigured()) {
         $this->addInfoMessage('Please complete plugin setup to start using it.', 'setup');
         $this->addToView('is_configured', false);
     } else {
         $this->addToView('is_configured', true);
     }
     $this->addToView('thinkup_site_url', Utils::getApplicationURL());
     return $this->generateView();
 }
 public function control()
 {
     $config = Config::getInstance();
     $this->addToView('is_registration_open', $config->getValue('is_registration_open'));
     if (isset($_POST['Submit']) && $_POST['Submit'] == 'Send Reset') {
         $this->disableCaching();
         $dao = DAOFactory::getDAO('OwnerDAO');
         $user = $dao->getByEmail($_POST['email']);
         if (isset($user)) {
             $token = $user->setPasswordRecoveryToken();
             $es = new ViewManager();
             $es->caching = false;
             $es->assign('apptitle', $config->getValue('app_title_prefix') . "ThinkUp");
             $es->assign('recovery_url', "session/reset.php?token={$token}");
             $es->assign('application_url', Utils::getApplicationURL($false));
             $es->assign('site_root_path', $config->getValue('site_root_path'));
             $message = $es->fetch('_email.forgotpassword.tpl');
             Mailer::mail($_POST['email'], $config->getValue('app_title_prefix') . "ThinkUp Password Recovery", $message);
             $this->addSuccessMessage('Password recovery information has been sent to your email address.');
         } else {
             $this->addErrorMessage('Error: account does not exist.');
         }
     }
     $this->view_mgr->addHelp('forgot', 'userguide/accounts/index');
     $this->setViewTemplate('session.forgot.tpl');
     return $this->generateView();
 }
 public function authControl()
 {
     $config = Config::getInstance();
     Loader::definePathConstants();
     $this->setViewTemplate(THINKUP_WEBAPP_PATH . 'plugins/twitter/view/twitter.account.index.tpl');
     $this->view_mgr->addHelp('twitter', 'userguide/settings/plugins/twitter/index');
     $instance_dao = DAOFactory::getDAO('InstanceDAO');
     // get plugin option values if defined...
     $plugin_options = $this->getPluginOptions();
     $oauth_consumer_key = $this->getPluginOption('oauth_consumer_key');
     $oauth_consumer_secret = $this->getPluginOption('oauth_consumer_secret');
     $archive_limit = $this->getPluginOption('archive_limit');
     $num_twitter_errors = $this->getPluginOption('num_twitter_errors');
     $this->addToView('twitter_app_name', "ThinkUp " . $_SERVER['SERVER_NAME']);
     $this->addToView('thinkup_site_url', Utils::getApplicationURL(true));
     $plugin = new TwitterPlugin();
     if ($plugin->isConfigured()) {
         $this->addToView('is_configured', true);
         $owner_instances = $instance_dao->getByOwnerAndNetwork($this->owner, 'twitter');
         $this->addToView('owner_instances', $owner_instances);
         if (isset($this->owner) && $this->owner->isMemberAtAnyLevel()) {
             if ($this->owner->isMemberLevel()) {
                 if (sizeof($owner_instances) > 0) {
                     $this->do_show_add_button = false;
                     $this->addInfoMessage("To connect another Twitter account to ThinkUp, upgrade your membership.", 'membership_cap');
                 }
             }
         }
         if (isset($_GET['oauth_token']) || $this->do_show_add_button) {
             $twitter_oauth = new TwitterOAuth($oauth_consumer_key, $oauth_consumer_secret);
             /* Request tokens from twitter */
             $token_array = $twitter_oauth->getRequestToken(Utils::getApplicationURL(true) . "account/?p=twitter");
             if (isset($token_array['oauth_token']) || isset($_SESSION["MODE"]) && $_SESSION["MODE"] == "TESTS" || getenv("MODE") == "TESTS") {
                 //testing
                 $token = $token_array['oauth_token'];
                 SessionCache::put('oauth_request_token_secret', $token_array['oauth_token_secret']);
                 if (isset($_GET['oauth_token'])) {
                     self::addAuthorizedUser($oauth_consumer_key, $oauth_consumer_secret, $num_twitter_errors);
                 }
                 if ($this->do_show_add_button) {
                     /* Build the authorization URL */
                     $oauthorize_link = $twitter_oauth->getAuthorizeURL($token);
                     $this->addToView('oauthorize_link', $oauthorize_link);
                 }
             } else {
                 //set error message here
                 $this->addErrorMessage("Unable to obtain OAuth tokens from Twitter. Please double-check the consumer key and secret " . "are correct.", "setup");
                 $oauthorize_link = '';
                 $this->addToView('is_configured', false);
             }
         }
     } else {
         $this->addInfoMessage('Please complete plugin setup to start using it.', 'setup');
         $this->addToView('is_configured', false);
     }
     // add plugin options from
     $this->addOptionForm();
     return $this->generateView();
 }
 /**
  * Bounce user to public page or to error page.
  * @throws ControllerAuthException
  */
 protected function bounce()
 {
     if ($this->content_type == 'text/html; charset=UTF-8' && $this->url_mapping != null) {
         $this->redirect(Utils::getApplicationURL() . 'session/login.php?redirect=' . $this->url_mapping);
     } else {
         throw new ControllerAuthException('You must log in to access this controller: ' . get_class($this));
     }
 }
Ejemplo n.º 7
0
 public function control()
 {
     $instance_dao = DAOFactory::getDAO('InstanceDAO');
     $hours_since_last_crawl = $instance_dao->getHoursSinceLastCrawlerRun();
     if (isset($hours_since_last_crawl) && $hours_since_last_crawl > $this->threshold) {
         $this->addToView('message', Utils::getApplicationURL() . ": Crawler hasn't run in " . round($hours_since_last_crawl) . " hours");
     }
     return $this->generateView();
 }
 /**
  * Process actions based on $_GET parameters. Authorize FB user or add FB page.
  * @param arr $options Facebook plugin options
  */
 protected function processPageActions($options)
 {
     //authorize user
     if (isset($_GET["code"]) && isset($_GET["state"])) {
         //validate state to avoid CSRF attacks
         if ($_GET["state"] == SessionCache::get('facebook_auth_csrf')) {
             //Prepare API request
             //First, prep redirect URI
             $redirect_uri = Utils::getApplicationURL() . 'account/?p=facebook';
             //Build API request URL
             $api_req = 'oauth/access_token';
             $api_req_params = array('client_id' => $options['facebook_app_id']->option_value, 'client_secret' => $options['facebook_api_secret']->option_value, 'redirect_uri' => $redirect_uri, 'state' => SessionCache::get('facebook_auth_csrf'), 'code' => $_GET["code"]);
             $access_token_response = FacebookGraphAPIAccessor::apiRequest($api_req, null, $api_req_params, null);
             //DEBUG
             // Logger::getInstance()->logInfo("Access token response: "
             //     .Utils::varDumpToString($access_token_response), __METHOD__.','.__LINE__);
             if (isset($access_token_response->error)) {
                 $this->addErrorMessage("There was a problem. Facebook says: " . $access_token_response->error->message . " Please try again.", 'user_add');
                 $logger->logInfo("Added error message ", __METHOD__ . ',' . __LINE__);
                 return;
             }
             $access_token = $access_token_response->access_token;
             if (isset($access_token)) {
                 /**
                  * Swap in short-term token for long-lived token as per
                  * https://developers.facebook.com/docs/facebook-login/access-tokens/#extending
                  */
                 $api_req = 'oauth/access_token';
                 $api_req_params = array('grant_type' => 'fb_exchange_token', 'client_id' => $options['facebook_app_id']->option_value, 'client_secret' => $options['facebook_api_secret']->option_value, 'fb_exchange_token' => $access_token);
                 $access_token_response = FacebookGraphAPIAccessor::apiRequest($api_req, null, $api_req_params);
                 // DEBUG
                 // Logger::getInstance()->logInfo("Exchanged access token response: "
                 //     .Utils::varDumpToString($access_token_response), __METHOD__.','.__LINE__);
                 $access_token = $access_token_response->access_token;
                 $fb_user_profile = FacebookGraphAPIAccessor::apiRequest('me', $access_token, 'name,id');
                 //DEBUG
                 // Logger::getInstance()->logInfo("FB user profile: ".Utils::varDumpToString($fb_user_profile),
                 //     __METHOD__.','.__LINE__);
                 if (isset($fb_user_profile->error)) {
                     $error_msg = "Problem authorizing your Facebook account!";
                     $error_object = $access_token_response;
                     if (isset($error_object) && isset($error_object->error->type) && isset($error_object->error->message)) {
                         $error_msg = $error_msg . "<br>Facebook says: \"" . $error_object->error->type . ": " . $error_object->error->message . "\"";
                     } else {
                         $error_msg = $error_msg . "<br>Facebook's response: \"" . $access_token_response . "\"";
                     }
                     $this->addErrorMessage($error_msg, 'user_add', true);
                 } else {
                     $fb_username = isset($fb_user_profile->name) ? $fb_user_profile->name : '';
                     $fb_user_id = isset($fb_user_profile->id) ? $fb_user_profile->id : '';
                     if (empty($fb_username)) {
                         $error = 'Sorry, ThinkUp does not support business accounts.';
                         $this->addErrorMessage($error, 'user_add');
                     } else {
                         $this->saveAccessToken($fb_user_id, $access_token, $fb_username);
                     }
                 }
             } else {
                 $error_msg = "Problem authorizing your Facebook account! Please correct your plugin settings.";
                 $error_object = $access_token_response;
                 if (isset($error_object) && isset($error_object->error->type) && isset($error_object->error->message)) {
                     $error_msg = $error_msg . "<br>Facebook says: \"" . $error_object->error->type . ": " . $error_object->error->message . "\"";
                 } else {
                     $error_msg = $error_msg . "<br>Facebook's response: \"" . $access_token_response . "\"";
                 }
                 $this->addErrorMessage($error_msg, 'user_add', true);
             }
         } else {
             $this->addErrorMessage("Could not authenticate Facebook account due to invalid CSRF token.", 'user_add');
         }
     }
 }
 /**
  * Populate view manager with instagram interaction UI, like the instagram Add User button and page dropdown.
  * @param array $options 'instagram_app_id' and 'instagram_api_secret'
  */
 protected function setUpInstagramInteractions($options)
 {
     // Create our instagram Application instance
     if (Utils::isThinkUpLLC()) {
         $redirect_uri = Config::getInstance()->getValue('thinkupllc_endpoint') . 'instagram/?u=' . Config::getInstance()->getValue('install_folder');
     } else {
         $redirect_uri = Utils::getApplicationURL() . 'account/?p=instagram';
     }
     $scope = array('likes', 'comments', 'relationships');
     $instagram = new Instagram\Auth(array('client_id' => $options['instagram_app_id']->option_value, 'client_secret' => $options['instagram_api_secret']->option_value, 'redirect_uri' => $redirect_uri));
     if ($this->do_show_add_button) {
         $instagramconnect_link = sprintf('https://api.instagram.com/oauth/authorize/?client_id=%s&redirect_uri=%s&response_type=code&scope=%s', $options['instagram_app_id']->option_value, $redirect_uri, implode('+', $scope));
         $this->addToView('instaconnect_link', $instagramconnect_link);
     }
     self::processPageActions($options, $instagram);
     $logger = Logger::getInstance();
     $instance_dao = DAOFactory::getDAO('InstanceDAO');
     $instances = $instance_dao->getByOwnerAndNetwork($this->owner, 'instagram');
     $owner_instance_dao = DAOFactory::getDAO('OwnerInstanceDAO');
     foreach ($instances as $instance) {
         $tokens = $owner_instance_dao->getOAuthTokens($instance->id);
         if (isset($tokens['auth_error']) && $tokens['auth_error'] != '') {
             $instance->auth_error = $tokens['auth_error'];
         }
     }
     $this->addToView('instances', $instances);
 }
Ejemplo n.º 10
0
 /**
  * Launch the crawler, if the latest crawler_last_run date is older than X minutes, then return a valid RSS feed.
  * @return string rendered view markup
  */
 public function authControl()
 {
     $this->setContentType('application/rss+xml; charset=UTF-8');
     $this->setViewTemplate('rss.tpl');
     $config = Config::getInstance();
     $rss_crawler_refresh_rate = $config->getValue('rss_crawler_refresh_rate');
     if (empty($rss_crawler_refresh_rate)) {
         $rss_crawler_refresh_rate = 20;
         // minutes
     }
     $base_url = Utils::getApplicationURL();
     $crawler_plugin_registrar_launched = false;
     $instance_dao = DAOFactory::getDAO('InstanceDAO');
     $email = $this->getLoggedInUser();
     $owner = parent::getOwner($email);
     $freshest_instance = $instance_dao->getFreshestByOwnerId($owner->id);
     if ($freshest_instance) {
         $crawler_plugin_registrar_last_run = strtotime($freshest_instance->crawler_last_run);
     }
     if ($freshest_instance && $crawler_plugin_registrar_last_run < time() - $rss_crawler_refresh_rate * 60) {
         $crawler_plugin_registrar_run_url = $base_url . 'crawler/run.php?' . sprintf('un=%s&as=%s', $email, $owner->api_key);
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $crawler_plugin_registrar_run_url);
         curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
         // seconds
         curl_setopt($ch, CURLOPT_TIMEOUT, 5);
         // seconds
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($ch, CURLOPT_HEADER, true);
         $result = curl_exec($ch);
         curl_close($ch);
         $body = substr($result, strpos($result, "\r\n\r\n") + 4);
         if (strpos($result, 'Content-Type: application/json') && function_exists('json_decode')) {
             $json = json_decode($body);
             if (isset($json->error)) {
                 $crawler_plugin_registrar_launched = false;
             } else {
                 if (isset($json->result) && $json->result == 'success') {
                     $crawler_plugin_registrar_launched = true;
                 }
             }
         } else {
             if (strpos($body, 'Error starting crawler') !== FALSE) {
                 $crawler_plugin_registrar_launched = false;
             } else {
                 $crawler_plugin_registrar_launched = true;
             }
         }
     }
     $items = array();
     $logger = Logger::getInstance();
     // Don't return an item if there is a crawler log defined;
     // it would just duplicate the information available in that file.
     if ($crawler_plugin_registrar_launched && !isset($logger->log)) {
         $title = 'ThinkUp crawl started on ' . date('Y-m-d H:i:s');
         $link = $base_url . 'rss.php?d=' . urlencode(date('Y-m-d H:i:s'));
         $description = "Last ThinkUp crawl ended on {$freshest_instance->crawler_last_run}<br />A new crawl " . "was started just now, since it's been more than {$rss_crawler_refresh_rate} minutes since the last run.";
         $items[] = self::createRSSItem($title, $link, $description);
     }
     $items = array_merge($items, $this->getAdditionalItems($base_url));
     $this->addToView('items', $items);
     $this->addToView('logged_in_user', htmlspecialchars($this->getLoggedInUser()));
     $this->addToView('rss_crawler_refresh_rate', htmlspecialchars($rss_crawler_refresh_rate));
     return $this->generateView();
 }
Ejemplo n.º 11
0
 public function testGetApplicationURL()
 {
     //no SSL
     $_SERVER['HTTP_HOST'] = "mytestthinkup";
     $_SERVER['HTTPS'] = null;
     $cfg = Config::getInstance();
     $cfg->setValue('site_root_path', '/my/path/to/thinkup/');
     $utils_url = Utils::getApplicationURL();
     $expected_url = 'http://mytestthinkup/my/path/to/thinkup/';
     $this->assertEqual($utils_url, $expected_url);
     //with SSL
     $_SERVER['HTTPS'] = true;
     $utils_url = Utils::getApplicationURL();
     $expected_url = 'https://mytestthinkup/my/path/to/thinkup/';
     $this->assertEqual($utils_url, $expected_url);
     //nonstandard port
     $_SERVER['HTTPS'] = null;
     $_SERVER['SERVER_PORT'] = '1003';
     $utils_url = Utils::getApplicationURL();
     $expected_url = 'http://mytestthinkup:1003/my/path/to/thinkup/';
     $this->assertEqual($utils_url, $expected_url);
     //standard port 80
     $_SERVER['HTTPS'] = null;
     $_SERVER['SERVER_PORT'] = '80';
     $utils_url = Utils::getApplicationURL();
     $expected_url = 'http://mytestthinkup/my/path/to/thinkup/';
     $this->assertEqual($utils_url, $expected_url);
     //SSL standard port 443
     $_SERVER['HTTPS'] = true;
     $_SERVER['SERVER_PORT'] = '443';
     $utils_url = Utils::getApplicationURL();
     $expected_url = 'https://mytestthinkup/my/path/to/thinkup/';
     $this->assertEqual($utils_url, $expected_url);
     //no port set
     $_SERVER['HTTPS'] = null;
     $_SERVER['SERVER_PORT'] = '80';
     $utils_url = Utils::getApplicationURL();
     $expected_url = 'http://mytestthinkup/my/path/to/thinkup/';
     $this->assertEqual($utils_url, $expected_url);
     //localhost
     $_SERVER['HTTP_HOST'] = "localhost";
     $utils_url = Utils::getApplicationURL();
     $expected_url = 'http://localhost/my/path/to/thinkup/';
     $this->assertEqual($utils_url, $expected_url);
     //localhost - return IP
     $_SERVER['HTTP_HOST'] = "localhost";
     $utils_url = Utils::getApplicationURL(true);
     $expected_url = 'http://127.0.0.1/my/path/to/thinkup/';
     $this->assertEqual($utils_url, $expected_url);
 }
Ejemplo n.º 12
0
 /**
  * Send user email alert about invalid OAuth tokens, at most one message per week.
  * In test mode, this will only write the message body to a file in the application data directory.
  * @param str $email
  * @param str $username
  * @return bool Whether or not email was sent
  */
 private function sendInvalidOAuthEmailAlert($email, $username)
 {
     //Determine whether or not an email about invalid tokens was sent in the past 7 days
     $should_send_email = true;
     $option_dao = DAOFactory::getDAO('OptionDAO');
     $plugin_dao = DAOFactory::getDAO('PluginDAO');
     $plugin_id = $plugin_dao->getPluginId('facebook');
     $last_email_timestamp = $option_dao->getOptionByName(OptionDAO::PLUGIN_OPTIONS . '-' . $plugin_id, 'invalid_oauth_email_sent_timestamp');
     if (isset($last_email_timestamp)) {
         //option exists, a message was sent
         //a message was sent in the past week
         if ($last_email_timestamp->option_value > strtotime('-1 week')) {
             $should_send_email = false;
         } else {
             $option_dao->updateOption($last_email_timestamp->option_id, time());
         }
     } else {
         $option_dao->insertOption(OptionDAO::PLUGIN_OPTIONS . '-' . $plugin_id, 'invalid_oauth_email_sent_timestamp', time());
     }
     if ($should_send_email) {
         $mailer_view_mgr = new ViewManager();
         $mailer_view_mgr->caching = false;
         $mailer_view_mgr->assign('thinkup_site_url', Utils::getApplicationURL());
         $mailer_view_mgr->assign('email', $email);
         $mailer_view_mgr->assign('faceboook_user_name', $username);
         $message = $mailer_view_mgr->fetch(Utils::getPluginViewDirectory('facebook') . '_email.invalidtoken.tpl');
         Mailer::mail($email, "Please re-authorize ThinkUp to access " . $username . " on Facebook", $message);
         return true;
     } else {
         return false;
     }
 }
Ejemplo n.º 13
0
 public function testGetApplicationURL()
 {
     $cfg = Config::getInstance();
     $cfg->setValue('site_root_path', '/my/path/to/thinkup/');
     //no $_SERVER vars set, but with application setting set
     $builder = FixtureBuilder::build('options', array('namespace' => 'application_options', 'option_name' => 'server_name', 'option_value' => 'testservername'));
     $utils_url = Utils::getApplicationURL();
     $expected_url = 'http://testservername/my/path/to/thinkup/';
     $this->assertEqual($utils_url, $expected_url);
     //SERVER_NAME, not HTTP_HOST
     $_SERVER['HTTP_HOST'] = null;
     $_SERVER['SERVER_NAME'] = 'mytestservername';
     $_SERVER['HTTPS'] = null;
     $utils_url = Utils::getApplicationURL();
     $expected_url = 'http://mytestservername/my/path/to/thinkup/';
     $this->assertEqual($utils_url, $expected_url);
     //no SSL
     $_SERVER['SERVER_NAME'] = null;
     $_SERVER['HTTP_HOST'] = "mytestthinkup";
     $_SERVER['HTTPS'] = null;
     $utils_url = Utils::getApplicationURL();
     $expected_url = 'http://mytestthinkup/my/path/to/thinkup/';
     $this->assertEqual($utils_url, $expected_url);
     //no SSL but with $_SERVER['HTTPS'] set to empty string
     $_SERVER['HTTPS'] = '';
     $utils_url = Utils::getApplicationURL();
     $expected_url = 'http://mytestthinkup/my/path/to/thinkup/';
     $this->assertEqual($utils_url, $expected_url);
     //with SSL
     $_SERVER['HTTPS'] = true;
     $utils_url = Utils::getApplicationURL();
     $expected_url = 'https://mytestthinkup/my/path/to/thinkup/';
     $this->assertEqual($utils_url, $expected_url);
     //nonstandard port
     $_SERVER['HTTPS'] = null;
     $_SERVER['SERVER_PORT'] = '1003';
     $utils_url = Utils::getApplicationURL();
     $expected_url = 'http://mytestthinkup:1003/my/path/to/thinkup/';
     $this->assertEqual($utils_url, $expected_url);
     //standard port 80
     $_SERVER['HTTPS'] = null;
     $_SERVER['SERVER_PORT'] = '80';
     $utils_url = Utils::getApplicationURL();
     $expected_url = 'http://mytestthinkup/my/path/to/thinkup/';
     $this->assertEqual($utils_url, $expected_url);
     //SSL standard port 443
     $_SERVER['HTTPS'] = true;
     $_SERVER['SERVER_PORT'] = '443';
     $utils_url = Utils::getApplicationURL();
     $expected_url = 'https://mytestthinkup/my/path/to/thinkup/';
     $this->assertEqual($utils_url, $expected_url);
     //no port set
     $_SERVER['HTTPS'] = null;
     $_SERVER['SERVER_PORT'] = '80';
     $utils_url = Utils::getApplicationURL();
     $expected_url = 'http://mytestthinkup/my/path/to/thinkup/';
     $this->assertEqual($utils_url, $expected_url);
     //localhost
     $_SERVER['HTTP_HOST'] = "localhost";
     $utils_url = Utils::getApplicationURL();
     $expected_url = 'http://localhost/my/path/to/thinkup/';
     $this->assertEqual($utils_url, $expected_url);
     //localhost - return IP
     $_SERVER['HTTP_HOST'] = "localhost";
     $utils_url = Utils::getApplicationURL(true);
     $expected_url = 'http://127.0.0.1/my/path/to/thinkup/';
     $this->assertEqual($utils_url, $expected_url);
     //with spaces in site_rooth_path
     $_SERVER['HTTP_HOST'] = "localhost";
     $cfg->setValue('site_root_path', '/my/path and this space/to/thinkup/');
     $utils_url = Utils::getApplicationURL(false);
     $expected_url = 'http://localhost/my/path+and+this+space/to/thinkup/';
     $this->assertEqual($utils_url, $expected_url);
     //with capital letters in site_root_path
     $_SERVER['HTTP_HOST'] = "localhost";
     $cfg->setValue('site_root_path', '/ThinkUp/');
     $utils_url = Utils::getApplicationURL(false);
     $expected_url = 'http://localhost/ThinkUp/';
     $this->assertEqual($utils_url, $expected_url);
     //with capital letters and spaces in site_root_path
     $_SERVER['HTTP_HOST'] = "localhost";
     $cfg->setValue('site_root_path', '/Think Up/');
     $utils_url = Utils::getApplicationURL(false);
     $expected_url = 'http://localhost/Think+Up/';
     $this->assertEqual($utils_url, $expected_url);
     //with capital letters in host and in site_root_path
     $_SERVER['HTTP_HOST'] = "LocalHost";
     $cfg->setValue('site_root_path', '/Think Up/');
     $utils_url = Utils::getApplicationURL(false);
     $expected_url = 'http://localhost/Think+Up/';
     $this->assertEqual($utils_url, $expected_url);
 }
 /**
  * Process actions based on $_GET parameters. Authorize FB user or add FB page.
  * @param arr $options Facebook plugin options
  * @param Facebook $facebook Facebook object
  */
 protected function processPageActions($options, Facebook $facebook)
 {
     //authorize user
     if (isset($_GET["code"]) && isset($_GET["state"])) {
         //validate state to avoid CSRF attacks
         if ($_GET["state"] == SessionCache::get('facebook_auth_csrf')) {
             //Prepare API request
             //First, prep redirect URI
             $redirect_uri = urlencode(Utils::getApplicationURL() . 'account/?p=facebook');
             //Build API request URL
             $api_req = 'https://graph.facebook.com/oauth/access_token?client_id=' . $options['facebook_app_id']->option_value . '&client_secret=' . $options['facebook_api_secret']->option_value . '&redirect_uri=' . $redirect_uri . '&state=' . SessionCache::get('facebook_auth_csrf') . '&code=' . $_GET["code"];
             $access_token_response = FacebookGraphAPIAccessor::rawApiRequest($api_req, false);
             parse_str($access_token_response);
             if (isset($access_token)) {
                 /**
                  * Swap in short-term token for long-lived token as per
                  * https://developers.facebook.com/docs/facebook-login/access-tokens/#extending
                  */
                 $api_req = 'https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=' . $options['facebook_app_id']->option_value . '&client_secret=' . $options['facebook_api_secret']->option_value . '&fb_exchange_token=' . $access_token;
                 $access_token_response = FacebookGraphAPIAccessor::rawApiRequest($api_req, false);
                 parse_str($access_token_response);
                 $facebook->setAccessToken($access_token);
                 $fb_user_profile = $facebook->api('/me');
                 $fb_username = $fb_user_profile['name'];
                 $fb_user_id = $fb_user_profile['id'];
                 if (empty($fb_username)) {
                     $error = 'Sorry, ThinkUp does not support business accounts.';
                     $this->addErrorMessage($error, 'authorization');
                 } else {
                     $this->addSuccessMessage($this->saveAccessToken($fb_user_id, $access_token, $fb_username), 'authorization');
                 }
             } else {
                 $error_msg = "Problem authorizing your Facebook account! Please correct your plugin settings.";
                 $error_object = json_decode($access_token_response);
                 if (isset($error_object) && isset($error_object->error->type) && isset($error_object->error->message)) {
                     $error_msg = $error_msg . "<br>Facebook says: \"" . $error_object->error->type . ": " . $error_object->error->message . "\"";
                 } else {
                     $error_msg = $error_msg . "<br>Facebook's response: \"" . $access_token_response . "\"";
                 }
                 $this->addErrorMessage($error_msg, 'authorization', true);
             }
         } else {
             $this->addErrorMessage("Could not authenticate Facebook account due to invalid CSRF token.", 'authorization');
         }
     }
     //insert pages
     if (isset($_GET["action"]) && $_GET["action"] == "add page" && isset($_GET["facebook_page_id"]) && isset($_GET["viewer_id"]) && isset($_GET["owner_id"]) && isset($_GET["instance_id"])) {
         //get access token
         $oid = DAOFactory::getDAO('OwnerInstanceDAO');
         $tokens = $oid->getOAuthTokens($_GET["instance_id"]);
         $access_token = $tokens['oauth_access_token'];
         $page_data = FacebookGraphAPIAccessor::apiRequest('/' . $_GET["facebook_page_id"], $access_token, "id,name,picture");
         self::insertPage($page_data->id, $_GET["viewer_id"], $_GET["instance_id"], $page_data->name, $page_data->picture->data->url);
     }
 }
Ejemplo n.º 15
0
 /**
  * Launch the crawler, if the latest crawler_last_run date is older than X minutes, then return a valid RSS feed.
  * @return string rendered view markup
  */
 public function authControl()
 {
     $this->setContentType('application/rss+xml; charset=UTF-8');
     $this->setViewTemplate('rss.tpl');
     $config = Config::getInstance();
     $rss_crawler_refresh_rate = $config->getValue('rss_crawler_refresh_rate');
     if (empty($rss_crawler_refresh_rate)) {
         $rss_crawler_refresh_rate = 20;
         // minutes
     }
     $base_url = Utils::getApplicationURL();
     $crawler_plugin_registrar_launched = false;
     $instance_dao = DAOFactory::getDAO('InstanceDAO');
     $email = $this->getLoggedInUser();
     $owner = parent::getOwner($email);
     $freshest_instance = $instance_dao->getFreshestByOwnerId($owner->id);
     if ($freshest_instance) {
         $crawler_plugin_registrar_last_run = strtotime($freshest_instance->crawler_last_run);
     }
     if ($freshest_instance && $crawler_plugin_registrar_last_run < time() - $rss_crawler_refresh_rate * 60) {
         $crawler_plugin_registrar_run_url = $base_url . 'crawler/run.php?' . sprintf('un=%s&as=%s', $email, $owner->api_key);
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $crawler_plugin_registrar_run_url);
         curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
         // seconds
         curl_setopt($ch, CURLOPT_TIMEOUT, 5);
         // seconds
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($ch, CURLOPT_HEADER, true);
         $result = curl_exec($ch);
         curl_close($ch);
         $body = substr($result, strpos($result, "\r\n\r\n") + 4);
         if (strpos($result, 'Content-Type: application/json') && function_exists('json_decode')) {
             $json = json_decode($body);
             if (isset($json->error)) {
                 $crawler_plugin_registrar_launched = false;
             } else {
                 if (isset($json->result) && $json->result == 'success') {
                     $crawler_plugin_registrar_launched = true;
                 }
             }
         } else {
             if (strpos($body, 'Error starting crawler') !== FALSE) {
                 $crawler_plugin_registrar_launched = false;
             } else {
                 $crawler_plugin_registrar_launched = true;
             }
         }
     }
     $items = array();
     $logger = Logger::getInstance();
     // Don't return an item if there is a crawler log defined;
     // it would just duplicate the information available in that file.
     if ($crawler_plugin_registrar_launched && !isset($logger->log)) {
         $title = 'ThinkUp crawl started on ' . date('Y-m-d H:i:s');
         $link = $base_url . 'rss.php?d=' . urlencode(date('Y-m-d H:i:s'));
         $description = "Last ThinkUp crawl ended on {$freshest_instance->crawler_last_run}<br />A new crawl " . "was started just now, since it's been more than {$rss_crawler_refresh_rate} minutes since the last run.";
         $items[] = self::createRSSItem($title, $link, $description);
     }
     $items = array_merge($items, $this->getAdditionalItems($base_url));
     //Add insights to RSS feed
     $insight_dao = DAOFactory::getDAO('InsightDAO');
     if ($this->isAdmin()) {
         ///show all insights for all service users
         $insights = $insight_dao->getAllInstanceInsights($page_count = InsightStreamController::PAGE_INSIGHTS_COUNT + 1, 1);
     } else {
         //show only service users owner owns
         $owner_dao = DAOFactory::getDAO('OwnerDAO');
         $owner = $owner_dao->getByEmail($this->getLoggedInUser());
         $insights = $insight_dao->getAllOwnerInstanceInsights($owner->id, $page_count = InsightStreamController::PAGE_INSIGHTS_COUNT + 1, 1);
     }
     if (sizeof($insights) == 0) {
         $title = 'No insights exist on ' . date('Y-m-d H:i:s');
         $link = $base_url . 'rss.php?d=' . urlencode(date('Y-m-d H:i:s'));
         $description = "ThinkUp doesn't have any insights to show you. Check your crawler log to make sure " . "ThinkUp is capturing data.";
         $items[] = self::createRSSItem($title, $link, $description);
     } else {
         foreach ($insights as $insight) {
             $username_in_title = ($insight->instance->network == 'twitter' ? '@' : '') . $insight->instance->network_username;
             $title = str_replace(':', '', $insight->headline) . " (" . $username_in_title . ")";
             $link = $base_url . '?u=' . $insight->instance->network_username . '&n=' . urlencode($insight->instance->network) . '&d=' . urlencode(date('Y-m-d', strtotime($insight->date))) . '&s=' . urlencode($insight->slug);
             $description = $insight->headline . " " . $insight->text . '<br><a href="' . $link . '">Link</a>';
             $time = strtotime($insight->date);
             $items[] = self::createRSSItem($title, $link, $description, $time);
         }
     }
     $this->addToView('items', $items);
     $this->addToView('logged_in_user', htmlspecialchars($this->getLoggedInUser()));
     $this->addToView('rss_crawler_refresh_rate', htmlspecialchars($rss_crawler_refresh_rate));
     return $this->generateView();
 }
 /**
  * Step 3 - Populate database and finish
  */
 private function step3()
 {
     $this->setViewTemplate('install.step3.tpl');
     $config_file_exists = false;
     $config_file = THINKUP_WEBAPP_PATH . 'config.inc.php';
     // make sure we are here with posted data
     if (empty($_POST)) {
         $this->step1();
         return;
     }
     // check if we have made config.inc.php
     if (file_exists($config_file) && filesize($config_file) > 0) {
         // this is could be from step 2 is not able writing
         // to webapp dir
         $config_file_exists = true;
         require $config_file;
         $db_config['db_type'] = $THINKUP_CFG['db_type'];
         $db_config['db_name'] = $THINKUP_CFG['db_name'];
         $db_config['db_user'] = $THINKUP_CFG['db_user'];
         $db_config['db_password'] = $THINKUP_CFG['db_password'];
         $db_config['db_host'] = $THINKUP_CFG['db_host'];
         $db_config['db_socket'] = $THINKUP_CFG['db_socket'];
         $db_config['db_port'] = $THINKUP_CFG['db_port'];
         $db_config['table_prefix'] = $THINKUP_CFG['table_prefix'];
         $db_config['timezone'] = $THINKUP_CFG['timezone'];
         $email = trim($_POST['site_email']);
     } else {
         // make sure we're not from error or couldn't write config.inc.php
         if (!isset($_POST['db_user']) && !isset($_POST['db_passwd']) && !isset($_POST['db_name']) && !isset($_POST['db_host'])) {
             $this->addErrorMessage("Missing database credentials");
             $this->step2();
             return;
         }
         // trim each posted value
         $db_config['db_type'] = trim(@$_POST['db_type']);
         $db_config['db_name'] = trim($_POST['db_name']);
         $db_config['db_user'] = trim($_POST['db_user']);
         $db_config['db_password'] = trim($_POST['db_passwd']);
         $db_config['db_host'] = trim($_POST['db_host']);
         $db_config['db_socket'] = trim($_POST['db_socket']);
         $db_config['db_port'] = trim($_POST['db_port']);
         $db_config['table_prefix'] = trim($_POST['db_prefix']);
         $db_config['timezone'] = trim($_POST['timezone']);
         $email = trim($_POST['site_email']);
     }
     $db_config['db_type'] = 'mysql';
     //default for now
     $password = $_POST['password'];
     $confirm_password = $_POST['confirm_password'];
     $full_name = $_POST['full_name'];
     $display_errors = false;
     // check email
     if (!Utils::validateEmail($email)) {
         $this->addErrorMessage("Please enter a valid email address.", "email");
         $display_errors = true;
     }
     if ($password != $confirm_password || $password == '' || !preg_match("/(?=.{8,})(?=.*[a-zA-Z])(?=.*[0-9])/", $password)) {
         //check password
         if ($password != $confirm_password) {
             $this->addErrorMessage("Your passwords did not match.", "password");
         } else {
             if ($password == '') {
                 $this->addErrorMessage("Please choose a password.", "password");
             } else {
                 if (!preg_match("/(?=.{8,})(?=.*[a-zA-Z])(?=.*[0-9])/", $password)) {
                     $this->addErrorMessage("Password must be at least 8 characters and contain both numbers and letters.", "password");
                 }
             }
         }
         $display_errors = true;
     }
     if ($_POST['db_name'] == '') {
         $this->addErrorMessage("Please enter a database name.", "database_name");
         $display_errors = true;
     }
     if ($_POST['db_host'] == '') {
         $this->addErrorMessage("Please enter a database host.", "database_host");
         $display_errors = true;
     }
     if ($_POST['timezone'] == '') {
         $this->addErrorMessage("Please select a time zone.", "timezone");
         $display_errors = true;
     }
     if (($error = $this->installer->checkDb($db_config)) !== true) {
         //check db
         if (($p = strpos($error->getMessage(), "Unknown MySQL server host")) !== false || ($p = strpos($error->getMessage(), "Can't connect to MySQL server")) !== false || ($p = strpos($error->getMessage(), "Can't connect to local MySQL server through socket")) !== false || ($p = strpos($error->getMessage(), "Access denied for user")) !== false) {
             $db_error = substr($error->getMessage(), $p);
         } else {
             $db_error = $error->getMessage();
         }
         $disable_xss = true;
         $db_error = filter_var($db_error, FILTER_SANITIZE_SPECIAL_CHARS);
         $this->addErrorMessage("ThinkUp couldn't connect to your database. The error message is:<br /> " . " <strong>{$db_error}</strong><br />Please correct your database information and try again.", "database", $disable_xss);
         $display_errors = true;
     }
     if ($display_errors) {
         $this->setViewTemplate('install.step2.tpl');
         $this->addToView('db_name', $db_config['db_name']);
         $this->addToView('db_user', $db_config['db_user']);
         $this->addToView('db_passwd', $db_config['db_password']);
         $this->addToView('db_host', $db_config['db_host']);
         $this->addToView('db_prefix', $db_config['table_prefix']);
         $this->addToView('db_socket', $db_config['db_socket']);
         $this->addToView('db_port', $db_config['db_port']);
         $this->addToView('db_type', $db_config['db_type']);
         $this->addToView('current_tz', $_POST['timezone']);
         $this->addToView('tz_list', $this->getTimeZoneList());
         $this->addToView('site_email', $email);
         $this->addToView('full_name', $full_name);
         return;
     }
     $admin_user = array('email' => $email, 'password' => $password, 'confirm_password' => $confirm_password);
     // trying to create config file
     if (!$config_file_exists && !$this->installer->createConfigFile($db_config, $admin_user)) {
         $config_file_contents_arr = $this->installer->generateConfigFile($db_config, $admin_user);
         $config_file_contents_str = '';
         foreach ($config_file_contents_arr as $line) {
             $config_file_contents_str .= htmlentities($line);
         }
         $whoami = @exec('whoami');
         $disable_xss = true;
         if (!empty($whoami)) {
             $whoami = filter_var($whoami, FILTER_SANITIZE_SPECIAL_CHARS);
             $this->addErrorMessage("ThinkUp couldn't write the <code>config.inc.php</code> file.<br /><br />" . "Use root (or sudo) to create the file manually, and allow PHP to write to it, by executing the " . "following commands:<br /><code>sudo touch " . escapeshellcmd(THINKUP_WEBAPP_PATH . "config.inc.php") . "</code><br /><code>sudo chown {$whoami} " . escapeshellcmd(THINKUP_WEBAPP_PATH . "config.inc.php") . "</code><br /><br />If you don't have root access, create the <code>" . THINKUP_WEBAPP_PATH . "config.inc.php</code> file, show the contents of your config file below," . " and copy and paste the text into the <code>config.inc.php</code> file.", null, $disable_xss);
         } else {
             $this->addErrorMessage("ThinkUp couldn't write the <code>config.inc.php</code> file.<br /><br />" . "You will need to create the <code>" . THINKUP_WEBAPP_PATH . "config.inc.php</code> file manually, and paste the following text into it.", null, $disable_xss);
         }
         $this->addToView('config_file_contents', $config_file_contents_str);
         $this->addToView('_POST', $_POST);
         $this->setViewTemplate('install.config.tpl');
         return;
     }
     unset($admin_user['confirm_password']);
     // check tables
     $this->installer->checkTable($db_config);
     // if empty, we're ready to populate the database with ThinkUp tables
     $this->installer->populateTables($db_config);
     //Set the application server name in app settings for access by command-line scripts
     Installer::storeServerName();
     $owner_dao = DAOFactory::getDAO('OwnerDAO', $db_config);
     if (!$owner_dao->doesAdminExist() && !$owner_dao->doesOwnerExist($email)) {
         // create admin if not exists
         $activation_code = $owner_dao->createAdmin($email, $password, $full_name);
         // view for email
         $cfg_array = array('site_root_path' => Utils::getSiteRootPathFromFileSystem(), 'source_root_path' => THINKUP_ROOT_PATH, 'debug' => false, 'app_title_prefix' => "", 'cache_pages' => false);
         $email_view = new ViewManager($cfg_array);
         $email_view->caching = false;
         $email_view->assign('application_url', Utils::getApplicationURL());
         $email_view->assign('email', urlencode($email));
         $email_view->assign('activ_code', $activation_code);
         $message = $email_view->fetch('_email.registration.tpl');
         Mailer::mail($email, "Activate Your New ThinkUp  Account", $message);
     } else {
         $email = 'Use your old email admin';
         $password = '******';
     }
     unset($THINKUP_CFG);
     $this->addToView('errors', $this->installer->getErrorMessages());
     $this->addToView('username', $email);
     $this->addToView('password', $password);
     $this->addToView('login_url', Utils::getSiteRootPathFromFileSystem() . 'session/login.php');
 }
 public function authControl()
 {
     $this->disableCaching();
     $this->addHeaderJavaScript('assets/js/jqBootstrapValidation.js');
     $this->addHeaderJavaScript('assets/js/validate-fields.js');
     $this->addHeaderJavaScript('assets/js/jstz-1.0.4.min.js');
     $owner_dao = DAOFactory::getDAO('OwnerDAO');
     $invite_dao = DAOFactory::getDAO('InviteDAO');
     $owner = $owner_dao->getByEmail($this->getLoggedInUser());
     $this->addToView('owner', $owner);
     $this->addToView('notification_options', $this->notification_frequencies);
     $this->addToView('tz_list', Installer::getTimeZoneList());
     $this->view_mgr->addHelp('api', 'userguide/api/posts/index');
     $this->view_mgr->addHelp('application_settings', 'userguide/settings/application');
     $this->view_mgr->addHelp('users', 'userguide/settings/allaccounts');
     $this->view_mgr->addHelp('backup', 'install/backup');
     $this->view_mgr->addHelp('account', 'userguide/settings/account');
     //process password change
     if (isset($_POST['changepass']) && $_POST['changepass'] == 'Change password' && isset($_POST['oldpass']) && isset($_POST['pass1']) && isset($_POST['pass2'])) {
         // Check their old password is correct
         if (!$owner_dao->isOwnerAuthorized($this->getLoggedInUser(), $_POST['oldpass'])) {
             $this->addErrorMessage("Password is incorrect.", 'password');
         } elseif ($_POST['pass1'] != $_POST['pass2']) {
             $this->addErrorMessage("New passwords did not match. Your password has not been changed.", 'password');
         } elseif (!preg_match("/(?=.{8,})(?=.*[a-zA-Z])(?=.*[0-9])/", $_POST['pass1'])) {
             $this->addErrorMessage("Your new password must be at least 8 characters and contain both numbers " . "and letters. Your password has not been changed.", 'password');
         } else {
             // verify CSRF token
             $this->validateCSRFToken();
             // Try to update the password
             if ($owner_dao->updatePassword($this->getLoggedInUser(), $_POST['pass1']) < 1) {
                 $this->addErrorMessage("Your password has NOT been updated.", 'password');
             } else {
                 $this->addSuccessMessage("Your password has been updated.", 'password');
             }
         }
     }
     //reset api_key
     if (isset($_POST['reset_api_key']) && $_POST['reset_api_key'] == 'Reset API Key') {
         $this->validateCSRFToken();
         $api_key = $owner_dao->resetAPIKey($owner->id);
         if (!$api_key) {
             throw new Exception("Unbale to update user's api_key, something bad must have happened");
         }
         $this->addSuccessMessage("Your API Key has been reset! Please update your ThinkUp RSS feed subscription.", 'api_key');
         $owner->api_key = $api_key;
     }
     // process invite
     if (isset($_POST['invite']) && $_POST['invite'] == 'Create Invitation') {
         // verify CSRF token
         $this->validateCSRFToken();
         $invite_code = substr(md5(uniqid(rand(), true)), 0, 10);
         $invite_added = $invite_dao->addInviteCode($invite_code);
         if ($invite_added == 1) {
             //invite generated and inserted
             $invite_link = Utils::getApplicationURL() . 'session/register.php?code=' . $invite_code;
             $this->addSuccessMessage("Invitation created!<br />Copy this link and send it to someone you want to " . 'invite to register on your ThinkUp installation.<br /><a href="' . $invite_link . '" id="clippy_12345">' . $invite_link . '</a>
               <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
                       width="100"
                       height="14"
                       class="clippy"
                       id="clippy" >
               <param name="movie" value="' . Utils::getApplicationURL() . 'assets/flash/clippy.swf"/>
               <param name="allowScriptAccess" value="always" />
               <param name="quality" value="high" />
               <param name="scale" value="noscale" />
               <param NAME="FlashVars" value="id=clippy_12345&amp;copied=copied!&amp;copyto=copy to clipboard">
               <param name="bgcolor" value="#D5F0FC">
               <param name="wmode" value="opaque">
               <embed src="' . Utils::getApplicationURL() . 'assets/flash/clippy.swf"
                      width="100"
                      height="14"
                      name="clippy"
                      quality="high"
                      allowScriptAccess="always"
                      type="application/x-shockwave-flash"
                      pluginspage="http://www.macromedia.com/go/getflashplayer"
                      FlashVars="id=clippy_12345&amp;copied=copied!&amp;copyto=copy to clipboard"
                      bgcolor="#dff0d8"
                      wmode="opaque"/></object>
             <br /> Good for one new registration. Expires in 7 days.', 'invite', true);
         } else {
             $this->addErrorMessage("There was an error creating a new invite. Please try again.", 'invite');
         }
     }
     //process service user deletion
     if (isset($_POST['action']) && $_POST['action'] == 'Delete' && isset($_POST['instance_id']) && is_numeric($_POST['instance_id']) && !isset($_POST['hashtag_id']) && !isset($_POST['new_hashtag_name'])) {
         $owner_instance_dao = DAOFactory::getDAO('OwnerInstanceDAO');
         $instance_dao = DAOFactory::getDAO('InstanceDAO');
         $instancehashtag_dao = DAOFactory::getDAO('InstanceHashtagDAO');
         $hashtagpost_dao = DAOFactory::getDAO('HashtagPostDAO');
         $hashtag_dao = DAOFactory::getDAO('HashtagDAO');
         $instance = $instance_dao->get($_POST['instance_id']);
         $message = '';
         if (isset($instance)) {
             // verify CSRF token
             $this->validateCSRFToken();
             if ($this->isAdmin()) {
                 //Retrieve this instance's saved searches
                 $instances_hashtags = $instancehashtag_dao->getByInstance($instance->id);
                 $deleted_searches = 0;
                 foreach ($instances_hashtags as $instance_hashtag) {
                     $hashtag_id = $instance_hashtag->hashtag_id;
                     $deleted_searches += $instancehashtag_dao->delete($instance_hashtag->instance_id, $hashtag_id);
                     //Continue deletions if no other owner has saved this search
                     if (!$instancehashtag_dao->isHashtagSaved($hashtag_id)) {
                         $deleted_searchposts = $hashtagpost_dao->deleteHashtagsPostsByHashtagID($hashtag_id);
                         $deleted_hashtag = $hashtag_dao->deleteHashtagByID($hashtag_id);
                     }
                 }
                 //delete all owner_instances
                 $owner_instance_dao->deleteByInstance($instance->id);
                 //delete instance
                 $instance_dao->delete($instance->network_username, $instance->network);
                 $this->addSuccessMessage('Account ' . ($deleted_searches > 0 ? 'and its saved searches ' : '') . 'deleted.', 'account');
             } else {
                 if ($owner_instance_dao->doesOwnerHaveAccessToInstance($owner, $instance)) {
                     //delete owner instance
                     $total_deletions = $owner_instance_dao->delete($owner->id, $instance->id);
                     if ($total_deletions > 0) {
                         //delete instance if no other owners have it
                         $remaining_owner_instances = $owner_instance_dao->getByInstance($instance->id);
                         $deleted_searches = 0;
                         if (sizeof($remaining_owner_instances) == 0) {
                             //Retrieve this instance's saved searches
                             $instances_hashtags = $instancehashtag_dao->getByInstance($instance->id);
                             foreach ($instances_hashtags as $instance_hashtag) {
                                 $hashtag_id = $instance_hashtag->hashtag_id;
                                 $deleted_searches += $instancehashtag_dao->delete($instance_hashtag->instance_id, $hashtag_id);
                                 //Continue deletions if no other owner has saved this search
                                 if (!$instancehashtag_dao->isHashtagSaved($hashtag_id)) {
                                     $deleted_searchposts = $hashtagpost_dao->deleteHashtagsPostsByHashtagID($hashtag_id);
                                     $deleted_hashtag = $hashtag_dao->deleteHashtagByID($hashtag_id);
                                 }
                             }
                             $instance_dao->delete($instance->network_username, $instance->network);
                         }
                         $this->addSuccessMessage('Account ' . ($deleted_searches > 0 ? 'and its saved searches ' : '') . 'deleted.', 'account');
                     }
                 } else {
                     $this->addErrorMessage('Insufficient privileges.', 'account');
                 }
             }
         } else {
             $this->addErrorMessage('Instance doesn\'t exist.', 'account');
         }
     }
     //process hashtag deletion
     if (isset($_POST['action']) && $_POST['action'] == 'Delete' && isset($_POST['hashtag_id']) && is_numeric($_POST['hashtag_id']) && isset($_POST['instance_id']) && is_numeric($_POST['instance_id'])) {
         $instancehashtag_dao = DAOFactory::getDAO('InstanceHashtagDAO');
         $hashtag_dao = DAOFactory::getDAO('HashtagDAO');
         $hashtagpost_dao = DAOFactory::getDAO('HashtagPostDAO');
         $hashtag_id = $_POST['hashtag_id'];
         $instance_id = $_POST['instance_id'];
         $instance_dao = DAOFactory::getDAO('InstanceDAO');
         $instance = $instance_dao->get($instance_id);
         if (isset($instance)) {
             $instances_hashtags_deleted = $instancehashtag_dao->delete($instance_id, $hashtag_id);
             if (!$instancehashtag_dao->isHashtagSaved($hashtag_id)) {
                 $deleted_searchposts = $hashtagpost_dao->deleteHashtagsPostsByHashtagID($hashtag_id);
                 $deleted_hashtag = $hashtag_dao->deleteHashtagByID($hashtag_id);
             }
             $message = "Deleted saved search.";
             $this->addSuccessMessage($message, 'account');
         } else {
             $this->addErrorMessage('Instance doesn\'t exist.', 'account');
         }
     }
     //process service user hashtag addition
     if (isset($_POST['action']) && $_POST['action'] == 'Save search' && isset($_POST['new_hashtag_name']) && $_POST['new_hashtag_name'] != '' && isset($_POST['instance_id']) && is_numeric($_POST['instance_id'])) {
         $instancehashtag_dao = DAOFactory::getDAO('InstanceHashtagDAO');
         $hashtag_dao = DAOFactory::getDAO('HashtagDAO');
         $instance_id = $_POST['instance_id'];
         $new_hashtag_name = $_POST['new_hashtag_name'];
         //Check if $new_hashtag_name is an individual word (no spaces)
         if (strpos($new_hashtag_name, " ") === false) {
             $instance_dao = DAOFactory::getDAO('InstanceDAO');
             $instance = $instance_dao->get($instance_id);
             if (isset($instance)) {
                 $hashtag = $hashtag_dao->getHashtag($new_hashtag_name, $instance->network);
                 if (!isset($hashtag)) {
                     $hashtag_id = $hashtag_dao->insertHashtag($new_hashtag_name, $instance->network);
                     $row_inserted = $instancehashtag_dao->insert($instance_id, $hashtag_id);
                     $message = "Saved search for " . $new_hashtag_name . ".";
                     $this->addSuccessMessage($message, 'account');
                 } else {
                     $row_inserted = $instancehashtag_dao->insert($instance_id, $hashtag->id);
                     $message = "Saved search for " . $new_hashtag_name . ".";
                     $this->addSuccessMessage($message, 'account');
                 }
             } else {
                 $this->addErrorMessage('Instance doesn\'t exist.', 'account');
             }
         } else {
             $this->addErrorMessage('You can only search for an individual keyword or hashtag, not a phrase. ' . 'Please try again.', 'account');
         }
     }
     //process change to notification frequency
     if (isset($_POST['updatefrequency'])) {
         $this->validateCSRFToken();
         $new_freq = isset($_POST['notificationfrequency']) ? $_POST['notificationfrequency'] : null;
         $updates = 0;
         if ($new_freq && isset($this->notification_frequencies[$new_freq])) {
             $updates = $owner_dao->setEmailNotificationFrequency($this->getLoggedInUser(), $new_freq);
         }
         if ($updates > 0) {
             // Update the user in the view to match
             $owner->email_notification_frequency = $new_freq;
             $this->addToView('owner', $owner);
             $this->addSuccessMessage('Your email notification frequency has been updated.', 'notifications');
         }
     }
     //process change to timezone
     if (isset($_POST['updatetimezone'])) {
         $this->validateCSRFToken();
         $new_tz = isset($_POST['timezone']) ? $_POST['timezone'] : null;
         $updates = 0;
         if (isset($new_tz)) {
             $possible_timezones = timezone_identifiers_list();
             if (in_array($new_tz, $possible_timezones)) {
                 $updates = $owner_dao->setTimezone($this->getLoggedInUser(), $new_tz);
             }
         }
         if ($updates > 0) {
             // Update the user in the view to match
             $owner->timezone = $new_tz;
             $this->addToView('owner', $owner);
             $this->addSuccessMessage('Your time zone has been saved.', 'timezone');
         }
     }
     $this->view_mgr->clear_all_cache();
     /* Begin plugin-specific configuration handling */
     if (isset($_GET['p']) && !isset($_GET['u'])) {
         // add config js to header
         if ($this->isAdmin()) {
             $this->addHeaderJavaScript('assets/js/plugin_options.js');
         }
         $active_plugin = $_GET['p'];
         $webapp_plugin_registrar = PluginRegistrarWebapp::getInstance();
         $pobj = $webapp_plugin_registrar->getPluginObject($active_plugin);
         $p = new $pobj();
         $this->addToView('body', $p->renderConfiguration($owner));
         $this->addToView('force_plugin', true);
         $profiler = Profiler::getInstance();
         $profiler->clearLog();
     } elseif (isset($_GET['p']) && isset($_GET['u']) && isset($_GET['n'])) {
         if ($this->isAdmin()) {
             $this->addHeaderJavaScript('assets/js/plugin_options.js');
         }
         $active_plugin = $_GET['p'];
         $instance_username = $_GET['u'];
         $instance_network = $_GET['n'];
         $webapp_plugin_registrar = PluginRegistrarWebapp::getInstance();
         $pobj = $webapp_plugin_registrar->getPluginObject($active_plugin);
         $p = new $pobj();
         $this->addToView('body', $p->renderInstanceConfiguration($owner, $instance_username, $instance_network));
         $this->addToView('force_plugin', true);
         $profiler = Profiler::getInstance();
         $profiler->clearLog();
     }
     $plugin_dao = DAOFactory::getDAO('PluginDAO');
     $config = Config::getInstance();
     $installed_plugins = $plugin_dao->getInstalledPlugins();
     $this->addToView('installed_plugins', $installed_plugins);
     /* End plugin-specific configuration handling */
     if ($owner->is_admin) {
         if (!isset($instance_dao)) {
             $instance_dao = DAOFactory::getDAO('InstanceDAO');
         }
         $owners = $owner_dao->getAllOwners();
         foreach ($owners as $o) {
             $instances = $instance_dao->getByOwner($o, true);
             $o->setInstances($instances);
         }
         $this->addToView('owners', $owners);
         $this->addToView('public_instances', $instance_dao->getPublicInstances());
     }
     $whichphp = @exec('which php');
     $php_path = !empty($whichphp) ? $whichphp : 'php';
     $email = $this->getLoggedInUser();
     //rss_crawl_url
     $rss_crawl_url = Utils::getApplicationURL() . sprintf('crawler/rss.php?un=%s&as=%s', urlencode($email), $owner->api_key);
     $this->addToView('rss_crawl_url', $rss_crawl_url);
     //cli_crawl_command
     $cli_crawl_command = 'cd ' . THINKUP_WEBAPP_PATH . 'crawler/;export THINKUP_PASSWORD=yourpassword; ' . $php_path . ' crawl.php ' . $email;
     $this->addToView('cli_crawl_command', $cli_crawl_command);
     //help link
     $this->view_mgr->addHelp('rss', 'userguide/datacapture');
     return $this->generateView();
 }
Ejemplo n.º 18
0
 public function testGetOAuthTokensWithAndWithoutSSL()
 {
     $gpc = new GooglePlusCrawler($this->profile1_instance, 'fauxaccesstoken', 10);
     //test getting token with HTTPS
     $_SERVER['SERVER_NAME'] = 'test';
     $_SERVER['HTTPS'] = 'y';
     $cfg = Config::getInstance();
     $cfg->setValue('site_root_path', '/');
     $redirect_uri = urlencode(Utils::getApplicationURL() . 'account/?p=google%2B');
     $tokens = $gpc->getOAuthTokens('ci', 'cs', 'tc1', 'authorization_code', $redirect_uri);
     $this->assertEqual($tokens->access_token, 'faux-access-token-with-https');
     $this->assertEqual($tokens->refresh_token, 'faux-refresh-token-with-https');
     //test getting token without HTTPS
     $_SERVER['HTTPS'] = null;
     $redirect_uri = urlencode(Utils::getApplicationURL() . 'account/?p=google%2B');
     $tokens = $gpc->getOAuthTokens('ci', 'cs', 'tc1', 'authorization_code', $redirect_uri);
     $this->assertEqual($tokens->access_token, 'faux-access-token-without-https');
     $this->assertEqual($tokens->refresh_token, 'faux-refresh-token-without-https');
 }
 public function authControl()
 {
     // Get an instance
     $config = Config::getInstance();
     // Set up some constants
     Loader::definePathConstants();
     // Set the view to the account index page for this plugin
     $this->setViewTemplate(THINKUP_WEBAPP_PATH . 'plugins/foursquare/view/foursquare.account.index.tpl');
     // URL to the help page for this plugin
     $this->view_mgr->addHelp('foursquare', 'userguide/settings/plugins/foursquare');
     // Set some option fields on the template page
     // Set the client ID text field
     $name_field = array('name' => 'foursquare_client_id', 'label' => 'Client ID', 'size' => 48);
     // Set the default value to be blank
     $name_field['default_value'] = '';
     // Add the element to the page
     $this->addPluginOption(self::FORM_TEXT_ELEMENT, $name_field);
     // Set a message saying this field is required
     $this->addPluginOptionRequiredMessage('foursquare_client_id', 'A client id is requried to use foursquare');
     // Set the client secret field
     $name_field = array('name' => 'foursquare_client_secret', 'label' => 'Client Secret', 'size' => 48);
     // Set the default value to be blank
     $name_field['default_value'] = '';
     // Add the element to the page
     $this->addPluginOption(self::FORM_TEXT_ELEMENT, $name_field);
     // Set a message saying this field is required
     $this->addPluginOptionRequiredMessage('foursquare_client_secret', 'A client secret is requried to use foursquare');
     // Get a data access object so we can get the options for the plugin from the database
     $plugin_option_dao = DAOFactory::getDAO('PluginOptionDAO');
     // Get a cached hash of the options from the database
     $options = $plugin_option_dao->getOptionsHash('foursquare', true);
     // Create a new plugin object
     $plugin = new FoursquarePlugin();
     // If the plugin is configured
     if ($plugin->isConfigured()) {
         // Set up the interactions
         $this->setUpFoursquareInteractions($options);
         // Indicate on the view that this plugin is configured
         $this->addToView('is_configured', true);
     } else {
         // If the plugin isn't configured
         // Tell the user that this plugin needs configuring
         $this->addInfoMessage('Please complete plugin setup to start using it', 'setup');
         // Indicate on the view that this plugin is not configured
         $this->addToView('is_configured', false);
     }
     $this->addToView('thinkup_site_url', Utils::getApplicationURL());
     // Display the foursquare account index page
     return $this->generateView();
 }
 /**
  * Send out insight email digest for a given time period.
  * @param Owner $owner Owner to send for
  * @param str $start When to start insight lookup
  * @param str $template Email view template to use
  * @param array $options Plugin options
  * return bool Whether email was sent
  */
 private function sendDigestSinceWithTemplate($owner, $start, $template, &$options)
 {
     $insights_dao = DAOFactory::GetDAO('InsightDAO');
     $start_time = date('Y-m-d H:i:s', strtotime($start, $this->current_timestamp));
     $insights = $insights_dao->getAllOwnerInstanceInsightsSince($owner->id, $start_time);
     if (count($insights) == 0) {
         return false;
     }
     $config = Config::getInstance();
     $view = new ViewManager();
     $view->caching = false;
     // If we've got a Mandrill key and template, send HTML
     if ($config->getValue('mandrill_api_key') != null && !empty($options['mandrill_template'])) {
         $view->assign('insights', $insights);
         $insights = $view->fetch(Utils::getPluginViewDirectory($this->folder_name) . '_email.insights_html.tpl');
         $parameters = array();
         $parameters['insights'] = $insights;
         $parameters['app_title'] = $config->getValue('app_title_prefix') . "ThinkUp";
         $parameters['app_url'] = Utils::getApplicationURL();
         $parameters['unsub_url'] = Utils::getApplicationURL() . 'account/index.php?m=manage#instances';
         // It's a weekly digest if we're going back more than a day or two.
         $days_ago = ($this->current_timestamp - strtotime($start)) / (60 * 60 * 24);
         $parameters['weekly_or_daily'] = $days_ago > 2 ? 'Weekly' : 'Daily';
         try {
             Mailer::mailHTMLViaMandrillTemplate($owner->email, 'ThinkUp has new insights for you!', $options['mandrill_template']->option_value, $parameters);
             return true;
         } catch (Mandrill_Unknown_Template $e) {
             // In this case, we'll fall back to plain text sending and warn the user in the log
             $logger = Logger::getInstance();
             $logger->logUserError("Invalid mandrill template configured:" . $options['mandrill_template']->option_value . ".", __METHOD__ . ',' . __LINE__);
             unset($options['mandrill_template']);
         }
     }
     $view->assign('apptitle', $config->getValue('app_title_prefix') . "ThinkUp");
     $view->assign('application_url', Utils::getApplicationURL());
     $view->assign('insights', $insights);
     $message = $view->fetch(Utils::getPluginViewDirectory($this->folder_name) . $template);
     list($subject, $message) = explode("\n", $message, 2);
     Mailer::mail($owner->email, $subject, $message);
     return true;
 }
 public function authControl()
 {
     $this->disableCaching();
     //passsswd reset validation
     $this->addHeaderCSS('assets/css/validate_password.css');
     $this->addHeaderJavaScript('assets/js/jquery.validate.min.js');
     $this->addHeaderJavaScript('assets/js/jquery.validate.password.js');
     $this->addHeaderJavaScript('assets/js/validate_password.js');
     $webapp = Webapp::getInstance();
     $owner_dao = DAOFactory::getDAO('OwnerDAO');
     $invite_dao = DAOFactory::getDAO('InviteDAO');
     $owner = $owner_dao->getByEmail($this->getLoggedInUser());
     $this->addToView('owner', $owner);
     $this->addToView('logo_link', '');
     $this->view_mgr->addHelp('api', 'userguide/api/posts/index');
     $this->view_mgr->addHelp('application_settings', 'userguide/settings/application');
     $this->view_mgr->addHelp('users', 'userguide/settings/allaccounts');
     $this->view_mgr->addHelp('backup', 'install/backup');
     $this->view_mgr->addHelp('account', 'userguide/settings/account');
     //process password change
     if (isset($_POST['changepass']) && $_POST['changepass'] == 'Change password' && isset($_POST['oldpass']) && isset($_POST['pass1']) && isset($_POST['pass2'])) {
         // Check their old password is correct
         if (!$owner_dao->isOwnerAuthorized($this->getLoggedInUser(), $_POST['oldpass'])) {
             $this->addErrorMessage("Old password does not match or empty.", 'password');
         } elseif ($_POST['pass1'] != $_POST['pass2']) {
             $this->addErrorMessage("New passwords did not match. Your password has not been changed.", 'password');
         } elseif (!preg_match("/(?=.{8,})(?=.*[a-zA-Z])(?=.*[0-9])/", $_POST['pass1'])) {
             $this->addErrorMessage("Your new password must be at least 8 characters and contain both numbers " . "and letters. Your password has not been changed.", 'password');
         } else {
             // verify CSRF token
             $this->validateCSRFToken();
             // Try to update the password
             if ($owner_dao->updatePassword($this->getLoggedInUser(), $_POST['pass1']) < 1) {
                 $this->addErrorMessage("Your password has NOT been updated.", 'password');
             } else {
                 $this->addSuccessMessage("Your password has been updated.", 'password');
             }
         }
     }
     //reset api_key
     if (isset($_POST['reset_api_key']) && $_POST['reset_api_key'] == 'Reset API Key') {
         $this->validateCSRFToken();
         $api_key = $owner_dao->resetAPIKey($owner->id);
         if (!$api_key) {
             throw new Exception("Unbale to update user's api_key, something bad must have happened");
         }
         $this->addSuccessMessage("Your API Key has been reset! Please update your ThinkUp RSS feed subscription.", 'api_key');
         $owner->api_key = $api_key;
     }
     // process invite
     if (isset($_POST['invite']) && $_POST['invite'] == 'Create Invitation') {
         // verify CSRF token
         $this->validateCSRFToken();
         $invite_code = substr(md5(uniqid(rand(), true)), 0, 10);
         $invite_added = $invite_dao->addInviteCode($invite_code);
         if ($invite_added == 1) {
             //invite generated and inserted
             $server = $_SERVER['HTTP_HOST'];
             $invite_link = Utils::getApplicationURL() . 'session/register.php?code=' . $invite_code;
             $this->addSuccessMessage("Invitation created!<br />Copy this link and send it to someone you want to " . 'invite to register on your ThinkUp installation.<br /><a href="' . $invite_link . '" id="clippy_12345">' . $invite_link . '</a>
               <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
                       width="100"
                       height="14"
                       class="clippy"
                       id="clippy" >
               <param name="movie" value="' . Utils::getApplicationURL() . 'assets/flash/clippy.swf"/>
               <param name="allowScriptAccess" value="always" />
               <param name="quality" value="high" />
               <param name="scale" value="noscale" />
               <param NAME="FlashVars" value="id=clippy_12345&amp;copied=copied!&amp;copyto=copy to clipboard">
               <param name="bgcolor" value="#D5F0FC">
               <param name="wmode" value="opaque">
               <embed src="' . Utils::getApplicationURL() . 'assets/flash/clippy.swf"
                      width="100"
                      height="14"
                      name="clippy"
                      quality="high"
                      allowScriptAccess="always"
                      type="application/x-shockwave-flash"
                      pluginspage="http://www.macromedia.com/go/getflashplayer"
                      FlashVars="id=clippy_12345&amp;copied=copied!&amp;copyto=copy to clipboard"
                      bgcolor="#D5F0FC"
                      wmode="opaque"/></object>
             <br /> Good for one new registration. Expires in 7 days.', 'invite', true);
         } else {
             $this->addErrorMessage("There was an error creating a new invite. Please try again.", 'invite');
         }
     }
     //process service user deletion
     if (isset($_POST['action']) && $_POST['action'] == 'delete' && isset($_POST['instance_id']) && is_numeric($_POST['instance_id'])) {
         $owner_instance_dao = DAOFactory::getDAO('OwnerInstanceDAO');
         $instance_dao = DAOFactory::getDAO('InstanceDAO');
         $instance = $instance_dao->get($_POST['instance_id']);
         if (isset($instance)) {
             // verify CSRF token
             $this->validateCSRFToken();
             if ($this->isAdmin()) {
                 //delete all owner_instances
                 $owner_instance_dao->deleteByInstance($instance->id);
                 //delete instance
                 $instance_dao->delete($instance->network_username, $instance->network);
                 $this->addSuccessMessage('Account deleted.', 'account');
             } else {
                 if ($owner_instance_dao->doesOwnerHaveAccessToInstance($owner, $instance)) {
                     //delete owner instance
                     $total_deletions = $owner_instance_dao->delete($owner->id, $instance->id);
                     if ($total_deletions > 0) {
                         //delete instance if no other owners have it
                         $remaining_owner_instances = $owner_instance_dao->getByInstance($instance->id);
                         if (sizeof($remaining_owner_instances) == 0) {
                             $instance_dao->delete($instance->network_username, $instance->network);
                         }
                         $this->addSuccessMessage('Account deleted.', 'account');
                     }
                 } else {
                     $this->addErrorMessage('Insufficient privileges.', 'account');
                 }
             }
         } else {
             $this->addErrorMessage('Instance doesn\'t exist.', 'account');
         }
     }
     $this->view_mgr->clear_all_cache();
     /* Begin plugin-specific configuration handling */
     if (isset($_GET['p'])) {
         // add config js to header
         if ($this->isAdmin()) {
             $this->addHeaderJavaScript('assets/js/plugin_options.js');
         }
         $active_plugin = $_GET['p'];
         $pobj = $webapp->getPluginObject($active_plugin);
         $p = new $pobj();
         $this->addToView('body', $p->renderConfiguration($owner));
         $profiler = Profiler::getInstance();
         $profiler->clearLog();
     } else {
         $plugin_dao = DAOFactory::getDAO('PluginDAO');
         $config = Config::getInstance();
         $installed_plugins = $plugin_dao->getInstalledPlugins();
         $this->addToView('installed_plugins', $installed_plugins);
     }
     /* End plugin-specific configuration handling */
     if ($owner->is_admin) {
         if (!isset($instance_dao)) {
             $instance_dao = DAOFactory::getDAO('InstanceDAO');
         }
         $owners = $owner_dao->getAllOwners();
         foreach ($owners as $o) {
             $instances = $instance_dao->getByOwner($o, true);
             $o->setInstances($instances);
         }
         $this->addToView('owners', $owners);
         $this->addToView('public_instances', $instance_dao->getPublicInstances());
     }
     $whichphp = @exec('which php');
     $php_path = !empty($whichphp) ? $whichphp : 'php';
     $email = $this->getLoggedInUser();
     //rss_crawl_url
     $rss_crawl_url = Utils::getApplicationURL() . sprintf('crawler/rss.php?un=%s&as=%s', urlencode($email), $owner->api_key);
     $this->addToView('rss_crawl_url', $rss_crawl_url);
     //cli_crawl_command
     $cli_crawl_command = 'cd ' . THINKUP_WEBAPP_PATH . 'crawler/;export THINKUP_PASSWORD=yourpassword; ' . $php_path . ' crawl.php ' . $email;
     $this->addToView('cli_crawl_command', $cli_crawl_command);
     //help link
     $this->view_mgr->addHelp('rss', 'userguide/datacapture');
     return $this->generateView();
 }
 public function testConfigOptionsMissingRequiredValues()
 {
     $_SERVER['SERVER_NAME'] = 'mytestthinkup';
     $this->simulateLogin('*****@*****.**', true);
     $owner_dao = DAOFactory::getDAO('OwnerDAO');
     $owner = $owner_dao->getByEmail(Session::getLoggedInUser());
     $controller = new TwitterPluginConfigurationController($owner, 'twitter');
     $output = $controller->go();
     // we have a text form element with proper data
     $this->assertPattern('/Save Settings/', $output);
     // should have no submit option
     $this->assertPattern('/plugin_options_oauth_consumer_secret/', $output);
     // should have secret option
     $this->assertPattern('/plugin_options_archive_limit/', $output);
     // should have limit option
     $this->assertPattern('/plugin_options_oauth_consumer_key/', $output);
     // should have key option
     $this->assertPattern('/var is_admin = true/', $output);
     // is a js admin
     //app not configured
     $this->assertPattern('/var required_values_set = false/', $output);
     // is not configured
     //not SSL by default
     $this->assertNoPattern('/https:\\/\\/mytestthinkup/', $output);
     //assert site URL is set so user can configure the app
     $v_mgr = $controller->getViewManager();
     $site_url = $v_mgr->getTemplateDataItem('thinkup_site_url');
     $this->assertEqual($site_url, Utils::getApplicationURL());
     $twitter_app_name = $v_mgr->getTemplateDataItem('twitter_app_name');
     $this->assertEqual($twitter_app_name, "ThinkUp " . $_SERVER['SERVER_NAME']);
 }
 /**
  * Add user auth link or process incoming auth requests.
  * @param array $options Plugin options array
  */
 protected function setUpGPlusInteractions(array $options)
 {
     //get options
     $client_id = $options['google_plus_client_id']->option_value;
     $client_secret = $options['google_plus_client_secret']->option_value;
     //prep redirect URI
     $config = Config::getInstance();
     $site_root_path = $config->getValue('site_root_path');
     $redirect_uri = urlencode(Utils::getApplicationURL() . 'account/?p=google%2B');
     //create OAuth link
     $oauth_link = "https://accounts.google.com/o/oauth2/auth?client_id=" . $client_id . "&redirect_uri=" . $redirect_uri . "&scope=https://www.googleapis.com/auth/plus.me&response_type=code&access_type=offline&approval_prompt=force";
     $this->addToView('oauth_link', $oauth_link);
     // Google provided a code to get an access token
     if (isset($_GET['code'])) {
         $code = $_GET['code'];
         $crawler_plugin_registrar = new GooglePlusCrawler(null, null);
         $tokens = $crawler_plugin_registrar->getOAuthTokens($client_id, $client_secret, $code, 'authorization_code', $redirect_uri);
         if (isset($tokens->error)) {
             $this->addErrorMessage("Oops! Something went wrong while obtaining OAuth tokens.<br>Google says \"" . $tokens->error . ".\" Please double-check your settings and try again.", 'authorization');
         } else {
             if (isset($tokens->access_token) && isset($tokens->access_token)) {
                 //Get user data
                 $gplus_api_accessor = new GooglePlusAPIAccessor();
                 $gplus_user = $gplus_api_accessor->apiRequest('people/me', $tokens->access_token, null);
                 if (isset($gplus_user->error)) {
                     if ($gplus_user->error->code == "403" && $gplus_user->error->message == 'Access Not Configured') {
                         $this->addErrorMessage("Oops! Looks like Google+ API access isn't turned on. " . "<a href=\"http://code.google.com/apis/console#access\">In the Google APIs console</a>, " . "in Services, flip the Google+ API Status switch to 'On' and try again.", 'authorization');
                     } else {
                         $this->addErrorMessage("Oops! Something went wrong querying the Google+ API.<br>" . "Google says \"" . $gplus_user->error->code . ": " . $gplus_user->error->message . ".\" Please double-check your settings and try again.", 'authorization');
                     }
                 } else {
                     if (isset($gplus_user->id) && isset($gplus_user->displayName)) {
                         $gplus_user_id = $gplus_user->id;
                         $gplus_username = $gplus_user->displayName;
                         //Process tokens
                         $this->saveAccessTokens($gplus_user_id, $gplus_username, $tokens->access_token, $tokens->refresh_token);
                     } else {
                         $this->addErrorMessage("Oops! Something went wrong querying the Google+ API.<br>" . "Google says \"" . Utils::varDumpToString($gplus_user) . ".\" Please double-check your settings and try again.", 'authorization');
                     }
                 }
             } else {
                 $this->addErrorMessage("Oops! Something went wrong while obtaining OAuth tokens.<br>Google says \"" . Utils::varDumpToString($tokens) . ".\" Please double-check your settings and try again.", 'authorization');
             }
         }
     }
     $instance_dao = DAOFactory::getDAO('InstanceDAO');
     $owner_instances = $instance_dao->getByOwnerAndNetwork($this->owner, 'google+');
     $this->addToView('owner_instances', $owner_instances);
 }
Ejemplo n.º 24
0
 public function control()
 {
     if ($this->isLoggedIn()) {
         $controller = new DashboardController(true);
         return $controller->go();
     } else {
         // register form validation
         $this->addHeaderCSS('assets/css/validate_password.css');
         $this->addHeaderJavaScript('assets/js/jquery.validate.min.js');
         $this->addHeaderJavaScript('assets/js/jquery.validate.password.js');
         $this->addHeaderJavaScript('assets/js/validate_password.js');
         $config = Config::getInstance();
         $is_registration_open = $config->getValue('is_registration_open');
         $this->disableCaching();
         $invite_dao = DAOFactory::getDAO('InviteDAO');
         if (isset($_GET['code'])) {
             $invite_code = $_GET['code'];
         } else {
             $invite_code = null;
         }
         $this->addToView('invite_code', $invite_code);
         $is_invite_code_valid = $invite_dao->isInviteValid($invite_code);
         if ($invite_code != null && $is_invite_code_valid) {
             $this->addSuccessMessage("Welcome, VIP! You've been invited to register on " . $config->getValue('app_title_prefix') . "ThinkUp.");
         }
         $has_been_registered = false;
         if (!$is_registration_open && !$is_invite_code_valid) {
             $this->addToView('closed', true);
             $disable_xss = true;
             $this->addErrorMessage('<p>Sorry, registration is closed on this installation of ' . $config->getValue('app_title_prefix') . "ThinkUp.</p>" . '<p><a href="http://thinkupapp.com">Install ThinkUp on your own server.</a></p>', null, $disable_xss);
         } else {
             $owner_dao = DAOFactory::getDAO('OwnerDAO');
             $this->addToView('closed', false);
             $captcha = new Captcha();
             if (isset($_POST['Submit']) && $_POST['Submit'] == 'Register') {
                 foreach ($this->REQUIRED_PARAMS as $param) {
                     if (!isset($_POST[$param]) || $_POST[$param] == '') {
                         $this->addErrorMessage('Please fill out all required fields.');
                         $this->is_missing_param = true;
                     }
                 }
                 if (!$this->is_missing_param) {
                     $valid_input = true;
                     if (!Utils::validateEmail($_POST['email'])) {
                         $this->addErrorMessage("Incorrect email. Please enter valid email address.", 'email');
                         $valid_input = false;
                     }
                     if (strcmp($_POST['pass1'], $_POST['pass2']) || empty($_POST['pass1'])) {
                         $this->addErrorMessage("Passwords do not match.", 'password');
                         $valid_input = false;
                     } else {
                         if (!preg_match("/(?=.{8,})(?=.*[a-zA-Z])(?=.*[0-9])/", $_POST['pass1'])) {
                             $this->addErrorMessage("Password must be at least 8 characters and contain both numbers " . "and letters.", 'password');
                             $valid_input = false;
                         }
                     }
                     if (!$captcha->doesTextMatchImage()) {
                         $this->addErrorMessage("Entered text didn't match the image. Please try again.", 'captcha');
                         $valid_input = false;
                     }
                     if ($valid_input) {
                         if ($owner_dao->doesOwnerExist($_POST['email'])) {
                             $this->addErrorMessage("User account already exists.", 'email');
                         } else {
                             // Insert the details into the database
                             $activation_code = $owner_dao->create($_POST['email'], $_POST['pass2'], $_POST['full_name']);
                             if ($activation_code != false) {
                                 $es = new ViewManager();
                                 $es->caching = false;
                                 $es->assign('application_url', Utils::getApplicationURL(false));
                                 $es->assign('email', urlencode($_POST['email']));
                                 $es->assign('activ_code', $activation_code);
                                 $message = $es->fetch('_email.registration.tpl');
                                 Mailer::mail($_POST['email'], "Activate Your Account on " . $config->getValue('app_title_prefix') . "ThinkUp", $message);
                                 SessionCache::unsetKey('ckey');
                                 $this->addSuccessMessage("Success! Check your email for an activation link.");
                                 //delete invite code
                                 if ($is_invite_code_valid) {
                                     $invite_dao->deleteInviteCode($invite_code);
                                 }
                                 $has_been_registered = true;
                             } else {
                                 $this->addErrorMessage("Unable to register a new user. Please try again.");
                             }
                         }
                     }
                 }
                 if (isset($_POST["full_name"])) {
                     $this->addToView('name', $_POST["full_name"]);
                 }
                 if (isset($_POST["email"])) {
                     $this->addToView('mail', $_POST["email"]);
                 }
                 $this->addToView('has_been_registered', $has_been_registered);
             }
             $challenge = $captcha->generate();
             $this->addToView('captcha', $challenge);
         }
         $this->view_mgr->addHelp('register', 'userguide/accounts/index');
         return $this->generateView();
     }
 }
 public function authControl()
 {
     $config = Config::getInstance();
     Loader::definePathConstants();
     $this->setViewTemplate(THINKUP_WEBAPP_PATH . 'plugins/twitter/view/twitter.account.index.tpl');
     $this->view_mgr->addHelp('twitter', 'userguide/settings/plugins/twitter');
     $id = DAOFactory::getDAO('InstanceDAO');
     $od = DAOFactory::getDAO('OwnerDAO');
     // get plugin option values if defined...
     $plugin_options = $this->getPluginOptions();
     $oauth_consumer_key = $this->getPluginOption('oauth_consumer_key');
     $oauth_consumer_secret = $this->getPluginOption('oauth_consumer_secret');
     $archive_limit = $this->getPluginOption('archive_limit');
     $num_twitter_errors = $this->getPluginOption('num_twitter_errors');
     $max_api_calls_per_crawl = $this->getPluginOption('max_api_calls_per_crawl');
     //Add public user instance
     if (isset($_GET['twitter_username'])) {
         // if form was submitted
         $logger = Logger::getInstance();
         $api = new TwitterAPIAccessorOAuth('NOAUTH', 'NOAUTH', $oauth_consumer_key, $oauth_consumer_secret, $num_twitter_errors, $max_api_calls_per_crawl);
         $api_call = str_replace("[id]", $_GET['twitter_username'], $api->cURL_source['show_user']);
         list($cURL_status, $data) = $api->apiRequestFromWebapp($api_call);
         if ($cURL_status == 200) {
             $thisFeed = array();
             try {
                 $xml = $api->createParserFromString(utf8_encode($data));
                 $user = array('user_id' => $xml->id, 'user_name' => $xml->screen_name, 'is_protected' => $xml->protected);
             } catch (Exception $e) {
                 $this->addErrorMessage($e->getMessage());
             }
             if (isset($user) && $user["is_protected"] == 'false') {
                 // if so, add to instances table and owners table
                 $i = $id->getByUsernameOnNetwork($_GET['twitter_username'], 'twitter');
                 $oid = DAOFactory::getDAO('OwnerInstanceDAO');
                 $msg = '';
                 if (isset($i)) {
                     //Instance exists
                     $oi = $oid->get($this->owner->id, $i->id);
                     if ($oi == null) {
                         //Owner_instance doesn't exist
                         $oid->insert($this->owner->id, $i->id, '', '');
                     }
                 } else {
                     //Instance does not exist
                     $id->insert($user["user_id"], $user["user_name"]);
                     $i = $id->getByUsernameOnNetwork($user["user_name"], 'twitter');
                     $oid->insert($this->owner->id, $i->id, '', '');
                 }
                 $this->addSuccessMessage($_GET['twitter_username'] . " has been added to ThinkUp.");
                 $this->addSuccessMessage("Added " . $_GET['twitter_username'] . " to ThinkUp.");
             } else {
                 // if not, return error
                 $this->addErrorMessage($_GET['twitter_username'] . " is a private Twitter account; ThinkUp cannot track it without authorization.");
             }
         } else {
             $this->addErrorMessage($_GET['twitter_username'] . " is not a valid Twitter username.");
         }
     }
     $this->addToView('twitter_app_name', "ThinkUp " . $_SERVER['SERVER_NAME']);
     $this->addToView('thinkup_site_url', Utils::getApplicationURL(true));
     $plugin = new TwitterPlugin();
     if ($plugin->isConfigured()) {
         $to = new TwitterOAuth($oauth_consumer_key, $oauth_consumer_secret);
         /* Request tokens from twitter */
         $tok = $to->getRequestToken(Utils::getApplicationURL(true) . "plugins/twitter/auth.php");
         if (isset($tok['oauth_token']) || isset($_SESSION["MODE"]) && $_SESSION["MODE"] == "TESTS" || getenv("MODE") == "TESTS") {
             //testing
             $token = $tok['oauth_token'];
             SessionCache::put('oauth_request_token_secret', $tok['oauth_token_secret']);
             /* Build the authorization URL */
             $oauthorize_link = $to->getAuthorizeURL($token);
             $owner_instances = $id->getByOwnerAndNetwork($this->owner, 'twitter');
             $this->addToView('owner_instances', $owner_instances);
             $this->addToView('oauthorize_link', $oauthorize_link);
             $this->addToView('is_configured', true);
         } else {
             //set error message here
             $this->addErrorMessage("Unable to obtain OAuth tokens from Twitter. Please double-check the consumer key and secret " . "are correct.", "setup");
             $oauthorize_link = '';
             $this->addToView('is_configured', false);
         }
     } else {
         $this->addInfoMessage('Please complete plugin setup to start using it.', 'setup');
         $this->addToView('is_configured', false);
     }
     // Secret config file value enables public Twitter name search
     $this->addToView('enable_twitter_search', $config->getValue('enable_twitter_search'));
     // add plugin options from
     $this->addOptionForm();
     return $this->generateView();
 }
 public function testConfigNotSet()
 {
     $plugin_options_dao = DAOFactory::getDAO("PluginOptionDAO");
     PluginOptionMySQLDAO::$cached_options = array();
     $this->simulateLogin('*****@*****.**');
     $owner_dao = DAOFactory::getDAO('OwnerDAO');
     $owner = $owner_dao->getByEmail(Session::getLoggedInUser());
     $controller = new FacebookPluginConfigurationController($owner);
     $results = $controller->go();
     $v_mgr = $controller->getViewManager();
     $info = $v_mgr->getTemplateDataItem('info_msgs');
     $this->assertEqual($info['setup'], 'Please complete plugin setup to start using it.');
     $this->debug(Utils::varDumpToString($info));
     //assert configuration URL is showing
     $site_url = $v_mgr->getTemplateDataItem('thinkup_site_url');
     $this->assertEqual($site_url, Utils::getApplicationURL());
 }
 /**
  * Generates a one time upgrade token, and emails admins with the token info.
  */
 public static function generateUpgradeToken()
 {
     $token_file = FileDataManager::getDataPath('.htupgrade_token');
     $md5_token = '';
     if (!file_exists($token_file)) {
         $fp = fopen($token_file, 'w');
         if ($fp) {
             $token = self::TOKEN_KEY . rand(0, time());
             $md5_token = md5($token);
             if (!fwrite($fp, $md5_token)) {
                 throw new OpenFileException("Unable to write upgrade token file: " + $token_file);
             }
             fclose($fp);
         } else {
             throw new OpenFileException("Unable to create upgrade token file: " + $token_file);
         }
         // email our admin with this token.
         $owner_dao = DAOFactory::getDAO('OwnerDAO');
         $admins = $owner_dao->getAdmins();
         if ($admins) {
             $tos = array();
             foreach ($admins as $admin) {
                 $tos[] = $admin->email;
             }
             $to = join(',', $tos);
             $upgrade_email = new ViewManager();
             $upgrade_email->caching = false;
             $upgrade_email->assign('application_url', Utils::getApplicationURL(false));
             $upgrade_email->assign('token', $md5_token);
             $message = $upgrade_email->fetch('_email.upgradetoken.tpl');
             $config = Config::getInstance();
             Mailer::mail($to, "Upgrade Your ThinkUp Database", $message);
         }
     }
 }
 /**
  * Send out insight email digest for a given time period.
  * @param Owner $owner Owner to send for
  * @param str $start When to start insight lookup
  * @param str $template Email view template to use
  * @param array $options Plugin options
  * @param bool $weekly Is this a weekly email?
  * return bool Whether email was sent
  */
 private function sendDigestSinceWithTemplate($owner, $start, $template, &$options, $weekly)
 {
     $insights_dao = DAOFactory::GetDAO('InsightDAO');
     $start_time = date('Y-m-d H:i:s', strtotime($start, $this->current_timestamp));
     $insights = $insights_dao->getAllOwnerInstanceInsightsSince($owner->id, $start_time);
     $num_insights = count($insights);
     if ($num_insights == 0) {
         return false;
     }
     $config = Config::getInstance();
     $view = new ViewManager();
     $view->caching = false;
     $logger = Logger::getInstance();
     // If we've got a Mandrill key and template, send HTML
     if ($config->getValue('mandrill_api_key') != null && !empty($options['mandrill_template'])) {
         $logger->logUserInfo("Mandrill API key and template set; sending HTML", __METHOD__ . ',' . __LINE__);
         $view->assign('insights', $insights);
         $view->assign('application_url', Utils::getApplicationURL());
         $view->assign('header_text', $this->getEmailMessageHeaderText());
         if (Utils::isThinkUpLLC()) {
             $logger->logUserInfo("Email via ThinkUpLLC, process welcome / free trial messaging", __METHOD__ . ',' . __LINE__);
             $thinkupllc_endpoint = $config->getValue('thinkupllc_endpoint');
             $view->assign('thinkupllc_endpoint', $thinkupllc_endpoint);
             $view->assign('unsub_url', $thinkupllc_endpoint . 'settings.php');
             $view->assign('install_folder', $config->getValue('install_folder'));
             if (!isset($options['last_daily_email'])) {
                 $logger->logUserInfo("No daily email ever sent before, include welcome message", __METHOD__ . ',' . __LINE__);
                 $view->assign('show_welcome_message', true);
             } else {
                 if ($owner->is_free_trial) {
                     $logger->logUserInfo("Owner is in free trial", __METHOD__ . ',' . __LINE__);
                     $creation_date = new DateTime($owner->joined);
                     $now = new DateTime();
                     $end_of_trial = $creation_date->add(new DateInterval('P15D'));
                     if ($end_of_trial >= $now) {
                         $interval = $now->diff($end_of_trial);
                         $days_left = $interval->format('%a');
                         if ($days_left > 2) {
                             $view->assign('pay_prompt_headline', $days_left . ' days left in your free trial!');
                         } elseif ($days_left == 0) {
                             //Last day
                             $view->assign('pay_prompt_headline', 'Last chance!');
                         } else {
                             //Show hours if it's 24 or 48 hours
                             $view->assign('pay_prompt_headline', 'Only ' . $days_left * 24 . ' hours left!');
                         }
                         $explainer_copy_options = array("Your free trial expires today. Don't lose any of your insights!", "It's time to become a member. We'd love to have you.", "It's just " . ($owner->membership_level == 'Member' ? '16' : '32') . " cents a day to get smarter about the time you spend online.", "Isn't this better than boring \"analytics\"?", "Just wait 'til you see ThinkUp next week.", "We never sell your data and we don't show you ads.", "Get our exclusive book on the future of social media for free.", "ThinkUp gives you social network superpowers.", "The longer you use ThinkUp, the smarter it gets.", "ThinkUp helps you be more thoughtful about your time online.", "ThinkUp works in email, on the web, and on all your devices.", "ThinkUp members can cancel at any time—with no hassles.", 'Wait until you see what ThinkUp has in store tomorrow.', "Your morning ThinkUp email will make your day.");
                         $view->assign('pay_prompt_explainer', $explainer_copy_options[$days_left]);
                         if ($owner->membership_level == 'Member') {
                             $view->assign('pay_prompt_button_label', 'Just $5/month');
                         } elseif ($owner->membership_level == 'Pro') {
                             $view->assign('pay_prompt_button_label', 'Just $10/month');
                         }
                     }
                 } else {
                     //Check subscription status and show a message if Payment failed or due
                     $logger->logUserInfo("User is not in free trial; check subscription status", __METHOD__ . ',' . __LINE__);
                     $thinkupllc_api_accessor = new ThinkUpLLCAPIAccessor();
                     $membership_details = $thinkupllc_api_accessor->getSubscriptionStatus($owner->email);
                     $logger->logUserInfo("Subscription status is " . Utils::varDumpToString($membership_details), __METHOD__ . ',' . __LINE__);
                     if (isset($membership_details->subscription_status) && ($membership_details->subscription_status == 'Payment failed' || $membership_details->subscription_status == 'Payment due')) {
                         $logger->logUserInfo("Owner has payment failure; include alert in email", __METHOD__ . ',' . __LINE__);
                         $payment_failed_copy = array();
                         if ($membership_details->subscription_status == 'Payment failed') {
                             $payment_failed_copy[] = array('headline' => 'Oops! Your account needs attention', 'explainer' => "We had a problem processing your membership payment. " . "But it's easy to fix.");
                             $payment_failed_copy[] = array('headline' => 'Uh oh, problem with your subscription...', 'explainer' => "There was a problem processing your membership payment. " . "To fix it, update your payment info.");
                             $payment_failed_copy[] = array('headline' => 'Your ThinkUp subscription is out of date...', 'explainer' => "We tried to charge your Amazon account for your ThinkUp membership," . " and there was an error. But it's easy to fix.");
                             $payment_failed_copy[] = array('headline' => 'Action required to keep your ThinkUp account active', 'explainer' => "We weren't able to process your last membership payment—maybe your " . "info is out of date? Fixing it just takes a moment.");
                             $payment_failed_copy[] = array('headline' => "Urgent! Keep your ThinkUp account active", 'explainer' => "We tried to process your ThinkUp subscription, but " . "the payment was not successful. Please update your payment information " . "now to make sure your ThinkUp membership stays in good standing.");
                             $payment_failed_button_label = "Update your payment info";
                         } else {
                             //Payment due
                             $payment_failed_copy[] = array('headline' => 'Oops! Your ThinkUp membership needs attention', 'explainer' => "Looks like you've got a membership payment due. " . "But it's easy to make it.");
                             $payment_failed_copy[] = array('headline' => "Uh-oh, don't let your subscription expire", 'explainer' => "Looks like your ThinkUp payment is due. " . "Make it now so your account doesn't expire.");
                             $payment_failed_copy[] = array('headline' => 'Hey, your ThinkUp subscription payment is due', 'explainer' => "Your membership payment isn't up-to-date. " . " But it's easy to fix.");
                             $payment_failed_copy[] = array('headline' => 'Action required: Keep your ThinkUp account active', 'explainer' => "Looks like you've got a membership payment due. " . "Making it just takes a moment.");
                             $payment_failed_copy[] = array('headline' => "Urgent! Keep your ThinkUp account active", 'explainer' => "Your subscription payment is due. " . "Please update your information now to keep your ThinkUp membership " . "in good standing.");
                             $payment_failed_button_label = "Make your payment";
                         }
                         $copy_index = TimeHelper::getDayOfYear() % count($payment_failed_copy);
                         $payment_failed_headline = $payment_failed_copy[$copy_index]['headline'];
                         $payment_failed_explainer = $payment_failed_copy[$copy_index]['explainer'];
                         $view->assign('payment_failed_headline', $payment_failed_headline);
                         $view->assign('payment_failed_explainer', $payment_failed_explainer);
                         $view->assign('payment_failed_button_label', $payment_failed_button_label);
                     }
                 }
             }
             $thinkupllc_email_tout = $config->getValue('thinkupllc_email_tout');
             if (isset($thinkupllc_email_tout)) {
                 $view->assign('thinkupllc_email_tout', $thinkupllc_email_tout);
             }
         } else {
             $logger->logUserInfo("Email is NOT via ThinkUpLLC", __METHOD__ . ',' . __LINE__);
             $view->assign('unsub_url', Utils::getApplicationURL() . 'account/index.php?m=manage#instances');
         }
         // It's a weekly digest if we're going back more than a day or two.
         $daily_or_weekly = $weekly ? 'Weekly' : 'Daily';
         $view->assign('weekly_or_daily', $daily_or_weekly);
         $view->assign('pay_prompt_url', $config->getValue('thinkupllc_endpoint') . 'membership.php');
         if ($config->getValue('image_proxy_enabled') == true) {
             $view->assign('image_proxy_sig', $config->getValue('image_proxy_sig'));
         }
         $insights_markup = $view->fetch(Utils::getPluginViewDirectory($this->folder_name) . '_email.insights_html.tpl');
         $parameters = array();
         $parameters['insights'] = $insights_markup;
         $parameters['app_title'] = $config->getValue('app_title_prefix') . "ThinkUp";
         $parameters['application_url'] = Utils::getApplicationURL();
         $parameters['weekly_or_daily'] = $daily_or_weekly;
         try {
             if (!isset($options['last_daily_email'])) {
                 $subject_line = "Welcome to ThinkUp! Here are your insights.";
             } else {
                 $subject_line = $this->getEmailMessageSubjectLine($daily_or_weekly, $insights);
             }
             $logger->logUserInfo("About to call Mailer::mailHTMLViaMandrillTemplate", __METHOD__ . ',' . __LINE__);
             Mailer::mailHTMLViaMandrillTemplate($owner->email, $subject_line, $options['mandrill_template']->option_value, $parameters);
             return true;
         } catch (Mandrill_Unknown_Template $e) {
             // In this case, we'll fall back to plain text sending and warn the user in the log
             $logger->logUserError("Invalid mandrill template configured:" . $options['mandrill_template']->option_value . ".", __METHOD__ . ',' . __LINE__);
             unset($options['mandrill_template']);
         }
     } else {
         if ($config->getValue('mandrill_api_key') == null) {
             $logger->logUserInfo("Mandrill API key is null", __METHOD__ . ',' . __LINE__);
         }
         if (empty($options['mandrill_template'])) {
             $logger->logUserInfo("Mandrill template is not set", __METHOD__ . ',' . __LINE__);
         }
     }
     $view->assign('app_title', $config->getValue('app_title_prefix') . "ThinkUp");
     $view->assign('application_url', Utils::getApplicationURL());
     $view->assign('insights', $insights);
     $message = $view->fetch(Utils::getPluginViewDirectory($this->folder_name) . $template);
     list($subject, $message) = explode("\n", $message, 2);
     $logger->logUserInfo("About to call Mailer::mail", __METHOD__ . ',' . __LINE__);
     Mailer::mail($owner->email, $subject, $message);
     return true;
 }
 /**
  * Get fully-rendered HTML markup for this insight.
  * @param  Insight $insight Test insight to render in HTML.
  * @return str Insight HTML with this insight
  */
 protected function getRenderedInsightInHTML(Insight $insight)
 {
     if ($insight->related_data !== null && is_string($insight->related_data)) {
         $insight->related_data = Serializer::unserializeString($insight->related_data);
     }
     $view = new ViewManager();
     $view->caching = false;
     $view->assign('insights', array($insight));
     $view->assign('expand', true);
     $view->assign('tpl_path', THINKUP_WEBAPP_PATH . 'plugins/insightsgenerator/view/');
     $view->assign('enable_bootstrap', true);
     $view->assign('thinkup_application_url', Utils::getApplicationURL());
     $view->assign('site_root_path', 'https://thinkup.thinkup.com/');
     $html_insight = $view->fetch(THINKUP_WEBAPP_PATH . '_lib/view/insights.tpl');
     return $html_insight;
 }
 /**
  * Load view with data to display individual insight.
  */
 private function displayIndividualInsight()
 {
     $insight_dao = DAOFactory::getDAO('InsightDAO');
     //get instance and check if it's public or that owner has access to it
     $instance_dao = DAOFactory::getDAO('InstanceDAO');
     $instance = $instance_dao->getByUsernameOnNetwork(stripslashes($_GET["u"]), $_GET['n']);
     $should_display_insight = false;
     if (isset($instance)) {
         if ($instance->is_public) {
             $should_display_insight = true;
         } else {
             if ($this->isLoggedIn()) {
                 $owner_dao = DAOFactory::getDAO('OwnerDAO');
                 $owner = $owner_dao->getByEmail($this->getLoggedInUser());
                 $owner_instance_dao = DAOFactory::getDAO('OwnerInstanceDAO');
                 if ($owner_instance_dao->doesOwnerHaveAccessToInstance($owner, $instance)) {
                     $should_display_insight = true;
                 } else {
                     $redirect_url = urlencode(Utils::getApplicationURL() . Utils::getApplicationRequestURI());
                     $this->addToView('redirect_url', $redirect_url);
                     $this->addErrorMessage("<a href='session/login.php?redirect=" . $redirect_url . '\'>Log in</a> to see this insight.', null, true);
                 }
             } else {
                 $redirect_url = urlencode(Utils::getApplicationURL() . Utils::getApplicationRequestURI());
                 $this->addToView('redirect_url', $redirect_url);
                 $this->addErrorMessage("<a href='session/login.php?redirect=" . $redirect_url . '\'>Log in</a> to see this insight.', null, true);
             }
         }
     } else {
         $this->addErrorMessage(stripslashes($_GET["u"]) . " on " . ucfirst($_GET['n']) . " is not in ThinkUp.");
     }
     if ($should_display_insight) {
         $insights = array();
         $insight = $insight_dao->getInsightByUsername($_GET['u'], $_GET['n'], $_GET['s'], $_GET['d']);
         if (isset($insight)) {
             $insights[] = $insight;
             $this->addToView('insights', $insights);
             $this->addToView('expand', true);
             $thinkupllc_endpoint = Config::getInstance()->getValue('thinkupllc_endpoint');
             if (isset($thinkupllc_endpoint)) {
                 $insight_params = array('tu' => Config::getInstance()->getValue('install_folder'), 'u' => $insight->instance->network_username, 'n' => $insight->instance->network, 'd' => date('Y-m-d', strtotime($insight->date)), 's' => $insight->slug, 'share' => 1);
                 $insight_image = "https://shares.thinkup.com/insight?" . http_build_query($insight_params);
                 $twitter_card = "summary_large_image";
             } else {
                 $insight_image = "https://www.thinkup.com/join/assets/ico/apple-touch-icon-144-precomposed.png";
                 $twitter_card = "summary";
             }
             $this->addToView('install_folder', Config::getInstance()->getValue('install_folder'));
             $this->addToView('insight_image', $insight_image);
             $this->addToView('twitter_card', $twitter_card);
         } else {
             $this->addErrorMessage("This insight doesn't exist.");
         }
     }
 }