Ejemplo n.º 1
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);
     }
     if (!Utils::isTest()) {
         //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);
 }
Ejemplo n.º 2
0
 /**
  * Check the $_POST'ed CAPTCHA inputs match the contents of the CAPTCHA.
  * @return bool
  */
 public function doesTextMatchImage()
 {
     //if in test mode, assume check is good if user_code is set to 123456
     if (Utils::isTest()) {
         if (isset($_POST['user_code']) && $_POST['user_code'] == '123456') {
             return true;
         } else {
             return false;
         }
     }
     switch ($this->type) {
         case self::RECAPTCHA_CAPTCHA:
             $config = Config::getInstance();
             $priv_key = $config->getValue('recaptcha_private_key');
             $resp = recaptcha_check_answer($priv_key, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
             if (!$resp->is_valid) {
                 return false;
             } else {
                 return true;
             }
             break;
         default:
             if (strcmp(md5($_POST['user_code']), SessionCache::get('ckey'))) {
                 return false;
             } else {
                 return true;
             }
             break;
     }
 }
Ejemplo n.º 3
0
 public function generateInsight(Instance $instance, User $user, $last_week_of_posts, $number_days)
 {
     parent::generateInsight($instance, $user, $last_week_of_posts, $number_days);
     $this->logger->logInfo("Begin generating insight", __METHOD__ . ',' . __LINE__);
     $baseline_dao = DAOFactory::getDAO('InsightBaselineDAO');
     foreach ($this->getSchedule() as $baseline_slug => $data) {
         $now = TimeHelper::getTime();
         if ($now >= strtotime($data['start']) && $now <= strtotime($data['end'])) {
             $this->logger->logInfo("{$now} is in-schedule", __METHOD__ . ',' . __LINE__);
             $baseline = $baseline_dao->getMostRecentInsightBaseline($baseline_slug, $instance->id);
             if (!$baseline) {
                 if ($instance->network == 'facebook' && date('w') == 4 || $instance->network == 'twitter' && date('w') == 1 || Utils::isTest()) {
                     $found = $this->runInsightForConfig($data, $instance);
                     $baseline_dao->insertInsightBaseline($baseline_slug, $instance->id, $found);
                 } else {
                     $this->logger->logInfo("Not today", __METHOD__ . ',' . __LINE__);
                 }
             } else {
                 $this->logger->logInfo("Already exists", __METHOD__ . ',' . __LINE__);
             }
         } else {
             $this->logger->logInfo("Not in-schedule", __METHOD__ . ',' . __LINE__);
         }
     }
     $this->logger->logInfo("Done generating insight", __METHOD__ . ',' . __LINE__);
 }
Ejemplo n.º 4
0
 /**
  * Determine whether an insight should be generated or not.
  * @param str $slug slug of the insight to be generated
  * @param Instance $instance user and network details for which the insight has to be generated
  * @param date $insight_date date for which the insight has to be generated
  * @param bool $regenerate_existing_insight whether the insight should be regenerated over a day
  * @param int $day_of_week the day of week (0 for Sunday through 6 for Saturday) on which the insight should run
  * @param int $count_last_week_of_posts if set, wouldn't run insight if there are no posts from last week
  * @param arr $excluded_networks array of networks for which the insight shouldn't be run
  * @param bool $alternate_day whether today is an alternate day or not
  * @return bool $run whether the insight should be generated or not
  */
 public function shouldGenerateInsight($slug, Instance $instance, $insight_date = null, $regenerate_existing_insight = false, $day_of_week = null, $count_last_week_of_posts = null, $excluded_networks = null, $alternate_day = true)
 {
     if (Utils::isTest()) {
         return true;
     } else {
         return $alternate_day && parent::shouldGenerateInsight($slug, $instance, $insight_date, $regenerate_existing_insight, $day_of_week, $count_last_week_of_posts, $excluded_networks);
     }
 }
 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']) || Utils::isTest()) {
                 $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();
 }
Ejemplo n.º 6
0
 public function generateInsight(Instance $instance, User $user, $last_week_of_posts, $number_days)
 {
     if (Utils::isTest() || date("Y-m-d") == '2015-02-23') {
         parent::generateInsight($instance, $user, $last_week_of_posts, $number_days);
         $this->logger->logInfo("Begin generating insight", __METHOD__ . ',' . __LINE__);
         $hero_image = array('url' => 'https://www.thinkup.com/assets/images/insights/2015-02/oscars2015.jpg', 'alt_text' => 'Oprah got a Lego Oscar!', 'credit' => 'Photo: Disney | ABC Television Group', 'img_link' => 'https://www.flickr.com/photos/disneyabc/16620198142');
         $post_dao = DAOFactory::getDAO('PostDAO');
         $last_month_of_posts = $post_dao->getAllPostsByUsernameOrderedBy($instance->network_username, $network = $instance->network, $count = 0, $order_by = "pub_date", $in_last_x_days = 30, $iterator = false, $is_public = false);
         if (self::shouldGenerateWeeklyInsight('oscars_2015', $instance, $insight_date = 'today', $regenerate_existing_insight = false, $day_of_week = 1, count($last_month_of_posts))) {
             foreach ($last_month_of_posts as $post) {
                 $this->logger->logInfo("Post text is: " . $post->post_text, __METHOD__ . ',' . __LINE__);
                 //  see if $post date is before the awards aired
                 if ($post->pub_date < "2015-02-22 18:00:00") {
                     $mentioned_oscar_winner = self::detectOscarWinnerReferences($post->post_text);
                     $mentioned_oscar_loser = self::detectOscarLoserReferences($post->post_text);
                     $oscar_mention_count = self::countOscarMentions($post->post_text);
                     if ($mentioned_oscar_winner) {
                         $this->logger->logInfo("Winner mention: {$mentioned_oscar_winner}", __METHOD__ . ',' . __LINE__);
                         $insight_body = "{$this->username} was talking about {$mentioned_oscar_winner} before the " . "Academy Award winners were even announced!";
                     } else {
                         $this->logger->logInfo("No winners mentioned, skipping insight. ", __METHOD__ . ',' . __LINE__);
                     }
                     if ($mentioned_oscar_loser) {
                         $this->logger->logInfo("Loser mention: {$mentioned_oscar_loser}", __METHOD__ . ',' . __LINE__);
                         $insight_body_suffix = " Looks like the Academy voters might have missed " . "{$this->username}'s " . $this->terms->getNoun('post', InsightTerms::PLURAL) . " about " . $mentioned_oscar_loser . ", though.";
                     }
                 }
             }
             if ($insight_body_suffix) {
                 $insight_text = $insight_body . $insight_body_suffix;
             } else {
                 $insight_text = $insight_body;
             }
             if ($insight_body) {
                 $headline = "Somebody was ready for the Oscars party!";
                 $my_insight = new Insight();
                 $my_insight->slug = 'oscars_2015';
                 //slug to label this insight's content
                 $my_insight->instance_id = $instance->id;
                 $my_insight->date = $this->insight_date;
                 //date is often this or $simplified_post_date
                 $my_insight->headline = $headline;
                 // or just set a string like 'Ohai';
                 $my_insight->text = $insight_text;
                 // or just set a strong like "Greetings humans";
                 $my_insight->filename = basename(__FILE__, ".php");
                 //Same for every insight, must be set this way
                 $my_insight->emphasis = Insight::EMPHASIS_HIGH;
                 //Optional emphasis, default Insight::EMPHASIS_LOW
                 $my_insight->setHeroImage($hero_image);
                 $this->insight_dao->insertInsight($my_insight);
             }
         }
         $this->logger->logInfo("Done generating insight", __METHOD__ . ',' . __LINE__);
     }
 }
Ejemplo n.º 7
0
 public function generateInsight(Instance $instance, User $user, $last_week_of_posts, $number_days)
 {
     parent::generateInsight($instance, $user, $last_week_of_posts, $number_days);
     $this->logger->logInfo("Begin generating insight", __METHOD__ . ',' . __LINE__);
     $has_never_run = !$this->insight_dao->doesInsightExist($this->slug, $instance->id);
     if (Utils::isTest() || $has_never_run && (date("Y-m-d") == '2015-06-27' || date("Y-m-d") == '2015-06-28')) {
         $this->logger->logInfo("Should generate insight", __METHOD__ . ',' . __LINE__);
         $hero_image = array('url' => 'https://www.thinkup.com/assets/images/insights/2015-06/white-house-rainbow.jpg', 'alt_text' => '1600 Pennsylvania Avenue', 'credit' => 'Photo: Jason Goldman', 'img_link' => 'https://twitter.com/Goldman44/status/614599247959322624');
         $topics = array('lovewins' => array("LoveWins", "marriage equality", "scotus", "gay marriage", "pride"));
         $matches = array();
         $matched_posts = array();
         $matched = false;
         foreach ($last_week_of_posts as $post) {
             foreach ($topics as $key => $strings) {
                 foreach ($strings as $string) {
                     if (preg_match_all('/\\b' . strtolower($string) . '\\b/i', strtolower($post->post_text), $matches)) {
                         $matched = true;
                         $this->logger->logInfo("FOUND " . $string . " in " . $post->post_text, __METHOD__ . ',' . __LINE__);
                     } else {
                         $this->logger->logInfo("Didn't find " . $string . " in " . $post->post_text, __METHOD__ . ',' . __LINE__);
                     }
                 }
             }
             if ($matched) {
                 $this->logger->logInfo("Matched post " . $post->post_text, __METHOD__ . ',' . __LINE__);
                 $matched_posts[] = $post;
             }
             $matched = false;
         }
         if (count($matched_posts) > 0) {
             if ($instance->network == 'facebook') {
                 $headline = $this->username . " had enough pride for all 50 states";
                 $insight_text = $this->username . ' joined the <a href="https://facebook.com/celebratepride">marriage equality celebration</a> ' . 'this week!';
             } else {
                 $headline = $this->username . " joined the #LoveWins celebration";
                 $insight_text = $this->username . ' was all about <a href="https://twitter.com/hashtag/LoveWins">marriage equality</a> ' . 'this week.';
             }
             $insight = new Insight();
             $insight->instance_id = $instance->id;
             $insight->slug = $this->slug;
             $insight->date = date("Y-m-d");
             $insight->headline = $headline;
             $insight->text = $insight_text;
             $insight->filename = basename(__FILE__, ".php");
             $insight->emphasis = Insight::EMPHASIS_HIGH;
             $insight->setHeroImage($hero_image);
             $matched_posts_sliced = array_slice($matched_posts, 0, 5);
             $insight->setPosts($matched_posts_sliced);
             $this->insight_dao->insertInsight($insight);
         }
     }
     $this->logger->logInfo("Done generating insight", __METHOD__ . ',' . __LINE__);
 }
Ejemplo n.º 8
0
 public function generateInsight(Instance $instance, User $user, $last_week_of_posts, $number_days)
 {
     parent::generateInsight($instance, $user, $last_week_of_posts, $number_days);
     $this->logger->logInfo("Begin generating insight", __METHOD__ . ',' . __LINE__);
     if (Utils::isTest() || date("Y-m-d") == $this->run_date) {
         $this->logger->logInfo("Should generate insight", __METHOD__ . ',' . __LINE__);
         $hero_image = array('url' => 'https://www.thinkup.com/assets/images/insights/2015-05/starwars.jpg', 'alt_text' => 'RockTrooper', 'credit' => 'Photo: JD Hancock', 'img_link' => 'https://www.flickr.com/photos/jdhancock/4932301604');
         $post_dao = DAOFactory::getDAO('PostDAO');
         $last_year_of_posts = $post_dao->getPostsByUserInRange($author_id = $instance->network_user_id, $network = $instance->network, $from = date('Y-m-d', strtotime('-1 year')), $until = date('Y-m-d'), $order_by = 'pub_date', $direction = 'DESC', $iterator = true, $is_public = false);
         $topics = array('force' => array("star wars", "force awakens", "bb-8", "darth vader", "bb8", "StarWars", "StarWarsDay"));
         $matches = array();
         $matched_posts = array();
         $matched = false;
         //print_r($last_year_of_posts);
         foreach ($last_year_of_posts as $post) {
             foreach ($topics as $key => $strings) {
                 foreach ($strings as $string) {
                     if (preg_match_all('/\\b' . strtolower($string) . '\\b/i', strtolower($post->post_text), $matches)) {
                         $matched = true;
                     }
                     //DEBUG
                     // else {
                     //     $this->logger->logInfo("Didn't find ".$string." in ".$post->post_text,
                     //         __METHOD__.','.__LINE__);
                     // }
                 }
             }
             if ($matched) {
                 $this->logger->logInfo("Matched post " . $post->post_text, __METHOD__ . ',' . __LINE__);
                 $matched_posts[] = $post;
             }
             $matched = false;
         }
         if (count($matched_posts) > 0) {
             $headline = "The Force is strong with " . $this->username . " on #StarWarsDay";
             $insight_text = $this->username . " was ready for Star Wars Day. May the fourth be with you... always.";
             $insight = new Insight();
             $insight->instance_id = $instance->id;
             $insight->slug = $this->slug;
             $insight->date = $this->run_date;
             $insight->headline = $headline;
             $insight->text = $insight_text;
             $insight->filename = basename(__FILE__, ".php");
             $insight->emphasis = Insight::EMPHASIS_HIGH;
             $insight->setHeroImage($hero_image);
             $matched_posts_sliced = array_slice($matched_posts, 0, 20);
             $insight->setPosts($matched_posts_sliced);
             $this->insight_dao->insertInsight($insight);
         }
     }
     $this->logger->logInfo("Done generating insight", __METHOD__ . ',' . __LINE__);
 }
Ejemplo n.º 9
0
 public function generateInsight(Instance $instance, User $user, $last_week_of_posts, $number_days)
 {
     if (Utils::isTest() || date("Y-m-d") == '2014-02-23') {
         parent::generateInsight($instance, $user, $last_week_of_posts, $number_days);
         $this->logger->logInfo("Begin generating insight", __METHOD__ . ',' . __LINE__);
         $hero_image = array('url' => 'https://www.thinkup.com/assets/images/insights/2014-02/olympics2014.jpg', 'alt_text' => 'The Olympic rings in Sochi', 'credit' => 'Photo: Atos International', 'img_link' => 'http://www.flickr.com/photos/atosorigin/12568057033/');
         $post_dao = DAOFactory::getDAO('PostDAO');
         $last_month_of_posts = $post_dao->getAllPostsByUsernameOrderedBy($instance->network_username, $network = $instance->network, $count = 0, $order_by = "pub_date", $in_last_x_days = 30, $iterator = false, $is_public = false);
         if (self::shouldGenerateWeeklyInsight('olympics_2014', $instance, $insight_date = 'today', $regenerate_existing_insight = true, $day_of_week = 0, count($last_month_of_posts))) {
             $event_count = 0;
             foreach ($last_month_of_posts as $post) {
                 $event_count += self::countOlympicReferences($post->post_text);
             }
             $this->logger->logInfo("There are {$event_count} Olympic-related mentions", __METHOD__ . ',' . __LINE__);
             if ($event_count > 0) {
                 $headline = "Do they give out medals for " . $this->terms->getNoun('post', InsightTerms::PLURAL) . "?";
                 $insight_text = "{$this->username} mentioned ";
                 if ($event_count > 0) {
                     $this->logger->logInfo("There are event mentions", __METHOD__ . ',' . __LINE__);
                     $insight_text .= "the Olympics ";
                     if ($event_count > 1) {
                         $this->logger->logInfo("there is more than one event mention", __METHOD__ . ',' . __LINE__);
                         $insight_text .= "{$event_count} times since they started.";
                         $insight_text .= " That's kind of like winning {$event_count} gold medals in " . ucfirst($instance->network) . ", right?";
                     } else {
                         $insight_text .= "just as the whole world's attention was focused on the Games.";
                         $insight_text .= " That's a pretty great way to join a global conversation.";
                     }
                 }
                 $my_insight = new Insight();
                 $my_insight->slug = 'olympics_2014';
                 //slug to label this insight's content
                 $my_insight->instance_id = $instance->id;
                 $my_insight->date = $this->insight_date;
                 //date is often this or $simplified_post_date
                 $my_insight->headline = $headline;
                 // or just set a string like 'Ohai';
                 $my_insight->text = $insight_text;
                 // or just set a strong like "Greetings humans";
                 $my_insight->filename = basename(__FILE__, ".php");
                 //Same for every insight, must be set this way
                 $my_insight->emphasis = Insight::EMPHASIS_HIGH;
                 //Optional emphasis, default is Insight::EMPHASIS_LOW
                 $my_insight->setHeroImage($hero_image);
                 $this->insight_dao->insertInsight($my_insight);
             }
         }
         $this->logger->logInfo("Done generating insight", __METHOD__ . ',' . __LINE__);
     }
 }
Ejemplo n.º 10
0
 public function generateInsight(Instance $instance, User $user, $last_week_of_posts, $number_days)
 {
     if (Utils::isTest() || date("Y-m-d") == $this->run_date) {
         parent::generateInsight($instance, $user, $last_week_of_posts, $number_days);
         $this->logger->logInfo("Begin generating insight", __METHOD__ . ',' . __LINE__);
         $hero_image = array('url' => 'https://www.thinkup.com/assets/images/insights/2015-02/llama.jpg', 'alt_text' => 'Llama', 'credit' => 'Photo: Eric Kilby', 'img_link' => 'https://www.flickr.com/photos/ekilby/8564867495/');
         $should_generate_insight = self::shouldGenerateWeeklyInsight($this->slug, $instance, $insight_date = $this->run_date, $regenerate_existing_insight = false, $day_of_week = 5, count($last_week_of_posts));
         if ($should_generate_insight) {
             $this->logger->logInfo("Should generate", __METHOD__ . ',' . __LINE__);
             $post_dao = DAOFactory::getDAO('PostDAO');
             $topics = array('llama' => array("llama", "llamas"));
             $matches = array();
             foreach ($last_week_of_posts as $post) {
                 foreach ($topics as $key => $strings) {
                     foreach ($strings as $string) {
                         if (preg_match_all('/\\b' . $string . '\\b/i', $post->post_text) > 0) {
                             $matches[$key] = array('term' => $string, 'post' => $post);
                             unset($topics[$key]);
                             break;
                         }
                     }
                 }
             }
             if (count($matches) == 0) {
                 $headline = $this->username . ' managed to avoid llamageddon!';
                 $insight_text = "It seems like half the internet was " . "<a href='http://www.theverge.com/2015/2/26/8116693/live-the-internet-is-going-bananas-" . "for-this-llama-chase'>talking about runaway llamas</a> " . 'yesterday. Kudos to ' . $this->username . ' for showing a llama restraint.';
             } else {
                 $headline = $this->username . " showed a whole llama love";
                 $insight_text = "Two runaway llamas <a href='http://www.theverge.com/2015/2/26/8116693/live-" . "the-internet-is-going-bananas-for-this-llama-chase'>took over Twitter yesterday</a>" . ", and like a llama people, " . $this->username . " couldn't resist.";
             }
             $insight = new Insight();
             $insight->instance_id = $instance->id;
             $insight->slug = $this->slug;
             $insight->date = $this->run_date;
             $insight->headline = $headline;
             $insight->text = $insight_text;
             $insight->filename = basename(__FILE__, ".php");
             $insight->emphasis = Insight::EMPHASIS_HIGH;
             $insight->setHeroImage($hero_image);
             $this->insight_dao->insertInsight($insight);
         }
         $this->logger->logInfo("Done generating insight", __METHOD__ . ',' . __LINE__);
     }
 }
Ejemplo n.º 11
0
 /**
  * Determine whether an insight should be generated or not.
  * @param str $slug slug of the insight to be generated
  * @param Instance $instance user and network details for which the insight has to be generated
  * @param date $insight_date date for which the insight has to be generated
  * @param bool $regenerate_existing_insight whether the insight should be regenerated over a day
  * @param int $day_of_week the day of week (0 for Sunday through 6 for Saturday) on which the insight should run
  * @param int $count_last_week_of_posts if set, wouldn't run insight if there are no posts from last week
  * @param arr $excluded_networks array of networks for which the insight shouldn't be run
  * @return bool $run whether the insight should be generated or not
  */
 public function shouldGenerateInsight($slug, Instance $instance, $insight_date = null, $regenerate_existing_insight = false, $day_of_week = null, $count_last_week_of_posts = null, $excluded_networks = null)
 {
     $run = true;
     // Check the number of posts from last week
     if (isset($count_last_week_of_posts)) {
         $run = $run && $count_last_week_of_posts;
     }
     // Check whether testing
     if (Utils::isTest()) {
         return $run && Utils::isTest();
     }
     // Check the day of the week (0 for Sunday through 6 for Saturday) on which the insight should run
     if (isset($day_of_week)) {
         if (date('w') == $day_of_week) {
             $run = $run && true;
         } else {
             $run = $run && false;
         }
     }
     // Check boolean whether insight should be regenerated over a day
     if (!$regenerate_existing_insight) {
         $insight_date = isset($insight_date) ? $insight_date : 'today';
         $existing_insight = $this->insight_dao->getInsight($slug, $instance->id, date('Y-m-d', strtotime($insight_date)));
         if (isset($existing_insight)) {
             $run = $run && false;
         } else {
             $run = $run && true;
         }
     }
     // Check array of networks for which the insight should run
     if (isset($excluded_networks)) {
         if (in_array($instance->network, $excluded_networks)) {
             $run = $run && false;
         } else {
             $run = $run && true;
         }
     }
     return $run;
 }
Ejemplo n.º 12
0
 /**
  * Send email from ThinkUp installation via Mandrill's API.
  * If you're running tests, just write the message headers and contents to the file system in the data directory.
  * @param str $to A valid email address
  * @param str $subject
  * @param str $message
  */
 public static function mailViaMandrill($to, $subject, $message)
 {
     $config = Config::getInstance();
     $app_title = $config->getValue('app_title_prefix') . "ThinkUp";
     $host = self::getHost();
     $mandrill_api_key = $config->getValue('mandrill_api_key');
     try {
         require_once THINKUP_WEBAPP_PATH . '_lib/extlib/mandrill/Mandrill.php';
         $mandrill = new Mandrill($mandrill_api_key);
         $message = array('text' => $message, 'subject' => $subject, 'from_email' => "notifications@{$host}", 'from_name' => $app_title, 'to' => array(array('email' => $to, 'name' => $to)));
         //don't send email when running tests, just write it to the filesystem for assertions
         if (Utils::isTest()) {
             self::setLastMail(json_encode($message));
         } else {
             $result = $mandrill->messages->send($message, $async, $ip_pool);
             //DEBUG
             //print_r($result);
         }
     } catch (Mandrill_Error $e) {
         throw new Exception('An error occurred while sending email via Mandrill. ' . get_class($e) . ': ' . $e->getMessage());
     }
 }
Ejemplo n.º 13
0
 /**
  * Send email from ThinkUp installation via Mandrill's API.
  * If you're running tests, just write the message headers and contents to the file system in the data directory.
  * @param str $to A valid email address
  * @param str $subject
  * @param str $message
  */
 public static function mailViaMandrill($to, $subject, $message)
 {
     $config = Config::getInstance();
     $app_title = $config->getValue('app_title_prefix') . "Empoddy Labs";
     $host = Utils::getApplicationHostName();
     $mandrill_api_key = $config->getValue('mandrill_api_key');
     if (Utils::isEmpoddyLabs()) {
         $from_email = '*****@*****.**';
     } else {
         $from_email = "notifications@{$host}";
     }
     try {
         require_once EFC_WEBAPP_PATH . '_lib/extlib/mandrill/Mandrill.php';
         $mandrill = new Mandrill($mandrill_api_key);
         $tos = array();
         foreach ($to as $key => $value) {
             $tos[] = array('email' => $value, 'name' => $value);
         }
         //$message = array( 'text' => $message, 'subject' => $subject, 'from_email' => $from_email,
         //'from_name' => $app_title, 'to' => array( array( 'email' => $to, 'name' => $to ) ) );
         $message = array('text' => $message, 'subject' => $subject, 'from_email' => $from_email, 'from_name' => $app_title, 'to' => $tos);
         //don't send email when running tests, just write it to the filesystem for assertions
         if (Utils::isTest()) {
             self::setLastMail(json_encode($message));
         } else {
             $async = true;
             $ip_pool = "Main pool";
             $result = $mandrill->messages->send($message, $async, $ip_pool);
             //DEBUG
             //print_r($result);
         }
     } catch (Mandrill_Error $e) {
         throw new Exception('An error occurred while sending email via Mandrill. ' . get_class($e) . ': ' . $e->getMessage());
     }
 }
Ejemplo n.º 14
0
 /**
  * Check if ThinkUp is already installed, that is, that:
  *  all system requirements are met;
  *  the ThinkUp config.inc.php file exists;
  *  all ThinkUp tables exist
  *  all tables report a status ok "Okay"
  *
  * @param array $config
  * @return bool true when ThinkUp is already installed
  */
 public function isThinkUpInstalled($config)
 {
     // check if file config present
     $config_file_exists = false;
     $config_file = THINKUP_WEBAPP_PATH . 'config.inc.php';
     // check if we have made config.inc.php
     if (file_exists($config_file)) {
         $config_file_exists = true;
     } else {
         self::$error_messages['config_file'] = "Config file doesn't exist.";
         return false;
     }
     // check version is met
     $version_met = self::checkStep1();
     // when testing
     if (Utils::isTest() && !empty($pass)) {
         $version_met = $pass;
     }
     if (!$version_met) {
         self::$error_messages['requirements'] = "Requirements are not met. " . "Make sure your PHP version >= " . self::$required_version['php'] . ", " . "you have cURL and GD extension installed, and template and log directories are writable";
         return false;
     }
     // database is okay
     $db_check = self::checkDb($config);
     // table present
     $table_present = true;
     if (!self::doThinkUpTablesExist($config)) {
         self::$error_messages['table'] = 'ThinkUp\'s database tables are not fully installed.';
         $table_present = false;
     }
     return $version_met && $db_check === true && $table_present;
 }
 public function control()
 {
     $config = Config::getInstance();
     $this->setViewTemplate($this->tpl_name);
     $this->addToView('enable_bootstrap', true);
     $this->addToView('developer_log', $config->getValue('is_log_verbose'));
     $this->addToView('thinkup_application_url', Utils::getApplicationURL());
     if ($this->shouldRefreshCache()) {
         if (isset($_GET['u']) && isset($_GET['n']) && isset($_GET['d']) && isset($_GET['s'])) {
             $this->displayIndividualInsight();
             if (isset($_GET['share'])) {
                 $this->addToView('share_mode', true);
             }
         } else {
             if (!$this->displayPageOfInsights()) {
                 $controller = new LoginController(true);
                 return $controller->go();
             }
         }
         if ($this->isLoggedIn()) {
             //Populate search dropdown with service users and add thinkup_api_key for desktop notifications.
             $owner_dao = DAOFactory::getDAO('OwnerDAO');
             $owner = $owner_dao->getByEmail($this->getLoggedInUser());
             $this->addToView('thinkup_api_key', $owner->api_key);
             $this->addHeaderJavaScript('assets/js/notify-insights.js');
             $instance_dao = DAOFactory::getDAO('InstanceDAO');
             $instances = $instance_dao->getByOwnerWithStatus($owner);
             $this->addToView('instances', $instances);
             $saved_searches = array();
             if (sizeof($instances) > 0) {
                 $instancehashtag_dao = DAOFactory::getDAO('InstanceHashtagDAO');
                 $saved_searches = $instancehashtag_dao->getHashtagsByInstances($instances);
             }
             $this->addToView('saved_searches', $saved_searches);
             //Start off assuming connection doesn't exist
             $connection_status = array('facebook' => 'inactive', 'twitter' => 'inactive', 'instagram' => 'inactive');
             foreach ($instances as $instance) {
                 if ($instance->auth_error != '') {
                     $connection_status[$instance->network] = 'error';
                 } else {
                     //connection exists, so it's active
                     $connection_status[$instance->network] = 'active';
                 }
             }
             $this->addToView('facebook_connection_status', $connection_status['facebook']);
             $this->addToView('twitter_connection_status', $connection_status['twitter']);
             $this->addToView('instagram_connection_status', $connection_status['instagram']);
         }
     }
     if (Utils::isTest() || date("Y-m-d") == '2015-11-26') {
         $this->addInfoMessage("Happy Thanksgiving! We're thankful you're using ThinkUp.");
     }
     $this->addToView('tpl_path', THINKUP_WEBAPP_PATH . 'plugins/insightsgenerator/view/');
     if ($config->getValue('image_proxy_enabled') == true) {
         $this->addToView('image_proxy_sig', $config->getValue('image_proxy_sig'));
     }
     return $this->generateView();
 }
 /**
  * Determine whether an end-of-year insight should be generated.
  * This is similar to shouldGenerateAnnualInsight, with one key difference, in that it will return true for an
  * insight scheduled on a date that has passed. So if an insight should run on December 1st,
  * and a user joins ThinkUp on December 3rd, that insight should get generated.
  *
  * @param str $slug slug of the insight to be generated
  * @param Instance $instance user and network details for which the insight has to be generated
  * @param str $insight_date valid strtotime parameter for insight date, defaults $day_of_year in current year.
  * @param bool $regenerate_existing_insight whether the insight should be regenerated over a day
  * @param str $day_of_year Day of the year to run in American MM/DD format. (ex. 12/25 = Christmas, December 25th)
  * @param int $count_related_posts if set, wouldn't run insight if there are no posts related to insight
  * @param arr $excluded_networks array of networks for which the insight shouldn't be run
  * @return bool Whether the insight should be generated or not
  */
 public function shouldGenerateEndOfYearAnnualInsight($slug, Instance $instance, $insight_date = null, $regenerate_existing_insight = false, $day_of_year = null, $count_related_posts = null, $excluded_networks = array())
 {
     if (Utils::isTest()) {
         return true;
     }
     $run = self::shouldGenerateInsight($slug, $instance, $insight_date, $regenerate_existing_insight, $count_related_posts, $excluded_networks);
     if (!$run) {
         return false;
     }
     if ($day_of_year === null) {
         $day_of_year = date('n-j');
     }
     //Do generate insight if today is past the end-of-year insight date
     $todays_day_of_year = date('z');
     list($month, $day) = preg_split('/[^0-9]+/', $day_of_year);
     $doy_date_str = date('Y') . '-' . $month . '-' . $day;
     $insight_day_of_year = date('z', strtotime($doy_date_str));
     return $todays_day_of_year >= $insight_day_of_year;
 }
Ejemplo n.º 17
0
 /**
  * Complete login action
  * @param Owner $owner
  * @return void
  */
 public static function completeLogin($owner)
 {
     SessionCache::put('user', $owner->email);
     SessionCache::put('user_is_admin', $owner->is_admin);
     // set a CSRF token
     SessionCache::put('csrf_token', uniqid(mt_rand(), true));
     if (Utils::isTest()) {
         SessionCache::put('csrf_token', 'TEST_CSRF_TOKEN');
     }
     // check for and validate an existing long-term cookie before creating one
     $cookie_dao = DAOFactory::getDAO('CookieDAO');
     $set_long_term = true;
     if (!empty($_COOKIE[self::COOKIE_NAME])) {
         $email = $cookie_dao->getEmailByCookie($_COOKIE[self::COOKIE_NAME]);
         $set_long_term = $email != $owner->email;
     }
     if ($set_long_term) {
         $cookie = $cookie_dao->generateForEmail($owner->email);
         if (!headers_sent()) {
             setcookie(self::COOKIE_NAME, $cookie, time() + 60 * 60 * 24 * 365 * 10, '/', self::getCookieDomain());
         }
     }
 }
Ejemplo n.º 18
0
 /**
  * Return the expanded version of a given short URL or save an error for the $original_link in links table and
  * return an empty string.
  *
  * @param str $tinyurl Shortened URL
  * @param str $original_link
  * @param int $current_number Current link number
  * @param int $total_number Total links in group
  * @return str Expanded URL
  */
 public static function expandURL($tinyurl, $original_link, $current_number, $total_number, $link_dao, $logger)
 {
     if (Utils::isTest()) {
         //for testing without actually making requests
         return $original_link . '/expandedversion';
     }
     $error_log_prefix = $current_number . " of " . $total_number . " links: ";
     $url = parse_url($tinyurl);
     if (isset($url['host'])) {
         $host = $url['host'];
     } else {
         $error_msg = $tinyurl . ": No host found.";
         $logger->logError($error_log_prefix . $error_msg, __METHOD__ . ',' . __LINE__);
         $link_dao->saveExpansionError($original_link, $error_msg);
         return '';
     }
     $port = isset($url['port']) ? ':' . $url['port'] : '';
     $query = isset($url['query']) ? '?' . $url['query'] : '';
     $fragment = isset($url['fragment']) ? '#' . $url['fragment'] : '';
     if (empty($url['path'])) {
         $path = '';
     } else {
         $path = $url['path'];
     }
     $scheme = isset($url['scheme']) ? $url['scheme'] : 'http';
     $reconstructed_url = $scheme . "://{$host}{$port}" . $path . $query . $fragment;
     $logger->logInfo("Making cURL request for " . $reconstructed_url, __METHOD__ . ',' . __LINE__);
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($ch, CURLOPT_URL, $reconstructed_url);
     curl_setopt($ch, CURLOPT_TIMEOUT, 5);
     // seconds
     curl_setopt($ch, CURLOPT_HEADER, true);
     curl_setopt($ch, CURLOPT_NOBODY, true);
     curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
     curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0");
     $response = curl_exec($ch);
     if ($response === false) {
         $error_msg = $reconstructed_url . " cURL error: " . curl_error($ch);
         $logger->logError($error_log_prefix . $error_msg, __METHOD__ . ',' . __LINE__);
         $link_dao->saveExpansionError($original_link, $error_msg);
         $tinyurl = '';
     }
     curl_close($ch);
     $lines = explode("\r\n", $response);
     foreach ($lines as $line) {
         if (stripos($line, 'Location:') === 0) {
             list(, $location) = explode(':', $line, 2);
             $result = ltrim($location);
             //If this is a relative redirect, add the host
             $dest_url = parse_url($result);
             if (!isset($dest_url['host'])) {
                 $result = $scheme . "://{$host}{$port}" . $result;
             }
             return $result;
         }
     }
     if (strpos($response, 'HTTP/1.1 404 Not Found') === 0) {
         $error_msg = $reconstructed_url . " returned '404 Not Found'";
         $logger->logError($error_log_prefix . $error_msg, __METHOD__ . ',' . __LINE__);
         $link_dao->saveExpansionError($original_link, $error_msg);
         return '';
     }
     return $tinyurl;
 }
 /**
  * Repair ThinkUp installation
  *
  * @param str $to_repair
  */
 private function repairInstallation($to_repair)
 {
     $this->setViewTemplate('install.repair.tpl');
     // check requirements on step #1
     $this->installer->repairerCheckStep1();
     // check file configuration
     $config_file = $this->installer->repairerCheckConfigFile();
     require $config_file;
     // check database
     $this->installer->checkDb($THINKUP_CFG);
     // check $THINKUP_CFG['repair'] is set to true
     // bypass this security check when running tests
     if (Utils::isTest()) {
         $THINKUP_CFG['repair'] = true;
     }
     $this->installer->repairerIsDefined($THINKUP_CFG);
     // clear error messages before doing the repair
     $this->installer->clearErrorMessages();
     $info = '';
     // do repairing when form is posted and $_GET is not empty
     if (isset($_POST['repair']) && !empty($_GET)) {
         $this->addToView('posted', true);
         $succeed = false;
         $messages = array();
         // check database again
         $this->installer->checkDb($THINKUP_CFG);
         // check if we repairing db
         if ($to_repair == "db") {
             $messages['db'] = $this->installer->repairTables($THINKUP_CFG);
             $this->addToView('messages_db', $messages['db']);
         }
         $error_messages = $this->installer->getErrorMessages();
         if (!empty($error_messages)) {
             // failed repairing
             $this->addToView('messages_error', $error_messages);
         } else {
             $succeed = true;
         }
         $this->addToView('succeed', $succeed);
     } else {
         if (empty($_GET)) {
             $this->addToView('show_form', 0);
         } else {
             $information_message = array();
             $this->addToView('show_form', 1);
             if ($to_repair == "db") {
                 $information_message['db'] = 'Check your existing ThinkUp tables. If some tables are missing ';
                 $information_message['db'] .= 'or need repair, ThinkUp will attempt to create or repair them.';
             }
             if (!empty($information_message)) {
                 $info .= '<p><strong>Important!</strong> <br />';
                 $info .= 'The ThinkUp repair process will: </p><ul>';
                 foreach ($information_message as $msg) {
                     $info .= "<li>{$msg}</li>";
                 }
                 $info .= '</ul>';
                 $this->addInfoMessage($info, null, true);
             }
             $this->addToView('action_form', $_SERVER['REQUEST_URI']);
         }
     }
 }