private function deleteFile($file)
 {
     $file = FileDataManager::getBackupPath($file);
     if (file_exists($file)) {
         unlink($file);
     }
 }
Exemplo n.º 2
0
 public function __construct($session_started = false)
 {
     parent::__construct($session_started);
     $this->setViewTemplate('install.backup.tpl');
     $this->setPageTitle('Backup & Restore');
     $this->backup_file = FileDataManager::getDataPath('.htthinkup_db_backup.zip');
     // not in the backup dir itself
 }
 public function tearDown()
 {
     $this->builders = null;
     $test_email = FileDataManager::getDataPath(Mailer::EMAIL);
     if (file_exists($test_email)) {
         unlink($test_email);
     }
     parent::tearDown();
 }
Exemplo n.º 4
0
 public function tearDown()
 {
     parent::tearDown();
     // delete test email file if it exists
     $test_email = FileDataManager::getDataPath(Mailer::EMAIL);
     if (file_exists($test_email)) {
         unlink($test_email);
     }
 }
Exemplo n.º 5
0
 /**
  * Return the contents of the last email Mailer "sent" out.
  * For testing purposes only; this will return nothing in production.
  * @return str The contents of the last email sent
  */
 public static function getLastMail()
 {
     $test_email_file = FileDataManager::getDataPath(Mailer::EMAIL);
     if (file_exists($test_email_file)) {
         return file_get_contents($test_email_file);
     } else {
         return '';
     }
 }
Exemplo n.º 6
0
 public function setUp()
 {
     parent::setUp();
     new BackupMySQLDAO();
     $this->config = Config::getInstance();
     $this->pdo = BackupMySQLDAO::$PDO;
     $this->backup_file = FileDataManager::getDataPath('.htthinkup_db_backup.zip');
     $this->backup_test = FileDataManager::getDataPath('thinkup_db_backup_test.zip');
     $this->backup_dir = FileDataManager::getBackupPath() . '/';
 }
Exemplo n.º 7
0
 public function tearDown()
 {
     parent::tearDown();
     $config = Config::getInstance();
     $config->setValue("mandrill_api_key", "");
     // delete test email file if it exists
     $test_email = FileDataManager::getDataPath(Mailer::EMAIL);
     if (file_exists($test_email)) {
         unlink($test_email);
     }
 }
Exemplo n.º 8
0
 public function tearDown()
 {
     parent::tearDown();
     $zipfile = FileDataManager::getBackupPath('.htthinkup_db_backup.zip');
     $backup_dir = FileDataManager::getBackupPath();
     if (file_exists($zipfile)) {
         unlink($zipfile);
     }
     if (file_exists($backup_dir)) {
         $this->recursiveDelete($backup_dir);
     }
 }
Exemplo n.º 9
0
 public function testGetBackupPath()
 {
     require THINKUP_WEBAPP_PATH . 'config.inc.php';
     //if test fails here, the config file doesn't have datadir_path set
     $this->assertNotNull($THINKUP_CFG['datadir_path']);
     //test just path
     $path = FileDataManager::getBackupPath();
     $this->assertEqual($path, $THINKUP_CFG['datadir_path'] . 'backup/');
     //test just path
     $path = FileDataManager::getBackupPath('README.txt');
     $this->assertEqual($path, $THINKUP_CFG['datadir_path'] . 'backup/README.txt');
 }
Exemplo n.º 10
0
 /**
  * Test default values
  */
 public function testViewManagerDefaultValues()
 {
     $cfg = Config::getInstance();
     $cfg->setValue('source_root_path', '/path/to/thinkup/');
     $cfg->setValue('cache_pages', true);
     $cfg->setValue('cache_lifetime', 600);
     $v_mgr = new ViewManager();
     $this->assertTrue(sizeof($v_mgr->template_dir), 2);
     $this->assertEqual($v_mgr->template_dir[1], '/path/to/thinkup/tests/view');
     $this->assertTrue(sizeof($v_mgr->plugins_dir), 2);
     $this->assertEqual($v_mgr->plugins_dir[0], 'plugins');
     $this->assertEqual($v_mgr->cache_dir, FileDataManager::getDataPath('compiled_view/cache'));
     $this->assertEqual($v_mgr->cache_lifetime, $cfg->getValue('cache_lifetime'));
     $this->assertTrue($v_mgr->caching);
 }
 public function testTokenEmailWithSSL()
 {
     $config = Config::getInstance();
     $site_root_path = $config->getValue('site_root_path');
     // build 1 valid admin and two invalid admins
     $builder1 = FixtureBuilder::build('owners', array('is_admin' => 1, 'is_activated' => 1, 'email' => '*****@*****.**'));
     $builder2 = FixtureBuilder::build('owners', array('is_admin' => 0, 'is_activated' => 1, 'email' => '*****@*****.**'));
     $builder3 = FixtureBuilder::build('owners', array('is_admin' => 1, 'is_activated' => 0, 'email' => '*****@*****.**'));
     $_SERVER['HTTP_HOST'] = "mytestthinkup";
     $_SERVER['HTTPS'] = "mytestthinkup";
     $controller = new UpgradeDatabaseController(true);
     $results = $controller->go();
     $this->assertTrue(file_exists($this->token_file));
     $this->assertPattern('/<!--  we are upgrading -->/', $results);
     $this->assertTrue(file_exists($this->token_file));
     $token = file_get_contents($this->token_file);
     $this->assertPattern('/^[\\da-f]{32}$/', $token);
     $email_file = Mailer::getLastMail();
     $this->debug($email_file);
     $this->assertPattern('/to\\: m@w\\.nz\\s/', $email_file);
     $this->assertPattern('/subject\\: Upgrade Your ThinkUp Database/', $email_file);
     $token_regex = '/https:\\/\\/mytestthinkup' . str_replace('/', '\\/', $site_root_path) . 'install\\/upgrade-database.php\\?upgrade_token=' . $token . '/';
     $this->assertPattern($token_regex, $email_file);
     // build 1 more valid admin, should have two to emails
     $test_email = FileDataManager::getDataPath(Mailer::EMAIL);
     unlink($test_email);
     unlink($this->token_file);
     $builder4 = FixtureBuilder::build('owners', array('is_admin' => 1, 'is_activated' => 1, 'email' => '*****@*****.**'));
     $results = $controller->go();
     $this->assertTrue(file_exists($this->token_file));
     $this->assertPattern('/<!--  we are upgrading -->/', $results);
     $this->assertTrue(file_exists($this->token_file));
     $token = file_get_contents($this->token_file);
     $this->assertPattern('/^[\\da-f]{32}$/', $token);
     $email_file = Mailer::getLastMail();
     $this->assertPattern('/to\\: m@w\\.nz,m4@w\\.nz\\s/', $email_file);
     $this->assertPattern('/subject\\: Upgrade Your ThinkUp Database/', $email_file);
     $token_regex = '/\\/install\\/upgrade-database.php\\?upgrade_token=' . $token . '/';
     $this->assertPattern($token_regex, $email_file);
     // should not send email if a token file exists
     $test_email = FileDataManager::getDataPath(Mailer::EMAIL);
     unlink($test_email);
     $results = $controller->go();
     $this->assertFalse(file_exists($test_email));
 }
Exemplo n.º 12
0
 public function testIsSessionDirectoryWritable()
 {
     //get whatever session save path is set to
     $session_save_path = ini_get('session.save_path');
     ini_set('session.save_path', FileDataManager::getDataPath());
     $installer = Installer::getInstance();
     $session_save_permission = $installer->isSessionDirectoryWritable();
     $this->assertTrue($session_save_permission);
     //reset back to what it was
     ini_set('session.save_path', $session_save_path);
 }
Exemplo n.º 13
0
 public function export($backup_file = null)
 {
     // get table names...
     $q = "show tables";
     $q2 = "show create table ";
     $stmt = $this->execute($q);
     $data = $this->getDataRowsAsArrays($stmt);
     $create_tables = '';
     $zip_file = FileDataManager::getDataPath('.htthinkup_db_backup.zip');
     if ($backup_file) {
         $zip_file = $backup_file;
     }
     $zip = new ZipArchive();
     if (file_exists($zip_file)) {
         unlink($zip_file);
     }
     // make sure w can create this zip file, ZipArchive is a little funky and wont let us know its status
     // until we call close
     $zip_create_status = @touch($zip_file);
     if ($zip_create_status) {
         unlink($zip_file);
     }
     $backup_dir = FileDataManager::getBackupPath();
     if (!$zip_create_status || $zip->open($zip_file, ZIPARCHIVE::CREATE) !== TRUE) {
         throw new Exception("Unable to open backup file for exporting: {$zip_file}");
     }
     // write lock tables...
     $table_locks_list = '';
     foreach ($data as $table) {
         foreach ($table as $key => $value) {
             if ($table_locks_list != '') {
                 $table_locks_list .= ', ';
             }
             $table_locks_list .= $value . ' WRITE';
         }
     }
     try {
         $stmt = $this->execute("LOCK TABLES " . $table_locks_list);
         $tmp_table_files = array();
         foreach ($data as $table) {
             foreach ($table as $key => $value) {
                 if (getenv('BACKUP_VERBOSE') !== false) {
                     print "  Backing up data for table: {$value}\n";
                 }
                 $stmt = $this->execute($q2 . $value);
                 $create_tables .= "-- Create {$value} table statement\n";
                 $create_tables .= "DROP TABLE IF EXISTS {$value};\n";
                 $create_data = $this->getDataRowAsArray($stmt);
                 $create_tables .= $create_data["Create Table"] . ";";
                 $create_tables .= "\n\n";
                 // export table data
                 $table_file = FileDataManager::getBackupPath($value . '.txt');
                 if (file_exists($table_file)) {
                     unlink($table_file);
                 }
                 $q3 = "select * INTO OUTFILE '{$table_file}' from {$value}";
                 $stmt = $this->execute($q3);
                 $zip->addFile($table_file, "/{$value}" . '.txt');
                 array_push($tmp_table_files, $table_file);
             }
         }
     } catch (Exception $e) {
         $err = $e->getMessage();
         if (preg_match("/Can't create\\/write to file/", $err) || preg_match("/Can\\'t get stat of/", $err)) {
             // a file perm issue?
             throw new OpenFileException("It looks like the MySQL user does not have the proper file permissions " . "to back up data");
         } else {
             // assume its a GRANT FILE OR LOCK TABLES issue?
             throw new MySQLGrantException("It looks like the MySQL user does not have the proper grant permissions " . "to back up data");
         }
         error_log("export DB OUTFILE error: " . $e->getMessage());
     }
     // unlock tables...
     $stmt = $this->execute("unlock tables");
     if (getenv('BACKUP_VERBOSE') !== false) {
         print "\n  Backing up create table statments\n";
     }
     $zip->addFromString("create_tables.sql", $create_tables);
     $zip_close_status = $zip->close();
     // clean up tmp table files
     foreach ($tmp_table_files as $tmp_file) {
         unlink($tmp_file);
     }
     if ($zip_close_status == false) {
         throw new Exception("Unable to create backup file for exporting. Bad file path?: {$zip_file}");
     }
     return $zip_file;
 }
 /**
  * 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 SmartyThinkUp();
             $upgrade_email->caching = false;
             $server = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost';
             //supress test weirdness
             $upgrade_email->assign('server', $server);
             $upgrade_email->assign('token', $md5_token);
             $message = $upgrade_email->fetch('_email.upgradetoken.tpl');
             $config = Config::getInstance();
             Mailer::mail($to, "Upgrade Your ThinkUp Database", $message);
         }
     }
 }
Exemplo n.º 15
0
    public function testCrawlWithAuthError()
    {
        //build active instance owned by a owner
        $instance_with_autherror = array('id' => 5, 'network_username' => 'Liz Lemon', 'network_user_id' => '123456', 'network_viewer_id' => '123456', 'last_post_id' => '0', 'total_posts_in_system' => '0', 'total_replies_in_system' => '0', 'total_follows_in_system' => '0', 'is_archive_loaded_replies' => '0', 'is_archive_loaded_follows' => '0', 'crawler_last_run' => '', 'earliest_reply_in_system' => '', 'avg_replies_per_day' => '2', 'is_public' => '0', 'is_active' => '1', 'network' => 'facebook', 'last_favorite_id' => '0', 'owner_favs_in_system' => '0', 'total_posts_by_owner' => 0, 'posts_per_day' => 1, 'posts_per_week' => 1, 'percentage_replies' => 50, 'percentage_links' => 50, 'earliest_post_in_system' => '2009-01-01 13:48:05', 'favorites_profile' => '0');
        $instance_builder_1 = FixtureBuilder::build('instances', $instance_with_autherror);
        $builders = array();
        $builders[] = FixtureBuilder::build('owners', array('id' => 1, 'full_name' => 'ThinkUp J. User', 'email' => '*****@*****.**', 'is_activated' => 1));
        $builders[] = FixtureBuilder::build('owner_instances', array('owner_id' => 1, 'instance_id' => 5, 'auth_error' => ''));
        //assert invalid_oauth_email_sent_timestamp option is not set
        $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');
        $this->assertNull($last_email_timestamp);
        //log in as that owner
        $this->simulateLogin('*****@*****.**');
        $_SERVER['HTTP_HOST'] = "mytestthinkup";
        //run the crawl
        $fb_plugin = new FacebookPlugin();
        $fb_plugin->crawl();
        //assert that APIOAuthException was caught and recorded in owner_instances table
        $owner_instance_dao = new OwnerInstanceMySQLDAO();
        $owner_instance = $owner_instance_dao->get(1, 5);
        $this->assertEqual($owner_instance->auth_error, 'Error validating access token: Session has expired at unix ' . 'time SOME_TIME. The current unix time is SOME_TIME.');
        //assert that the email notification was sent to the user
        $expected_reg_email_pattern = '/to: me@example.com
subject: Please re-authorize ThinkUp to access Liz Lemon on Facebook
message: Hi! Your ThinkUp installation is no longer connected to the Liz Lemon Facebook account./';
        $actual_reg_email = Mailer::getLastMail();
        $this->debug($actual_reg_email);
        $this->assertPattern($expected_reg_email_pattern, $actual_reg_email);
        //assert invalid_oauth_email_sent_timestamp option has been set
        $last_email_timestamp = $option_dao->getOptionByName(OptionDAO::PLUGIN_OPTIONS . '-' . $plugin_id, 'invalid_oauth_email_sent_timestamp');
        $this->assertNotNull($last_email_timestamp);
        //Delete last mail file
        $test_email_file = FileDataManager::getDataPath(Mailer::EMAIL);
        unlink($test_email_file);
        $actual_reg_email = Mailer::getLastMail();
        //Assert it's been deleted
        $this->assertEqual($actual_reg_email, '');
        //Crawl again
        $fb_plugin->crawl();
        //Assert email has not been resent
        $actual_reg_email = Mailer::getLastMail();
        $this->debug($actual_reg_email);
        $this->assertEqual($actual_reg_email, '');
    }
 protected function exportCountHistory($user_id, $network)
 {
     //just the max of each day's count
     $count_history_table_file = FileDataManager::getBackupPath('count_history.tmp');
     $export_dao = DAOFactory::getDAO('ExportDAO');
     $export_dao->exportCountHistoryToFile($user_id, $network, $count_history_table_file);
     $this->files_to_zip[] = array('path' => $count_history_table_file, 'name' => 'count_history.tmp');
     $import_instructions = "LOAD DATA INFILE '/your/path/to/count_history.tmp' ";
     $import_instructions .= "IGNORE INTO TABLE tu_count_history;\n\n";
     self::appendToReadme($import_instructions);
 }
Exemplo n.º 17
0
 /**
  * Clear the follower ID last cursor saved to file.
  * @return bool
  */
 public function clearFollowerIDLastCursor()
 {
     return unlink(FileDataManager::getDataPath('follower-id-last-cursor.txt'));
 }
 /**
  * Step 1 - Check system requirements
  */
 private function step1()
 {
     $this->setViewTemplate('install.step1.tpl');
     // php version check
     $php_compat = false;
     if ($this->installer->checkVersion()) {
         $php_compat = true;
     }
     $this->addToView('php_compat', $php_compat);
     $requiredVersion = $this->installer->getRequiredVersion();
     $this->addToView('php_required_version', $requiredVersion['php']);
     // libs check
     if (isset($this->reqs)) {
         //testing only
         $libs = $this->installer->checkDependency($this->reqs);
     } else {
         $libs = $this->installer->checkDependency();
     }
     $libs_compat = true;
     foreach ($libs as $lib) {
         if (!$lib) {
             $libs_compat = false;
         }
     }
     $this->addToView('libs', $libs);
     // path permissions check
     $permissions = $this->installer->checkPermission();
     $this->addToView('permission', $permissions);
     $permissions_compat = true;
     foreach ($permissions as $perm) {
         if (!$perm) {
             $permissions_compat = false;
         }
     }
     $this->addToView('permissions_compat', $permissions_compat);
     $this->addToView('writable_data_directory', FileDataManager::getDataPath());
     // session save path permissions check
     $session_permissions_compat = $this->installer->isSessionDirectoryWritable();
     $this->addToView('session_permissions_compat', $session_permissions_compat);
     $this->addToView('writable_session_save_directory', ini_get('session.save_path'));
     // other vars set to view
     $requirements_met = $php_compat && $libs_compat && $permissions_compat && $session_permissions_compat;
     $this->addToView('requirements_met', $requirements_met);
     $this->addToView('subtitle', 'Check System Requirements');
     //If all requirements are met, go to step 2
     if ($requirements_met) {
         $this->addSuccessMessage("<strong>Great!</strong> Your system has everything it needs to run ThinkUp.", null, true);
         $this->step2();
     }
 }
 /**
  * Upgrade the application code to the latest version.
  * @throws Exception
  * @param bool $verify_updatable Whether or not to verify if installation is updatable, defaults to false
  * @return array Backup file information
  */
 public function runUpdate($file_path, $verify_updatable = false)
 {
     $app_dir = preg_replace("/\\/_lib\\/controller/", '', $file_path);
     // do we have the disk space we need?
     $disk_util = new AppUpgraderDiskUtil($app_dir);
     $disk_space_megs = $disk_util->getAvailableDiskSpace();
     // do we have the perms to do what we need?
     $disk_util->validateUpdatePermissions($app_dir);
     // do we need to update?
     $update_client = new AppUpgraderClient();
     $update_info = $update_client->getLatestVersionInfo();
     require dirname(__FILE__) . '/../../install/version.php';
     $version = Config::GetInstance()->getvalue('THINKUP_VERSION');
     if ($update_info['version'] < $version) {
         throw new Exception("You are running the latest version of ThinkUp.");
     }
     if ($verify_updatable == true) {
         return array('latest_version' => $update_info['version']);
     }
     // download zip...
     $update_zip_data = $update_client->getLatestVersionZip($update_info['url']);
     $update_zip = $disk_util->writeZip($update_zip_data);
     $zip = new ZipArchive();
     $open_result = $zip->open($update_zip);
     if ($open_result !== true) {
         unlink($update_zip);
         throw new Exception("Unable to extract " . $update_zip . ". ZipArchive::open failed with error code " . $open_result);
     }
     $num_files = $zip->numFiles;
     if ($num_files < 1) {
         unlink($update_zip);
         throw new Exception("Unable to extract " . $update_zip . ". ZipArchive->numFiles is " . $num_files);
     }
     $backup_file_info = array();
     $backup_file_info = $disk_util->backupInstall();
     $disk_util->deleteOldInstall();
     $data_path = FileDataManager::getDataPath();
     if ($zip->extractTo($data_path) !== true) {
         throw new Exception("Unable to extract new files into {$app_dir}: " . $zip->getStatusString());
     } else {
         $new_version_dir = $data_path . 'thinkup';
         $disk_util->recurseCopy($new_version_dir, $app_dir);
         // delete install files
         $disk_util->deleteDir($new_version_dir);
         unlink($update_zip);
     }
     //replace config file
     copy($backup_file_info['config'], "{$app_dir}/config.inc.php");
     return $backup_file_info;
 }
Exemplo n.º 20
0
 public function testNoTimezoneHandling()
 {
     $tz = date_default_timezone_get();
     unlink(FileDataManager::getDataPath(Mailer::EMAIL));
     $builders = array();
     $builders[] = FixtureBuilder::build('owners', array('id' => 1, 'full_name' => 'ThinkUp J. User', 'is_admin' => 1, 'email' => '*****@*****.**', 'is_activated' => 1, 'email_notification_frequency' => 'daily', 'timezone' => ''));
     $builders[] = FixtureBuilder::build('owner_instances', array('owner_id' => 1, 'instance_id' => 5, 'auth_error' => ''));
     $builders[] = FixtureBuilder::build('instances', array('network_username' => 'cdmoyer', 'id' => 5, 'network' => 'twitter', 'is_activated' => 1, 'is_public' => 1));
     $builders[] = FixtureBuilder::build('insights', array('id' => 1, 'instance_id' => 5, 'slug' => 'new_group_memberships', 'prefix' => 'Made the List:', 'text' => 'CDMoyer is on 29 new lists', 'time_generated' => date('Y-m-d 03:00:00')));
     $builders[] = FixtureBuilder::build('insights', array('id' => 2, 'instance_id' => 5, 'slug' => 'new_group_memberships', 'prefix' => 'Made the List:', 'text' => 'CDMoyer is on 99 new lists', 'time_generated' => date('Y-m-d 01:00:00')));
     $plugin_option_dao = DAOFactory::GetDAO('PluginOptionDAO');
     $options = $plugin_option_dao->getOptionsHash($plugin->folder_name, true);
     $this->assertEqual(count($options), 0);
     $config = Config::getInstance();
     date_default_timezone_set($config->getValue('timezone'));
     $this->simulateLogin('*****@*****.**');
     $plugin = new InsightsGeneratorPlugin();
     $plugin->current_timestamp = strtotime('3am');
     // Should not set yet
     $plugin->crawl();
     $sent = Mailer::getLastMail();
     $this->assertEqual('', $sent);
     $plugin_option_dao = DAOFactory::GetDAO('PluginOptionDAO');
     $options = $plugin_option_dao->getOptionsHash($plugin->folder_name, true);
     $this->assertEqual(count($options), 0);
     $plugin->current_timestamp = strtotime('5am');
     // SHould send
     $plugin->crawl();
     $sent = Mailer::getLastMail();
     $this->assertNotEqual('', $sent);
     $plugin_option_dao = DAOFactory::GetDAO('PluginOptionDAO');
     $options = $plugin_option_dao->getOptionsHash($plugin->folder_name, true);
     $this->assertTrue(count($options) > 0);
     date_default_timezone_set($tz);
 }
Exemplo n.º 21
0
 public function testExportToFile()
 {
     $posts_table_file = FileDataManager::getBackupPath('posts.tmp');
     $links_table_file = FileDataManager::getBackupPath('links.tmp');
     $users_table_file = FileDataManager::getBackupPath('users.tmp');
     if (file_exists($posts_table_file)) {
         unlink($posts_table_file);
     }
     if (file_exists($links_table_file)) {
         unlink($links_table_file);
     }
     if (file_exists($users_table_file)) {
         unlink($users_table_file);
     }
     $this->assertFalse(file_exists($posts_table_file));
     $this->assertFalse(file_exists($users_table_file));
     $this->assertFalse(file_exists($links_table_file));
     $this->dao->exportPostsLinksUsersToFile($posts_table_file, $links_table_file, $users_table_file);
     $this->assertTrue(file_exists($posts_table_file));
     $this->assertTrue(file_exists($users_table_file));
     $this->assertTrue(file_exists($links_table_file));
 }
 public function testMandrillHTMLWithExceptions()
 {
     unlink(FileDataManager::getDataPath(Mailer::EMAIL));
     $plugin = new InsightsGeneratorPlugin();
     $config = Config::getInstance();
     $config->setValue('mandrill_api_key', '1234');
     $plugin_dao = DAOFactory::getDAO('PluginDAO');
     $plugin_id = $plugin_dao->getPluginId($plugin->folder_name);
     $plugin_option_dao = DAOFactory::GetDAO('PluginOptionDAO');
     $plugin_option_dao->insertOption($plugin_id, 'mandrill_template', $template = 'my_template');
     $long_ago = date('Y-m-d', strtotime('last year'));
     // When in test mode, the mailHTMLViaMandrill method will throw a Template Not Found exception
     // if the email address contains "templateerror".
     $builders = array();
     $builders[] = FixtureBuilder::build('owners', array('id' => 1, 'full_name' => 'ThinkUp Q. User', 'is_admin' => 1, 'email' => '*****@*****.**', 'is_activated' => 1, 'email_notification_frequency' => 'daily'));
     $builders[] = FixtureBuilder::build('instances', array('network_username' => 'cdmoyer', 'id' => 6, 'network' => 'twitter', 'is_activated' => 1, 'is_public' => 1));
     $builders[] = FixtureBuilder::build('owner_instances', array('owner_id' => 1, 'instance_id' => 6, 'id' => 1));
     $builders[] = FixtureBuilder::build('insights', array('id' => 2, 'instance_id' => 6, 'slug' => 'new_group_memberships', 'prefix' => 'Made the List:', 'text' => 'Joe Test is on 1234 new lists', 'time_generated' => date('Y-m-d 03:00:00', strtotime('1am'))));
     $this->simulateLogin('*****@*****.**');
     $plugin->current_timestamp = strtotime('5pm');
     $exception = null;
     try {
         $plugin->crawl();
     } catch (Exception $e) {
         $exception = $e;
     }
     $this->assertNull($e, 'Should not get Mandrill template error');
     $sent = Mailer::getLastMail();
     //Sent plain text email
     $this->assertNotEqual($sent, '');
     $decoded = json_decode($sent);
     //Not HTML email via JSON
     $this->assertNull($decoded->global_merge_vars);
     //Check user got a log message
     $config = Config::getInstance();
     $logger_file = $config->getValue('log_location');
     $log = file($logger_file);
     $last_log = join("\n", array_slice($log, -10));
     $this->assertPattern('/invalid mandrill template/i', $last_log);
 }
 public function testFreshInstallStep1AllReqsMet()
 {
     self::time(__METHOD__);
     //get whatever session save path is set to
     $session_save_path = ini_get('session.save_path');
     ini_set('session.save_path', FileDataManager::getDataPath());
     //remove config file
     Config::destroyInstance();
     $this->removeConfigFile();
     //drop DB
     $this->testdb_helper->drop($this->test_database_name);
     $controller = new InstallerController(true);
     $this->assertTrue(isset($controller));
     $result = $controller->go();
     $this->debug($result);
     $this->assertPattern('/Your system has everything it needs to run ThinkUp./', $result);
     //make sure we've auto-progressed to step 2 b/c all requirements have been met
     $this->assertPattern('/Create your ThinkUp/', $result);
     $this->restoreConfigFile();
     //reset back to what it was
     ini_set('session.save_path', $session_save_path);
 }
 /**
  * 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);
         }
     }
 }
Exemplo n.º 25
0
 /**
  * Return the contents of the last email Mailer "sent" out.
  * For testing purposes only; this will return nothing in production.
  * @return str The contents of the last email sent
  */
 private static function setLastMail($message)
 {
     $test_email = FileDataManager::getDataPath(Mailer::EMAIL);
     $fp = fopen($test_email, 'w');
     fwrite($fp, $message);
     fclose($fp);
 }
 /**
  * Constructor
  * @param $app_dir str Application directory
  * @returns AppUpgraderDiskUtil
  */
 public function __construct($app_dir)
 {
     $this->app_dir = $app_dir;
     $this->app_version = Config::getInstance()->getValue('THINKUP_VERSION');
     $this->data_path = FileDataManager::getDataPath();
 }
Exemplo n.º 27
0
 /**
  * Preemptively halt test run if testing environment requirement isn't met.
  * Prevents unnecessary/inexplicable failures and data loss.
  */
 public static function isTestEnvironmentReady()
 {
     require THINKUP_WEBAPP_PATH . 'config.inc.php';
     $datadir_path = FileDataManager::getDataPath();
     if (!is_writable($datadir_path)) {
         $message = "In order to test your ThinkUp installation, {$datadir_path} must be writable.";
     }
     if (!is_writable($datadir_path . 'compiled_view/')) {
         try {
             @exec('cd ' . $datadir_path . '; rm -rf compiled_view');
         } catch (Exception $e) {
         }
     }
     if (!file_exists($datadir_path . 'compiled_view/')) {
         mkdir($datadir_path . 'compiled_view/');
         @exec('chmod -R 777 ' . $datadir_path . 'compiled_view/');
     }
     if (!is_writable($datadir_path . 'compiled_view/')) {
         $message = "In order to test your ThinkUp installation, " . $datadir_path . "compiled_view/ must be writable.";
     }
     if ($THINKUP_CFG['log_location'] === false) {
         $message = "In order to test your ThinkUp installation, \$THINKUP_CFG['log_location'] must be set to a " . "writable file.";
     } else {
         if (!self::isLogWritable($THINKUP_CFG['log_location'])) {
             $message = "In order to test your ThinkUp installation with your current settings, " . $THINKUP_CFG['log_location'] . " must be a writable file.";
         } else {
             if (file_exists($THINKUP_CFG['log_location']) && filesize($THINKUP_CFG['log_location']) > 10485760) {
                 $message = "Your crawler log file is so large it may cause a PHP Fatal error due to memory usage. " . "Please make " . $THINKUP_CFG['log_location'] . " less than 10MB in size and try again.";
             }
         }
     }
     if (!isset($THINKUP_CFG['stream_log_location']) || $THINKUP_CFG['stream_log_location'] === false) {
         $message = "In order to test your ThinkUp installation, \$THINKUP_CFG['stream_log_location'] must be set " . "to a writable file.";
     } else {
         if (!self::isLogWritable($THINKUP_CFG['stream_log_location'])) {
             $message = "In order to test your ThinkUp installation with your current settings, " . $THINKUP_CFG['stream_log_location'] . " must be a writable file.";
         } else {
             if (file_exists($THINKUP_CFG['stream_log_location']) && filesize($THINKUP_CFG['stream_log_location']) > 10485760) {
                 $message = "Your stream log file is so large it may cause a PHP Fatal error due to memory usage. " . "Please make " . $THINKUP_CFG['stream_log_location'] . " less than 10MB in size and try again.";
             }
         }
     }
     global $TEST_DATABASE;
     if (getenv("RD_MODE") == "1") {
         $TEST_DATABASE = $THINKUP_CFG['db_name'];
     }
     if ($THINKUP_CFG['db_name'] != $TEST_DATABASE) {
         $message = "The database name in webapp/config.inc.php does not match \$TEST_DATABASE in " . "tests/config.tests.inc.php.\nIn order to test your ThinkUp installation without losing data, these database names must both point to the same " . "empty test database.";
     }
     if ($THINKUP_CFG['cache_pages']) {
         $message = "In order to test your ThinkUp installation, \$THINKUP_CFG['cache_pages'] must be set to false.";
     }
     $cmd = "find . -type f -path '????????????????????????????????????????????????????????????????????????????????" . "?????????????????????????????????????????????????????????????????????????????????????????????????????????????" . "????????*'";
     @exec($cmd, $filenames, $return_val);
     if (is_array($filenames) && sizeof($filenames) > 1) {
         $message = "Filenames in the repository are greater than 200 characters in length:\n";
         foreach ($filenames as $filename) {
             $message .= $filename . "\n";
         }
     }
     if (isset($message)) {
         echo "Stopping tests...Test environment isn't ready.\n" . $message . "\nPlease try again.\n";
         exit(1);
     }
     $cmd = "find . -type f -name '*:*'";
     @exec($cmd, $filenames, $return_val);
     if (is_array($filenames) && sizeof($filenames) > 1) {
         $message = "Files in the repository have a colon in their names, an invalid character on Windows:\n";
         foreach ($filenames as $filename) {
             $message .= $filename . "\n";
         }
     }
     if (isset($message)) {
         echo "Stopping tests...Test environment isn't ready.\n" . $message . "\nPlease try again.\n";
         exit(1);
     }
 }
 public function testHandlingLastSentTime()
 {
     $tz = date_default_timezone_get();
     unlink(FileDataManager::getDataPath(Mailer::EMAIL));
     $builders = array();
     $builders[] = FixtureBuilder::build('owners', array('id' => 1, 'full_name' => 'ThinkUp J. User', 'is_admin' => 1, 'email' => '*****@*****.**', 'is_activated' => 1, 'email_notification_frequency' => 'daily', 'timezone' => 'America/New_York'));
     $builders[] = FixtureBuilder::build('owner_instances', array('owner_id' => 1, 'instance_id' => 5, 'auth_error' => ''));
     $builders[] = FixtureBuilder::build('instances', array('network_username' => 'cdmoyer', 'id' => 5, 'network' => 'twitter', 'is_activated' => 1, 'is_public' => 1));
     $builders[] = FixtureBuilder::build('insights', array('id' => 1, 'instance_id' => 5, 'slug' => 'new_group_memberships', 'headline' => 'Made the List:', 'related_data' => null, 'text' => 'CDMoyer is on 29 new lists', 'time_generated' => date('Y-m-d 4:00', strtotime('-49 hour'))));
     $builders[] = FixtureBuilder::build('insights', array('id' => 2, 'instance_id' => 5, 'slug' => 'new_group_memberships', 'headline' => 'Made the List:', 'related_data' => null, 'text' => 'CDMoyer is on 99 new lists', 'time_generated' => date('Y-m-d H:00:00', strtotime('-45 hour'))));
     $builders[] = FixtureBuilder::build('insights', array('id' => 3, 'instance_id' => 5, 'slug' => 'new_group_memberships', 'headline' => 'Made the List:', 'related_data' => null, 'text' => 'CDMoyer is on 42 new lists', 'time_generated' => date('Y-m-d H:00:00', strtotime('-42 hour'))));
     $plugin_option_dao = DAOFactory::GetDAO('PluginOptionDAO');
     $options = $plugin_option_dao->getOptionsHash($plugin->folder_name, true);
     $this->assertEqual(count($options), 0);
     $config = Config::getInstance();
     //date_default_timezone_set($config->getValue('timezone'));
     $this->simulateLogin('*****@*****.**');
     $plugin = new InsightsGeneratorPlugin();
     $plugin->current_timestamp = strtotime('Yesterday 4am');
     // Should send
     $plugin->crawl();
     $sent = Mailer::getLastMail();
     $this->assertNoPattern('/29 new lists/', $sent);
     unlink(FileDataManager::getDataPath(Mailer::EMAIL));
     $plugin->current_timestamp = strtotime('4am');
     // Should send
     $plugin_dao = DAOFactory::getDAO('PluginDAO');
     $plugin_id = $plugin_dao->getPluginId($plugin->folder_name);
     $options = $plugin_option_dao->getOptionsHash($plugin->folder_name, true);
     $plugin_option_dao->updateOption($options['last_daily_email']->id, 'last_daily_email', date('Y-m-d H:00:00', strtotime('-43 hour')));
     $options = $plugin_option_dao->getOptionsHash($plugin->folder_name, true);
     $plugin->crawl();
     $sent = Mailer::getLastMail();
     $this->assertNoPattern('/29 new lists/', $sent);
     $this->assertNoPattern('/99 new lists/', $sent);
     $this->assertPattern('/42 new lists/', $sent);
 }
Exemplo n.º 29
0
 /**
  * Override the parent's fetch method to handle an unwritable compilation directory.
  * @param str $template Template name
  * @param str $cache_key Cache key
  * @param str Results
  */
 public function fetch($template, $cache_key = null, $compile_id = null, $display = false)
 {
     $continue = false;
     if (is_writable(FileDataManager::getDataPath())) {
         if (!file_exists($this->compile_dir)) {
             if (mkdir($this->compile_dir, 0777)) {
                 $continue = true;
             }
         } else {
             $continue = true;
         }
     }
     if (is_writable($this->compile_dir)) {
         if ($this->caching == 1 && !file_exists($this->compile_dir . '/cache')) {
             if (mkdir($this->compile_dir . '/cache/', 0777)) {
                 $continue = true;
             }
         } else {
             $continue = true;
         }
     }
     if ($continue) {
         return parent::fetch($template, $cache_key, $compile_id, $display);
     } else {
         Loader::definePathConstants();
         $whoami = @exec('whoami');
         if (empty($whoami)) {
             $whoami = 'nobody';
         }
         return str_replace(array('#THINKUP_BASE_URL#', '#WHOAMI#', '#COMPILE_DIR#'), array(Utils::getSiteRootPathFromFileSystem(), $whoami, FileDataManager::getDataPath()), file_get_contents(THINKUP_WEBAPP_PATH . '_lib/view/500-perm.html'));
     }
 }
 public function testUpdate()
 {
     $upgrade_controller = new UpgradeApplicationController(true);
     $valid_url = AppUpgraderClient::$UPDATE_URL;
     error_reporting(E_ERROR | E_USER_ERROR);
     // turn off warning messages
     $config = Config::getInstance();
     $proper_version = $config->getValue('THINKUP_VERSION');
     $config->setValue('THINKUP_VERSION', 1.0);
     //set a low version num
     // delete index.pho
     $this->assertTrue(unlink($this->test_web_dir . '/index.php'));
     // create a file in out data dir
     touch($this->test_web_dir . '/data/dont_delete_me');
     AppUpgraderClient::$UPDATE_URL = $this->test_web_dir . '/data/valid_json';
     file_put_contents(AppUpgraderClient::$UPDATE_URL, '{"version":"100.1", "url":"' . THINKUP_WEBAPP_PATH . 'test_installer/thinkup.zip"}');
     $update_info = $upgrade_controller->runUpdate($this->test_web_dir);
     $this->assertPattern('/data\\/\\d+\\-v1\\-config\\.inc\\.backup\\.php/', $update_info['config']);
     $this->assertPattern('/data\\/\\d+\\-v1\\-backup\\.zip/', $update_info['backup']);
     $this->assertTrue(file_exists($this->test_web_dir . '/index.php'), "we should have our index file back");
     $data_path = FileDataManager::getDataPath();
     $this->assertFalse(is_dir($data_path . '/data/thinkup'), "our unzipped update deleted");
     $this->assertTrue(file_exists($this->test_web_dir . '/data/dont_delete_me'), "/data/* not deleted");
     unlink(AppUpgraderClient::$UPDATE_URL);
     // reset
     AppUpgraderClient::$UPDATE_URL = $valid_url;
     error_reporting(E_STRICT);
     // reset error reporting
     $config->setValue('THINKUP_VERSION', $proper_version);
 }