Exemplo n.º 1
0
 public function upload()
 {
     $app = App::getInstance();
     $user_id = SessionManager::getInstance()->getUserID();
     if (!empty($_FILES['file']['name'])) {
         $filename = $_FILES['file']['name'];
         $file = sprintf("%s/%s", PathUtils::getTmpDir('tmp/uploads'), $filename);
         $saved = move_uploaded_file($_FILES['file']['tmp_name'], $file);
     } elseif (!empty($_POST['file']) && !empty($_POST['data'])) {
         $filename = $_POST['file'];
         $file = sprintf("%s/%s", PathUtils::getTmpDir('tmp/uploads'), $filename);
         $data = !empty($_POST['base64']) ? base64_decode($_POST['data']) : $_POST['data'];
         $saved = file_put_contents($file, $data);
     }
     if (!empty($file) & !empty($saved)) {
         try {
             $type = PathUtils::getFileType($file);
             $event = new UploadEvent($user_id, ['file' => $file]);
             if ($app->dispatch("user_upload_{$type}", $event)) {
                 if ($upload = $event->getURL()) {
                     HttpResponse::getInstance()->display(['url' => $upload], '', true);
                 }
             }
         } finally {
             @unlink($file);
         }
     }
     HttpResponse::getInstance()->displayError("Unable to upload file");
 }
Exemplo n.º 2
0
 public function videoPass(Swf2VidEvent $event)
 {
     /** @var Video $video */
     if ($data = $event->getEventData()) {
         if ($video = @Video::find($data['video']['video_id'])) {
             if ($user = $event->getUser()) {
                 if (Video::count(['conditions' => ['project_id = ? and vid_status = "pass" and updated_at > DATE_SUB(NOW(), INTERVAL 10 MINUTE)', $video->project_id]])) {
                     //redo
                     return;
                 }
                 $minLevel = Swf2Vid::getInstance()->getUserVideoLevel();
                 $levels = $user->user_level;
                 /** @var UserLevel $level */
                 foreach ($levels as $level) {
                     if ($level->credits > 0) {
                         if (AccessLevels::getInstance()->checkAccess($level->level, $minLevel)) {
                             $level->credits = $level->credits - 1;
                             $level->save_direct();
                             return;
                         }
                     }
                 }
             }
             $video->vid_status = 'fail';
             $video->save_direct();
         }
         App::getInstance()->dispatch(Swf2VidEvent::VIDEO_NO_CREDITS, $event);
     }
 }
Exemplo n.º 3
0
 public static function getBucket($dir, $ext = '*')
 {
     $app = App::getInstance();
     $results = [];
     if ($s3conf = $app->config->getKey(self::stockUtilsKey)) {
         if (!empty($s3conf['access_key']) && !empty($s3conf['secret_key']) && !empty($s3conf['bucket_name'])) {
             try {
                 if ($s3 = S3Client::factory(array('key' => $s3conf['access_key'], 'secret' => $s3conf['secret_key'], 'region' => @$s3conf['region'] ?: Region::US_EAST_1))) {
                     if ($objects = $s3->getListObjectsIterator(['Bucket' => $s3conf['bucket_name'], 'Prefix' => sprintf('bgtracks/%s/', rtrim($dir, '/'))])) {
                         foreach ($objects as $object) {
                             $fn = $object['Key'];
                             $name = basename($fn);
                             if (empty($ext) || preg_match("/\\.({$ext})\$/", $name)) {
                                 $host = !empty($s3conf['cdn']) ? $s3conf['cdn'] : sprintf('%s.s3.amazonaws.com', $s3conf['bucket_name']);
                                 $result = ['name' => self::fix_name(pathinfo($name, PATHINFO_FILENAME)), 'url' => sprintf('http://%s/%s', $host, $fn)];
                                 if (preg_match("!{$dir}/(\\w+)!", dirname($fn), $matches)) {
                                     $results[$matches[1]][] = $result;
                                 } else {
                                     $results[] = $result;
                                 }
                             }
                         }
                     }
                 }
             } catch (Exception $e) {
                 throw new BgtracksError("Error connecting to S3: " . $e->getMessage(), $e);
             }
         }
     }
     return $results;
 }
Exemplo n.º 4
0
 private function go($name, $thumb = false)
 {
     if ($s3conf = App::getInstance()->config->getKey(S3Utils::stockUtilsKey)) {
         $host = !empty($s3conf['cdn']) ? $s3conf['cdn'] : sprintf('%s.s3.amazonaws.com', $s3conf['bucket_name']);
         $url = sprintf('http://%s/bgtracks/fonts/%s%s.%s', $host, !empty($thumb) ? 'thumbs/' : '', $name, !empty($thumb) ? 'png' : 'swf');
         HttpResponse::getInstance()->redirect($url);
     }
 }
Exemplo n.º 5
0
 public function index($param1)
 {
     $config = App::getInstance()->config;
     if ($s3conf = $config->getKey(S3Utils::stockUtilsKey)) {
         $host = @(!empty($s3conf['cdn']) ? $s3conf['cdn'] : sprintf('%s.s3.amazonaws.com', $s3conf['bucket_name'] ?: 'stockutils'));
         $url = sprintf('http%s://%s/bgtracks/%s', $config->getKey('private/prefer_https') ? 's' : '', $host, $param1);
         HttpResponse::getInstance()->redirect($url);
     }
 }
Exemplo n.º 6
0
 public function index($project_id)
 {
     $host = App::getInstance()->getSelfHost();
     $data = ['converter_url' => sprintf('%s/static/local/swf/converter/converter.swf', $host), 'player_url' => sprintf('%s/static/local/swf/player/player.swf', $host, $project_id), 'project_url' => sprintf('%s/members/projects/data/%d', $host, $project_id)];
     if (@$_GET['html'] == '0') {
         $url = sprintf('%s?%s', $data['converter_url'], http_build_query(array_intersect_key($data, array_flip(['player_url', 'project_url']))));
         HttpResponse::getInstance()->redirect($url);
     }
     View::forgeWithoutLayout('Swf2Vid/FlashPlayer.php', $data);
 }
Exemplo n.º 7
0
 public function healthCheck()
 {
     foreach (['pending', 'processing'] as $type) {
         if ($videos = Swf2Vid::getInstance()->getVideosByType($type, null, '1 HOUR')) {
             if (count($videos) > 20) {
                 App::getInstance()->alert("More than 20 {$type} videos before last 1 hour!");
             }
         }
     }
 }
Exemplo n.º 8
0
 /**
  * @param array $videos
  * @param string $vid_status
  * @param string $vid_url
  */
 public function index($video, $vid_status, $vid_url)
 {
     /** @var Video $video */
     if (!empty($video) && !empty($vid_status)) {
         $video->set_attributes(['vid_status' => $vid_status, 'vid_url' => !empty($vid_url) ? preg_replace('~^s3://~', 'https://s3.amazonaws.com/', $vid_url) : null]);
         $video->save_direct();
         $eventName = $vid_status == 'pass' ? Swf2VidEvent::VIDEO_PASS : Swf2VidEvent::VIDEO_FAIL;
         App::getInstance()->dispatch($eventName, new Swf2VidEvent($video->user_id, ['video' => $video->to_hash()]));
     }
     exit('OK');
 }
Exemplo n.º 9
0
 public function addInstance($urgent)
 {
     $key = sprintf("site/instances/lastQueued%s", $urgent ? 'Reserved' : 'Spot');
     $config = App::getInstance()->config;
     if (time() - $config->getKey($key, 0) > 60 * self::minTime) {
         if ($newInstance = $urgent ? $this->addReservedInstance() : $this->addSpotInstance()) {
             $config->setKey($key, time(), true);
             return $newInstance;
         }
     }
     return false;
 }
Exemplo n.º 10
0
 /**
  * @param ActiveModel $project
  */
 public function index($project)
 {
     $ytConfig = App::getInstance()->config->getKey(YouTubeWrapper::youtubeKey);
     $settings = ['api_key' => $ytConfig['api_key'], 'title' => $project->title];
     if ($project->public != 'y') {
         $scope['hidden'] = true;
         if ($project->user_id != SessionManager::getInstance()->getUserID()) {
             $project = [];
             $settings['private'] = true;
         }
     }
     View::forge('ActiveTheme/StockVideoPage.php', ['settings' => json_encode($settings)], $project);
 }
Exemplo n.º 11
0
 public function upload(UploadEvent $event)
 {
     set_time_limit(max(100, ini_get('max_execution_time')));
     if (!$event->getUrl()) {
         #some other uploader has already taken care of it?
         if ($data = $event->getEventData()) {
             if ($file = @$data['file']) {
                 if (file_exists($file)) {
                     $app = App::getInstance();
                     $user_id = $event->getUserId();
                     if ($s3conf = $app->config->getKey('private/api_keys/aws-s3')) {
                         if (!empty($s3conf['access_key']) && !empty($s3conf['secret_key']) && !empty($s3conf['bucket_name'])) {
                             if ($user_id > 0 || !empty($s3conf['anonymous_uploads'])) {
                                 try {
                                     $s3 = S3Client::factory(array('key' => $s3conf['access_key'], 'secret' => $s3conf['secret_key'], 'region' => @$s3conf['region'] ?: Region::US_EAST_1));
                                     $type = PathUtils::getFileType($file);
                                     $file_key = sprintf("users/%s/%s/%d-%s", $user_id > 0 ? $user_id : 'anon', $type, filesize($file), basename($file));
                                     $result = $s3->putObject(array('Bucket' => $s3conf['bucket_name'], 'SourceFile' => $file, 'Key' => $file_key, 'ContentType' => 'text/plain', 'ACL' => 'public-read', 'StorageClass' => 'REDUCED_REDUNDANCY'));
                                     if (!empty($result['ObjectURL'])) {
                                         $url = $result['ObjectURL'];
                                         if (!empty($s3conf['cdn'])) {
                                             $event->setUrl(sprintf('http://%s/%s', $s3conf['cdn'], $file_key));
                                         } else {
                                             $event->setUrl($url);
                                         }
                                     } else {
                                         throw new UploadError("Error uploading to S3: No url returned");
                                     }
                                 } catch (Exception $e) {
                                     throw new UploadError("Error uploading to S3: " . $e->getMessage(), $e);
                                 }
                             } else {
                                 throw new LoginError("You must be logged in to upload.", $user_id);
                             }
                         } else {
                             throw new UploadError("S3 configuration is incomplete.", $s3conf);
                         }
                     } else {
                         throw new UploadError("S3 configuration is empty");
                     }
                 } else {
                     throw new UploadError("Upload file is missing");
                 }
             } else {
                 throw new UploadError("Upload data is empty");
             }
         }
     }
 }
Exemplo n.º 12
0
 public function upload($video)
 {
     if (!empty($video['url'])) {
         $ytWrapper = YouTubeWrapper::getInstance();
         if ($user_id = SessionManager::getInstance()->getUserID()) {
             if ($url = $ytWrapper->uploadS3URL($user_id, $video['url'], 'public', $video['title'], $video['description'], $video['category'], $video['keywords'])) {
                 App::getInstance()->dispatch(Swf2VidEvent::USER_UPLOAD_VIDEO, new UserEvent($user_id, array_merge($video, ['upload_url' => $url])));
                 HttpResponse::getInstance()->display(['url' => $url], '', true);
             }
         }
     } else {
         throw new UploadError("Video url cannot be empty");
     }
     throw new UploadError("Unable to upload at this time, sorry.");
 }
Exemplo n.º 13
0
 public function index($urls)
 {
     if ($files = HttpProxy::getInstance()->proxy($urls)) {
         $app = App::getInstance();
         $user_id = SessionManager::getInstance()->getUserID();
         foreach ($files as $file) {
             $event = new UploadEvent($user_id, ['file' => $file['local']]);
             if ($app->dispatch(UploadEvent::USER_UPLOAD_IMAGE, $event)) {
                 if ($upload = $event->getURL()) {
                     $results[] = ['src' => $file['remote'], 'copy' => $upload];
                 }
             }
         }
     }
     HttpResponse::getInstance()->display(!empty($results) ? $results : '');
 }
Exemplo n.º 14
0
 public function index($urls, $width, $height)
 {
     if ($images = HttpProxy::getInstance()->proxy($urls)) {
         $app = App::getInstance();
         $user_id = SessionManager::getInstance()->getUserID();
         foreach ($images as $image) {
             $resized = self::resize_image($image['local'], $width ?: 854, $height ?: 480);
             $event = new UploadEvent($user_id, ['file' => $resized]);
             if ($app->dispatch(UploadEvent::USER_UPLOAD_IMAGE, $event)) {
                 if ($upload = $event->getURL()) {
                     $results[] = ['src' => $image['remote'], 'copy' => $upload];
                 }
             }
         }
     }
     HttpResponse::getInstance()->display(!empty($results) ? $results : '');
 }
Exemplo n.º 15
0
 public function save($fn)
 {
     $app = App::getInstance();
     $content = file_get_contents('php://input');
     //$file_path = sprintf("%s/%s.wav", PathUtils::getTmpDir('tmp/recordings'), $fn);
     $wav = sprintf("E:/var/Dropbox/www/viralvideorobot/public/tmp/%s.wav", $fn);
     if (file_put_contents($wav, $content)) {
         $mp3 = preg_replace('/(\\.wav)$/', '.mp3', $wav);
         system(sprintf('ffmpeg -y -i "%s" -qscale:a 2 "%s"', $wav, $mp3));
         if (file_exists($mp3)) {
             $output = basename($mp3);
             unlink($wav);
         } else {
             $output = basename($wav);
         }
         echo json_encode(['filename' => "/tmp/{$output}"]);
         exit;
     }
     HttpResponse::getInstance()->displayError("Content not found");
 }
Exemplo n.º 16
0
 /**
  * @param ActiveModel $cron_jobs
  */
 public function index($cron_jobs)
 {
     $lastRun = time() - App::getInstance()->config->getKey('site/cron/lastrun', 0);
     View::forge('Admin/ListView/ViewCronJobs.php', $cron_jobs, array('lastRun' => $lastRun, 'base' => addslashes(StringUtils::unixPath(BASE_DIR))));
 }
Exemplo n.º 17
0
 function __construct()
 {
     $this->app = App::getInstance();
 }
Exemplo n.º 18
0
 private function getDefaultProjectURL($project_id)
 {
     return sprintf('%s/members/projects/data/%d', App::getInstance()->getSelfHost(), $project_id ?: 6);
 }
Exemplo n.º 19
0
 private function uploadVideo($file, $token, &$refreshToken, $videoPrivacy = 'unlisted', $videoTitle = '', $videoDescription = '', $videoCategory = '', $videoTags = [])
 {
     $app = App::getInstance();
     $youtubeConfig = $app->config->getKey('private/api_keys/youtube');
     $application_name = $youtubeConfig['application_name'];
     $client_secret = $youtubeConfig['client_secret'];
     $client_id = $youtubeConfig['client_id'];
     $scope = array('https://www.googleapis.com/auth/youtube.upload', 'https://www.googleapis.com/auth/youtube', 'https://www.googleapis.com/auth/youtubepartner');
     $videoPath = $file;
     $videoTitle = $videoTitle ?: basename($file);
     $videoDescription = $videoDescription ?: "Private video";
     $videoCategory = $videoCategory ?: "22";
     $videoTags = !empty($videoTags) ? $videoTags : array("youtube", "video", basename($file));
     try {
         // Client init
         $client = new Google_Client();
         $client->setApplicationName($application_name);
         $client->setClientId($client_id);
         $client->setAccessType('offline');
         $client->setAccessToken($token);
         $client->setScopes($scope);
         $client->setClientSecret($client_secret);
         if ($client->getAccessToken()) {
             /**
              * Check to see if our access token has expired. If so, get a new one and save it to file for future use.
              */
             if ($client->isAccessTokenExpired()) {
                 $newToken = json_decode($client->getAccessToken());
                 $client->refreshToken($newToken->refresh_token);
                 $refreshToken = $client->getAccessToken();
             }
             $youtube = new Google_Service_YouTube($client);
             // Create a snipet with title, description, tags and category id
             $snippet = new Google_Service_YouTube_VideoSnippet();
             $snippet->setTitle($videoTitle);
             $snippet->setDescription($videoDescription);
             $snippet->setCategoryId($videoCategory);
             $snippet->setTags($videoTags);
             // Create a video status with privacy status. Options are "public", "private" and "unlisted".
             $status = new Google_Service_YouTube_VideoStatus();
             $status->setPrivacyStatus($videoPrivacy);
             // Create a YouTube video with snippet and status
             $video = new Google_Service_YouTube_Video();
             $video->setSnippet($snippet);
             $video->setStatus($status);
             // Size of each chunk of data in bytes. Setting it higher leads faster upload (less chunks,
             // for reliable connections). Setting it lower leads better recovery (fine-grained chunks)
             $chunkSizeBytes = 1 * 1024 * 1024;
             // Setting the defer flag to true tells the client to return a request which can be called
             // with ->execute(); instead of making the API call immediately.
             $client->setDefer(true);
             // Create a request for the API's videos.insert method to create and upload the video.
             $insertRequest = $youtube->videos->insert("status,snippet", $video);
             // Create a MediaFileUpload object for resumable uploads.
             $media = new Google_Http_MediaFileUpload($client, $insertRequest, 'video/*', null, true, $chunkSizeBytes);
             $media->setFileSize(filesize($videoPath));
             // Read the media file and upload it chunk by chunk.
             $status = false;
             $handle = fopen($videoPath, "rb");
             while (!$status && !feof($handle)) {
                 $chunk = fread($handle, $chunkSizeBytes);
                 $status = $media->nextChunk($chunk);
             }
             fclose($handle);
             // If you want to make other calls after the file upload, set setDefer back to false
             $client->setDefer(false);
             /**
              * Video has successfully been upload, now lets perform some cleanup functions for this video
              */
             if (!empty($status->status) && $status->status['uploadStatus'] == 'uploaded') {
                 return sprintf("http://www.youtube.com/watch?v=%s", $status['id']);
             }
         } else {
             throw new UploadError("Problems uploading video on YouTube");
         }
     } catch (Google_Service_Exception $e) {
         throw new UploadError("Youtube error: " . $e->getMessage());
     } catch (Exception $e) {
         throw new UploadError("Upload error: " . $e->getMessage());
     }
     return null;
 }
Exemplo n.º 20
0
 public function queueEmails()
 {
     ArCampaign::$has_many = [['messages', 'foreign_key' => 'ar_campaign_id', 'class_name' => 'ArMessage', 'order' => 'sequence asc']];
     if ($autoresponders = ArCampaign::find_all_by_enabled('y')) {
         $lists = Lists::getInstance();
         $ext_mail_id = function ($msg) {
             return $msg->mail_id ?: 0;
         };
         foreach ($autoresponders as $autoresponder_id => $autoresponder) {
             if ($messages = $autoresponder->messages) {
                 $mails = $mail_ids = [];
                 foreach ($messages as $message) {
                     if ($mail_id = $message->mail_id) {
                         $mails[$mail_id] = $message;
                         $mail_ids[] = $mail_id;
                     }
                 }
                 if ($user_ids = $lists->getTargetUserIds($autoresponder->ar_list_id)) {
                     $count = 0;
                     printf("Found %d users in list: {$autoresponder->ar_list_id}\n", count($user_ids));
                     $sql = sprintf('SELECT user_id, MAX(sent_at) AS last_sent, COUNT(user_id) AS total_sent FROM ar_history WHERE user_id IN (%s) AND mail_id IN (%s) ' . 'GROUP BY user_id HAVING ((total_sent = %d) OR (last_sent > DATE_SUB(NOW(), INTERVAL 1 DAY)))', join(',', $user_ids), join(',', $mail_ids), count($messages));
                     if ($recent_or_full = User::find_by_sql($sql)) {
                         # find all users that have been sent all messages |OR| last mail sent is within 1 day
                         foreach ($recent_or_full as $i_user) {
                             $ignored_user_ids[$i_user->user_id] = 1;
                         }
                     }
                     if ($send_to = !empty($ignored_user_ids) ? array_diff($user_ids, array_keys($ignored_user_ids)) : $user_ids) {
                         foreach ($send_to as $user_id) {
                             $days_since_last_email = 1000;
                             if ($messages_sent = ArHistory::find_all_by_user_id($user_id, ['select' => 'mail_id, sent_at', 'order' => 'sent_at ASC', 'limit' => count($messages)])) {
                                 $message_sent_ids = array_map($ext_mail_id, $messages_sent);
                                 if ($last_sent = end($messages_sent)) {
                                     $days_since_last_email = floor(max(0, time() - $last_sent->sent_at->getTimestamp()) / 86400);
                                 }
                             }
                             if ($messages_remaining = !empty($message_sent_ids) ? array_diff($mail_ids, $message_sent_ids) : $mail_ids) {
                                 if ($mail_id_to_send = array_shift($messages_remaining)) {
                                     try {
                                         $wait_days = !empty($message_sent_ids) && !empty($mails[$mail_id_to_send]) ? $mails[$mail_id_to_send]->wait : 0;
                                         if ($days_since_last_email >= $wait_days) {
                                             $send_at = new DateTime();
                                             if ($schedule = $autoresponder->schedule) {
                                                 if ($ranges = json_decode($schedule, true)) {
                                                     $user = User::find_cached($user_id);
                                                     $timezone = !empty($user->tz_offset) ? timezone_name_from_abbr("", $user->tz_offset * -60, 0) : date_default_timezone_get();
                                                     $send_at = $this->getQueueDate($ranges, $timezone) ?: $send_at;
                                                 }
                                             }
                                             $sent_at = $send_at->format(Connection::$datetime_format);
                                             if (ArHistory::create_direct(['user_id' => $user_id, 'mail_id' => $mail_id_to_send, 'sent_at' => $sent_at])) {
                                                 $now = new DateTime();
                                                 $count = $count + 1;
                                                 if ($send_at > $now) {
                                                     echo "Queued mail_id #{$mail_id_to_send} for user_id #{$user_id} at {$sent_at}\n";
                                                     ArQueue::create_direct(['send_at' => $sent_at, 'user_id' => $user_id, 'mail_id' => $mail_id_to_send, 'status' => 'pending']);
                                                 } else {
                                                     echo "Sending mail_id #{$mail_id_to_send} to user_id #{$user_id} right now\n";
                                                     SendMail::getInstance()->send($mail_id_to_send, $user_id);
                                                 }
                                             }
                                         }
                                     } catch (Exception $e) {
                                         App::getInstance()->warn("Unable to send mail: " . $e->getMessage());
                                     }
                                 }
                             }
                         }
                     }
                     print "{$count} mails sent\n";
                 }
             }
         }
     }
 }
Exemplo n.º 21
0
 /**
  * @return mixed
  * @throws \Minute\Errors\ConfigError
  */
 public function getUserVideoLevel()
 {
     return App::getInstance()->config->getKey(Swf2Vid::swf2vidKey . '/video-level', SessionManager::getInstance()->getMinPaidLevel());
 }