示例#1
0
 public static function processAvatar($model, $source, $type = "artist")
 {
     try {
         $fileSystem = new Filesystem();
         $alowSize = Yii::app()->params['imageSize'];
         $maxSize = max($alowSize);
         $folderMax = "s0";
         foreach ($alowSize as $folder => $size) {
             // Create folder by ID
             $fileSystem->mkdirs($model->getAvatarPath($model->id, $folder, true));
             @chmod($model->getAvatarPath($model->id, $folder, true), 0755);
             // Get link file by ID
             $savePath[$folder] = $model->getAvatarPath($model->id, $folder);
             if ($size == $maxSize) {
                 $folderMax = $folder;
             }
         }
         // Delete file if exists
         if (file_exists($savePath[$folder])) {
             $fileSystem->remove($savePath);
         }
         if (file_exists($source)) {
             list($width, $height) = getimagesize($source);
             $imgCrop = new ImageCrop($source, 0, 0, $width, $height);
             // aspect ratio for image size
             $aspectRatioW = $aspectRatioH = 1;
             if ($type == "video") {
                 $videoAspectRatio = Yii::app()->params['videoResolutionRate'];
                 list($aspectRatioW, $aspectRatioH) = explode(":", $videoAspectRatio);
             }
             $res = array();
             foreach ($savePath as $k => $v) {
                 $desWidth = $alowSize[$k];
                 $desHeight = round($alowSize[$k] * intval($aspectRatioH) / intval($aspectRatioW));
                 if (file_exists($v) && is_file($v)) {
                     @unlink($v);
                 }
                 if ($width > 4000) {
                     self::ImageCropPro($v, $source, $desWidth, $desHeight, 70);
                 } else {
                     if ($k == $folderMax) {
                         $imgCrop->resizeRatio($v, $desWidth, $desHeight, 70);
                     } else {
                         $imgCrop->resizeCrop($v, $desWidth, $desHeight, 70);
                     }
                 }
             }
             if ($type != "video") {
                 $fileSystem->remove($source);
             }
         }
     } catch (Exception $e) {
         $error = $e->getMessage();
     }
 }
示例#2
0
 function testRemove()
 {
     $dir = PhutilDirectoryFixture::newEmptyFixture();
     $root = realpath($dir->getPath());
     mkdir("{$root}/one");
     touch("{$root}/one/onefile");
     mkdir("{$root}/one/two");
     touch("{$root}/one/two/twofile");
     touch("{$root}/top");
     $this->watch($root);
     $this->assertFileList($root, array('one', 'one/onefile', 'one/two', 'one/two/twofile', 'top'));
     $this->watchmanCommand('log', 'debug', 'XXX: remove dir one');
     Filesystem::remove("{$root}/one");
     $this->assertFileList($root, array('top'));
     $this->watchmanCommand('log', 'debug', 'XXX: touch file one');
     touch("{$root}/one");
     $this->assertFileList($root, array('one', 'top'));
     $this->watchmanCommand('log', 'debug', 'XXX: unlink file one');
     unlink("{$root}/one");
     $this->assertFileList($root, array('top'));
     system("rm -rf {$root} ; mkdir -p {$root}/notme");
     if (PHP_OS == 'Linux' && getenv('TRAVIS')) {
         $this->assertSkipped('openvz and inotify unlinks == bad time');
     }
     $watches = $this->waitForWatchman(array('watch-list'), function ($list) use($root) {
         return !in_array($root, $list['roots']);
     });
     $this->assertEqual(false, in_array($root, $watches['roots']), "watch deleted");
 }
 protected function deleteDocumentsByHash(array $hashes)
 {
     $root = $this->getConfig('root');
     $cache = $this->getPublishCache();
     foreach ($hashes as $hash) {
         $paths = $cache->getAtomPathsFromCache($hash);
         foreach ($paths as $path) {
             $abs = $root . DIRECTORY_SEPARATOR . $path;
             Filesystem::remove($abs);
             // If the parent directory is now empty, clean it up.
             $dir = dirname($abs);
             while (true) {
                 if (!Filesystem::isDescendant($dir, $root)) {
                     // Directory is outside of the root.
                     break;
                 }
                 if (Filesystem::listDirectory($dir)) {
                     // Directory is not empty.
                     break;
                 }
                 Filesystem::remove($dir);
                 $dir = dirname($dir);
             }
         }
         $cache->removeAtomPathsFromCache($hash);
         $cache->deleteAtomFromIndex($hash);
     }
 }
 /**
  * Deletes the file from local disk, if it exists.
  * @task impl
  */
 public function deleteFile($handle)
 {
     $path = $this->getLocalDiskFileStorageFullPath($handle);
     if (Filesystem::pathExists($path)) {
         Filesystem::remove($path);
     }
 }
 /**
  * Launch an editor and edit the content. The edited content will be
  * returned.
  *
  * @return string    Edited content.
  * @throws Exception The editor exited abnormally or something untoward
  *                   occurred.
  *
  * @task edit
  */
 public function editInteractively()
 {
     $name = $this->getName();
     $content = $this->getContent();
     if (phutil_is_windows()) {
         $content = str_replace("\n", "\r\n", $content);
     }
     $tmp = Filesystem::createTemporaryDirectory('edit.');
     $path = $tmp . DIRECTORY_SEPARATOR . $name;
     try {
         Filesystem::writeFile($path, $content);
     } catch (Exception $ex) {
         Filesystem::remove($tmp);
         throw $ex;
     }
     $editor = $this->getEditor();
     $offset = $this->getLineOffset();
     $err = $this->invokeEditor($editor, $path, $offset);
     if ($err) {
         Filesystem::remove($tmp);
         throw new Exception("Editor exited with an error code (#{$err}).");
     }
     try {
         $result = Filesystem::readFile($path);
         Filesystem::remove($tmp);
     } catch (Exception $ex) {
         Filesystem::remove($tmp);
         throw $ex;
     }
     if (phutil_is_windows()) {
         $result = str_replace("\r\n", "\n", $result);
     }
     $this->setContent($result);
     return $this->getContent();
 }
 protected function deleteTmpDir($testCase)
 {
     if (!file_exists($dir = sys_get_temp_dir() . '/' . Kernel::VERSION . '/' . $testCase)) {
         return;
     }
     $fs = new Filesystem();
     $fs->remove($dir);
 }
 /**
  * Deletes the file from local disk, if it exists.
  * @task impl
  */
 public function deleteFile($handle)
 {
     $path = $this->getLocalDiskFileStorageFullPath($handle);
     if (Filesystem::pathExists($path)) {
         AphrontWriteGuard::willWrite();
         Filesystem::remove($path);
     }
 }
示例#8
0
 public function __destruct()
 {
     Filesystem::remove($this->dir);
     // Note that the function tempnam() doesn't guarantee it will return a
     // file inside the dir you passed to the function.
     if (file_exists($this->file)) {
         unlink($this->file);
     }
 }
示例#9
0
 public static function processAvatar($id, $source, $type = "blog")
 {
     $fileSystem = new Filesystem();
     $alowSize = Yii::app()->params['imageSize']["{$type}"];
     $maxSize = max($alowSize);
     $folderMax = "s0";
     $pathDir = Yii::app()->params[$type . '_path'];
     foreach ($alowSize as $folder => $size) {
         // Create folder by ID
         $avatarPath = self::getAvatarPath($id, $folder, true, $pathDir);
         $fileSystem->mkdirs($avatarPath);
         @chmod($avatarPath, 0777);
         // Get link file by ID
         $savePath[$folder] = self::getAvatarPath($id, $folder, false, $pathDir);
         if ($size == $maxSize) {
             $folderMax = $folder;
         }
     }
     // Delete file if exists
     if (file_exists($savePath[$folder])) {
         $fileSystem->remove($savePath);
     }
     if (file_exists($source)) {
         list($width, $height) = getimagesize($source);
         $imgCrop = new ImageCrop($source, 0, 0, $width, $height);
         // aspect ratio for image size
         $aspectRatioW = $aspectRatioH = 1;
         foreach ($savePath as $k => $v) {
             $desWidth = $alowSize[$k];
             $desHeight = round($alowSize[$k] * intval($aspectRatioH) / intval($aspectRatioW));
             if (file_exists($v) && is_file($v)) {
                 @unlink($v);
             }
             if ($k == $folderMax) {
                 $imgCrop->resizeRatio($v, $desWidth, $desHeight, 100);
             } else {
                 $imgCrop->resizeCrop($v, $desWidth, $desHeight, 100);
             }
         }
         //remove file source
         $fileSystem->remove($source);
     }
 }
示例#10
0
 /**
  * When the object is destroyed, it destroys the temporary file. You can
  * change this behavior with @{method:setPreserveFile}.
  *
  * @task internal
  */
 public function __destruct()
 {
     if ($this->preserve) {
         return;
     }
     Filesystem::remove($this->dir);
     // NOTE: tempnam() doesn't guarantee it will return a file inside the
     // directory you passed to the function, so we make sure to nuke the file
     // explicitly.
     Filesystem::remove($this->file);
 }
 public function test_symlink_removal()
 {
     $test_dir = 'tests/test-data/symlinks';
     $test_link = $test_dir . '/points_nowhere';
     if (is_dir($test_dir)) {
         $this->rmdir_recursive($test_dir);
     }
     mkdir($test_dir);
     symlink("does_not_exist", $test_link);
     $fs = new Filesystem();
     $fs->remove($test_dir);
     $this->assertFalse(is_link($test_link) || is_file($test_link));
 }
示例#12
0
function cleanup($sig = '?')
{
    global $g_pidfile;
    if ($g_pidfile) {
        Filesystem::remove($g_pidfile);
        $g_pidfile = null;
    }
    global $g_future;
    if ($g_future) {
        $g_future->resolveKill();
        $g_future = null;
    }
    exit(1);
}
 public function beforeScenario($event)
 {
     parent::beforeScenario($event);
     // @todo provide our own mail system to ameliorate ensuing ugliness.
     if ($event instanceof ScenarioEvent) {
         if ($event->getScenario()->hasTag('mail')) {
             if (module_exists('devel')) {
                 variable_set('mail_system', array('default-system' => 'DevelMailLog'));
             } else {
                 throw new \Exception('You must ensure that the devel module is enabled');
             }
             $fs = new \Filesystem();
             if ($mail_path = $event->getScenario()->getTitle()) {
                 $fs->remove('/tmp/' . $mail_path);
                 $fs->mkdir($mail_path);
             }
             variable_set('devel_debug_mail_directory', $mail_path);
             // NB: DevelMailLog is going to replace our separator with __.
             variable_set('devel_debug_mail_file_format', '%to::%subject');
             $this->mail = new \DevelMailLog();
         }
     }
     if (!$this->drupalSession) {
         $_SERVER['SERVER_SOFTWARE'] = 'foo';
         $this->drupalSession = (object) array('name' => session_name(), 'id' => session_id());
         $_SESSION['foo'] = 'bar';
         drupal_session_commit();
     }
     session_name($this->drupalSession->name);
     session_id($this->drupalSession->id);
     $_COOKIE[session_name()] = session_id();
     drupal_session_start();
     $base_url = getenv('DRUPAL_BASE_URL');
     if (!empty($base_url)) {
         $this->setMinkParameter('base_url', $base_url);
     }
     $userName = getenv('DRUPAL_BASIC_AUTH_USERNAME');
     $pass = getenv('DRUPAL_BASIC_AUTH_PASS');
     foreach (array('selenium2', 'goutte') as $session) {
         $session = $this->getMink()->getSession($session);
         $session->visit($this->locatePath('/index.php?foo=bar'));
         if (!empty($userName) && !empty($pass)) {
             $this->getMink()->getSession()->setBasicAuth($userName, $pass);
         }
     }
 }
示例#14
0
 function testRemoveRoot()
 {
     if (PHP_OS == 'Linux' && getenv('TRAVIS')) {
         $this->assertSkipped('openvz and inotify unlinks == bad time');
     }
     $dir = PhutilDirectoryFixture::newEmptyFixture();
     $top = realpath($dir->getPath());
     $root = "{$top}/root";
     mkdir($root);
     touch("{$root}/hello");
     $this->watch($root);
     $this->assertFileList($root, array('hello'));
     Filesystem::remove($root);
     $this->assertFileList($root, array());
     $watches = $this->waitForWatchman(array('watch-list'), function ($list) use($root) {
         return !in_array($root, $list['roots']);
     });
     $this->assertEqual(false, in_array($root, $watches['roots']), "watch deleted");
     mkdir($root);
     touch("{$root}/hello");
     $this->assertFileList($root, array());
 }
示例#15
0
 private function closeSocket()
 {
     if ($this->socket) {
         @stream_socket_shutdown($this->socket, STREAM_SHUT_RDWR);
         @fclose($this->socket);
         Filesystem::remove(self::getPathToSocket($this->workingCopy));
         $this->socket = null;
     }
 }
 /**
  * @task git
  */
 private function executeGitUpdate()
 {
     $repository = $this->getRepository();
     list($err, $stdout) = $repository->execLocalCommand('rev-parse --show-toplevel');
     $message = null;
     $path = $repository->getLocalPath();
     if ($err) {
         // Try to raise a more tailored error message in the more common case
         // of the user creating an empty directory. (We could try to remove it,
         // but might not be able to, and it's much simpler to raise a good
         // message than try to navigate those waters.)
         if (is_dir($path)) {
             $files = Filesystem::listDirectory($path, $include_hidden = true);
             if (!$files) {
                 $message = pht("Expected to find a git repository at '%s', but there " . "is an empty directory there. Remove the directory: the daemon " . "will run '%s' for you.", $path, 'git clone');
             } else {
                 $message = pht("Expected to find a git repository at '%s', but there is " . "a non-repository directory (with other stuff in it) there. Move " . "or remove this directory (or reconfigure the repository to use a " . "different directory), and then either clone a repository " . "yourself or let the daemon do it.", $path);
             }
         } else {
             if (is_file($path)) {
                 $message = pht("Expected to find a git repository at '%s', but there is a " . "file there instead. Remove it and let the daemon clone a " . "repository for you.", $path);
             } else {
                 $message = pht("Expected to find a git repository at '%s', but did not.", $path);
             }
         }
     } else {
         $repo_path = rtrim($stdout, "\n");
         if (empty($repo_path)) {
             // This can mean one of two things: we're in a bare repository, or
             // we're inside a git repository inside another git repository. Since
             // the first is dramatically more likely now that we perform bare
             // clones and I don't have a great way to test for the latter, assume
             // we're OK.
         } else {
             if (!Filesystem::pathsAreEquivalent($repo_path, $path)) {
                 $err = true;
                 $message = pht("Expected to find repo at '%s', but the actual git repository root " . "for this directory is '%s'. Something is misconfigured. " . "The repository's 'Local Path' should be set to some place where " . "the daemon can check out a working copy, " . "and should not be inside another git repository.", $path, $repo_path);
             }
         }
     }
     if ($err && $repository->canDestroyWorkingCopy()) {
         phlog(pht("Repository working copy at '%s' failed sanity check; " . "destroying and re-cloning. %s", $path, $message));
         Filesystem::remove($path);
         $this->executeGitCreate();
     } else {
         if ($err) {
             throw new Exception($message);
         }
     }
     $retry = false;
     do {
         // This is a local command, but needs credentials.
         if ($repository->isWorkingCopyBare()) {
             // For bare working copies, we need this magic incantation.
             $future = $repository->getRemoteCommandFuture('fetch origin %s --prune', '+refs/heads/*:refs/heads/*');
         } else {
             $future = $repository->getRemoteCommandFuture('fetch --all --prune');
         }
         $future->setCWD($path);
         list($err, $stdout, $stderr) = $future->resolve();
         if ($err && !$retry && $repository->canDestroyWorkingCopy()) {
             $retry = true;
             // Fix remote origin url if it doesn't match our configuration
             $origin_url = $repository->execLocalCommand('config --get remote.origin.url');
             $remote_uri = $repository->getRemoteURIEnvelope();
             if ($origin_url != $remote_uri->openEnvelope()) {
                 $repository->execLocalCommand('remote set-url origin %P', $remote_uri);
             }
         } else {
             if ($err) {
                 throw new CommandException(pht('Failed to fetch changes!'), $future->getCommand(), $err, $stdout, $stderr);
             } else {
                 $retry = false;
             }
         }
     } while ($retry);
 }
 protected final function executeStopCommand(array $pids, array $options)
 {
     $console = PhutilConsole::getConsole();
     $grace_period = idx($options, 'graceful', 15);
     $force = idx($options, 'force');
     $gently = idx($options, 'gently');
     if ($gently && $force) {
         throw new PhutilArgumentUsageException(pht('You can not specify conflicting options %s and %s together.', '--gently', '--force'));
     }
     $daemons = $this->loadRunningDaemons();
     if (!$daemons) {
         $survivors = array();
         if (!$pids && !$gently) {
             $survivors = $this->processRogueDaemons($grace_period, $warn = true, $force);
         }
         if (!$survivors) {
             $console->writeErr("%s\n", pht('There are no running Phabricator daemons.'));
         }
         return 0;
     }
     $stop_pids = $this->selectDaemonPIDs($daemons, $pids);
     if (!$stop_pids) {
         $console->writeErr("%s\n", pht('No daemons to kill.'));
         return 0;
     }
     $survivors = $this->sendStopSignals($stop_pids, $grace_period);
     // Try to clean up PID files for daemons we killed.
     $remove = array();
     foreach ($daemons as $daemon) {
         $pid = $daemon->getPID();
         if (empty($stop_pids[$pid])) {
             // We did not try to stop this overseer.
             continue;
         }
         if (isset($survivors[$pid])) {
             // We weren't able to stop this overseer.
             continue;
         }
         if (!$daemon->getPIDFile()) {
             // We don't know where the PID file is.
             continue;
         }
         $remove[] = $daemon->getPIDFile();
     }
     foreach (array_unique($remove) as $remove_file) {
         Filesystem::remove($remove_file);
     }
     if (!$gently) {
         $this->processRogueDaemons($grace_period, !$pids, $force);
     }
     return 0;
 }
 /**
  * Get the path to a scratch file, if possible.
  *
  * @param string  Scratch file name.
  * @return mixed  File path, or false on failure.
  * @task scratch
  */
 public function getScratchFilePath($path)
 {
     $new_scratch_path = Filesystem::resolvePath('arc', $this->getMetadataPath());
     static $checked = false;
     if (!$checked) {
         $checked = true;
         $old_scratch_path = $this->getPath('.arc');
         // we only want to do the migration once
         // unfortunately, people have checked in .arc directories which
         // means that the old one may get recreated after we delete it
         if (Filesystem::pathExists($old_scratch_path) && !Filesystem::pathExists($new_scratch_path)) {
             Filesystem::createDirectory($new_scratch_path);
             $existing_files = Filesystem::listDirectory($old_scratch_path, true);
             foreach ($existing_files as $file) {
                 $new_path = Filesystem::resolvePath($file, $new_scratch_path);
                 $old_path = Filesystem::resolvePath($file, $old_scratch_path);
                 Filesystem::writeFile($new_path, Filesystem::readFile($old_path));
             }
             Filesystem::remove($old_scratch_path);
         }
     }
     return Filesystem::resolvePath($path, $new_scratch_path);
 }
 public function executeStopCommand($pids = null)
 {
     $daemons = $this->loadRunningDaemons();
     if (!$daemons) {
         echo "There are no running Phabricator daemons.\n";
         return 0;
     }
     $daemons = mpull($daemons, null, 'getPID');
     $running = array();
     if ($pids == null) {
         $running = $daemons;
     } else {
         // We were given a PID or set of PIDs to kill.
         foreach ($pids as $key => $pid) {
             if (!preg_match('/^\\d+$/', $pid)) {
                 echo "'{$pid}' is not a valid PID.\n";
                 continue;
             } else {
                 if (empty($daemons[$pid])) {
                     echo "'{$pid}' is not Phabricator-controlled PID. Not killing.\n";
                     continue;
                 } else {
                     $running[] = $daemons[$pid];
                 }
             }
         }
     }
     if (empty($running)) {
         echo "No daemons to kill.\n";
         return 0;
     }
     $all_daemons = $running;
     foreach ($running as $key => $daemon) {
         $pid = $daemon->getPID();
         $name = $daemon->getName();
         echo "Stopping daemon '{$name}' ({$pid})...\n";
         if (!$daemon->isRunning()) {
             echo "Daemon is not running.\n";
             unset($running[$key]);
             $daemon_log = $daemon->loadDaemonLog();
             if ($daemon_log) {
                 $daemon_log->setStatus(PhabricatorDaemonLog::STATUS_EXITED);
                 $daemon_log->save();
             }
         } else {
             posix_kill($pid, SIGINT);
         }
     }
     $start = time();
     do {
         foreach ($running as $key => $daemon) {
             $pid = $daemon->getPID();
             if (!$daemon->isRunning()) {
                 echo "Daemon {$pid} exited normally.\n";
                 unset($running[$key]);
             }
         }
         if (empty($running)) {
             break;
         }
         usleep(100000);
     } while (time() < $start + 15);
     foreach ($running as $key => $daemon) {
         $pid = $daemon->getPID();
         echo "KILLing daemon {$pid}.\n";
         posix_kill($pid, SIGKILL);
     }
     foreach ($all_daemons as $daemon) {
         if ($daemon->getPIDFile()) {
             Filesystem::remove($daemon->getPIDFile());
         }
     }
 }
示例#20
0
 public static function removeContentFrom($directory)
 {
     if (is_dir($directory)) {
         $fileSystem = new Filesystem();
         $cacheIterator = new \DirectoryIterator($directory);
         foreach ($cacheIterator as $item) {
             if (!$item->isDot() && '.gitkeep' !== $item->getFilename()) {
                 $fileSystem->remove($item->getPathname());
             }
         }
     }
 }
 private function lookupRecursiveFileList(PhabricatorRepository $repository, array $info)
 {
     $path = $info['rawPath'];
     $rev = $info['rawCommit'];
     $path_uri = $repository->getSubversionPathURI($path, $rev);
     $hashkey = md5($path_uri);
     // This method is quite horrible. The underlying challenge is that some
     // commits in the Facebook repository are enormous, taking multiple hours
     // to 'ls -R' out of the repository and producing XML files >1GB in size.
     // If we try to SimpleXML them, the object exhausts available memory on a
     // 64G machine. Instead, cache the XML output and then parse it line by line
     // to limit space requirements.
     $cache_loc = sys_get_temp_dir() . '/diffusion.' . $hashkey . '.svnls';
     if (!Filesystem::pathExists($cache_loc)) {
         $tmp = new TempFile();
         $repository->execxRemoteCommand('--xml ls -R %s > %s', $path_uri, $tmp);
         execx('mv %s %s', $tmp, $cache_loc);
     }
     $map = $this->parseRecursiveListFileData($cache_loc);
     Filesystem::remove($cache_loc);
     return $map;
 }
示例#22
0
 private function getBulkFileDataAtRevision($paths, $revision)
 {
     // Calling 'hg cat' on each file individually is slow (1 second per file
     // on a large repo) because mercurial has to decompress and parse the
     // entire manifest every time. Do it in one large batch instead.
     // hg cat will write the file data to files in a temp directory
     $tmpdir = Filesystem::createTemporaryDirectory();
     // Mercurial doesn't create the directories for us :(
     foreach ($paths as $path) {
         $tmppath = $tmpdir . '/' . $path;
         Filesystem::createDirectory(dirname($tmppath), 0755, true);
     }
     list($err, $stdout) = $this->execManualLocal('cat --rev %s --output %s -- %C', $revision, $tmpdir . '/%p', implode(' ', $paths));
     $filedata = array();
     foreach ($paths as $path) {
         $tmppath = $tmpdir . '/' . $path;
         if (Filesystem::pathExists($tmppath)) {
             $filedata[$path] = Filesystem::readFile($tmppath);
         }
     }
     Filesystem::remove($tmpdir);
     return $filedata;
 }
 public function actionNewimport()
 {
     //$path = _APP_PATH_ . DS . "data";
     //$pathSource = 'E:\phuongnv\Vega\chacha_cloud\src\trunk\chacha\data';
     $pathSource = _APP_PATH_ . DS . "data";
     try {
         $log = new KLogger('LOG_IMPORT_FILE_SONG_PNV', KLogger::INFO);
         $log->LogInfo("Start New Import", false);
         $model = new AdminImportSongModel();
         $importer = self::IMPORT_SONG_CACHE . Yii::app()->user->id;
         $result = array();
         if (isset($_POST['AdminImportSongModel'])) {
             $this->layout = false;
             $autoconfirm = Yii::app()->request->getParam('autoconfirm');
             $autoconfirm = isset($autoconfirm) ? 1 : 0;
             $created_time = $_POST['AdminSongModel']['created_time'];
             $updated_time = $_POST['AdminSongModel']['updated_time'];
             $path = Yii::app()->params['importsong']['store_path'];
             $file_path = $pathSource . DS . "tmp" . DS . $_POST['AdminImportSongModel']['source_path'];
             $fileName = explode(DS, $file_path);
             $fileName = $fileName[count($fileName) - 1];
             if (file_exists($file_path)) {
                 $count = 0;
                 $start_row = $_POST['AdminImportSongModel']['start_row'] > 0 ? $_POST['AdminImportSongModel']['start_row'] : 0;
                 $start_row += self::START_ROW;
                 $limit_row = 65000;
                 $limit_row += $start_row;
                 $log->LogInfo("Start Read File and put Memcache | " . $file_path, false);
                 $data = new ExcelReader($file_path);
                 $resultSql = array();
                 //insert file
                 $sql = "INSERT INTO import_song_file(file_name,importer,status,created_time)\n                \t\t\tVALUE('" . $fileName . "', '{$importer}',0,NOW())\n\t                \t\t\t";
                 $insertFileRess = Yii::app()->db->createCommand($sql)->execute();
                 $fileImportId = Yii::app()->db->getLastInsertID();
                 for ($i = $start_row; $i < $limit_row; $i++) {
                     if ($data->val($i, 'B') != "" && $data->val($i, 'G') != "" && $data->val($i, 'C') != "") {
                         $stt = $data->val($i, Yii::app()->params['importsong']['excelcolumns']['stt']);
                         $name = $model->my_encoding($data->val($i, Yii::app()->params['importsong']['excelcolumns']['name']));
                         $category = $model->my_encoding($data->val($i, Yii::app()->params['importsong']['excelcolumns']['category']));
                         $sub_category = $model->my_encoding($data->val($i, Yii::app()->params['importsong']['excelcolumns']['sub_category']));
                         $composer = $model->my_encoding($data->val($i, Yii::app()->params['importsong']['excelcolumns']['composer']));
                         $artist = $model->my_encoding($data->val($i, Yii::app()->params['importsong']['excelcolumns']['artist']));
                         $album = $model->my_encoding($data->val($i, Yii::app()->params['importsong']['excelcolumns']['album']));
                         $path = str_replace('\\', DS, $data->val($i, Yii::app()->params['importsong']['excelcolumns']['path']));
                         $file = $data->val($i, Yii::app()->params['importsong']['excelcolumns']['file']);
                         $sql = "(";
                         $sql .= "'" . $autoconfirm . "'";
                         $sql .= ",'" . $created_time . "'";
                         $sql .= ",'" . $updated_time . "'";
                         $sql .= ",'" . $stt . "'";
                         $sql .= ",'" . addslashes($name) . "'";
                         $sql .= ",'" . $category . "'";
                         $sql .= ",'" . $sub_category . "'";
                         $sql .= ",'" . addslashes($composer) . "'";
                         $sql .= ",'" . addslashes($artist) . "'";
                         $sql .= ",'" . addslashes($album) . "'";
                         //$sql .= ",'".str_replace('\\', '\\\\', $path)."'";
                         $sql .= ",'" . addslashes($path) . "'";
                         //$sql .= ",'".str_replace('\\', '\\\\', $file)."'";
                         $sql .= ",'" . addslashes($file) . "'";
                         $sql .= ",'" . $importer . "'";
                         //$sql .= ",'".str_replace('\\', '\\\\', $file_path)."'";
                         $sql .= ",'" . addslashes($file_path) . "'";
                         $sql .= ",'" . $fileImportId . "'";
                         $sql .= ")";
                         $resultSql[] = $sql;
                         $count++;
                     }
                     /* if($count==10)
                     		 echo '<pre>';print_r($result);die(); */
                 }
                 //insert data to db
                 if ($insertFileRess) {
                     $sql = "INSERT INTO import_song(autoconfirm,created_time,updated_time,stt,name,category,sub_category,composer,artist,album,path,file,importer,file_name,file_id) VALUES";
                     $sql .= implode(',', $resultSql);
                     if (Yii::app()->db->createCommand($sql)->execute()) {
                         $sql = "UPDATE import_song_file set total_song={$count} WHERE id={$fileImportId}";
                         Yii::app()->db->createCommand($sql)->execute();
                     }
                     //insert false
                 }
                 //remove file source after insert
                 $fileSystem = new Filesystem();
                 $fileSystem->remove($file_path);
                 echo CJSON::encode(array('errorCode' => 0, 'errorDesc' => 'Success imported Total Record: ' . count($resultSql)));
             } else {
                 //if ($_POST['AdminImportSongModel']['ajax'])
                 echo CJSON::encode(array('errorCode' => 1, 'errorDesc' => 'Chưa upload file excel'));
             }
             Yii::app()->end();
         }
     } catch (Exception $e) {
         $log->LogError("actionAjaxImport | Exception Error: " . $e->getMessage(), false);
         echo CJSON::encode(array('errorCode' => 1, 'errorDesc' => 'Chưa upload file excel'));
         Yii::app()->end();
     }
     $uploadModel = new XUploadForm();
     $this->render('newimport', array('model' => $model, 'listSong' => $result, 'uploadModel' => $uploadModel));
 }
 public function destroyCache()
 {
     Filesystem::remove($this->getCacheDirectory());
     return $this;
 }
 protected final function executeStopCommand(array $pids, $grace_period, $force)
 {
     $console = PhutilConsole::getConsole();
     $daemons = $this->loadRunningDaemons();
     if (!$daemons) {
         $survivors = array();
         if (!$pids) {
             $survivors = $this->processRogueDaemons($grace_period, $warn = true, $force);
         }
         if (!$survivors) {
             $console->writeErr(pht('There are no running Phabricator daemons.') . "\n");
         }
         return 0;
     }
     $daemons = mpull($daemons, null, 'getPID');
     $running = array();
     if (!$pids) {
         $running = $daemons;
     } else {
         // We were given a PID or set of PIDs to kill.
         foreach ($pids as $key => $pid) {
             if (!preg_match('/^\\d+$/', $pid)) {
                 $console->writeErr(pht("PID '%s' is not a valid PID.", $pid) . "\n");
                 continue;
             } else {
                 if (empty($daemons[$pid])) {
                     $console->writeErr(pht("PID '%s' is not a Phabricator daemon PID. It will not " . "be killed.", $pid) . "\n");
                     continue;
                 } else {
                     $running[] = $daemons[$pid];
                 }
             }
         }
     }
     if (empty($running)) {
         $console->writeErr(pht('No daemons to kill.') . "\n");
         return 0;
     }
     $all_daemons = $running;
     // don't specify force here as that's about rogue daemons
     $this->sendStopSignals($running, $grace_period);
     foreach ($all_daemons as $daemon) {
         if ($daemon->getPIDFile()) {
             Filesystem::remove($daemon->getPIDFile());
         }
     }
     $this->processRogueDaemons($grace_period, !$pids, $force);
     return 0;
 }
示例#26
0
 public function writeToDisk($path)
 {
     $changes = $this->getChanges();
     $change_list = array();
     foreach ($changes as $change) {
         $change_list[] = $change->toDictionary();
     }
     $hunks = array();
     foreach ($change_list as $change_key => $change) {
         foreach ($change['hunks'] as $key => $hunk) {
             $hunks[] = $hunk['corpus'];
             $change_list[$change_key]['hunks'][$key]['corpus'] = count($hunks) - 1;
         }
     }
     $blobs = array();
     foreach ($change_list as $change) {
         if (!empty($change['metadata']['old:binary-phid'])) {
             $blobs[$change['metadata']['old:binary-phid']] = null;
         }
         if (!empty($change['metadata']['new:binary-phid'])) {
             $blobs[$change['metadata']['new:binary-phid']] = null;
         }
     }
     foreach ($blobs as $phid => $null) {
         $blobs[$phid] = $this->getBlob($phid);
     }
     $meta_info = array('version' => 5, 'projectName' => $this->getProjectID(), 'baseRevision' => $this->getBaseRevision(), 'revisionID' => $this->getRevisionID(), 'encoding' => $this->getEncoding(), 'authorName' => $this->getAuthorName(), 'authorEmail' => $this->getAuthorEmail());
     $dir = Filesystem::createTemporaryDirectory();
     Filesystem::createDirectory($dir . '/hunks');
     Filesystem::createDirectory($dir . '/blobs');
     Filesystem::writeFile($dir . '/changes.json', json_encode($change_list));
     Filesystem::writeFile($dir . '/meta.json', json_encode($meta_info));
     foreach ($hunks as $key => $hunk) {
         Filesystem::writeFile($dir . '/hunks/' . $key, $hunk);
     }
     foreach ($blobs as $key => $blob) {
         Filesystem::writeFile($dir . '/blobs/' . $key, $blob);
     }
     execx('(cd %s; tar -czf %s *)', $dir, Filesystem::resolvePath($path));
     Filesystem::remove($dir);
 }
 public function executeStopCommand()
 {
     $daemons = $this->loadRunningDaemons();
     if (!$daemons) {
         echo "There are no running Phabricator daemons.\n";
         return 0;
     }
     $running = $daemons;
     foreach ($running as $key => $daemon) {
         $pid = $daemon->getPID();
         $name = $daemon->getName();
         echo "Stopping daemon '{$name}' ({$pid})...\n";
         if (!$daemon->isRunning()) {
             echo "Daemon is not running.\n";
             unset($running[$key]);
         } else {
             posix_kill($pid, SIGINT);
         }
     }
     $start = time();
     do {
         foreach ($running as $key => $daemon) {
             $pid = $daemon->getPID();
             if (!$daemon->isRunning()) {
                 echo "Daemon {$pid} exited normally.\n";
                 unset($running[$key]);
             }
         }
         if (empty($running)) {
             break;
         }
         usleep(100000);
     } while (time() < $start + 15);
     foreach ($running as $key => $daemon) {
         $pid = $daemon->getPID();
         echo "KILLing daemon {$pid}.\n";
         posix_kill($pid, SIGKILL);
     }
     foreach ($daemons as $daemon) {
         if ($daemon->getPIDFile()) {
             Filesystem::remove($daemon->getPIDFile());
         }
     }
 }
 /**
  * Drop the symbol cache, forcing a clean rebuild.
  *
  * @return this
  *
  * @task symbol
  */
 public function dropSymbolCache()
 {
     $this->log(pht('Dropping symbol cache...'));
     Filesystem::remove($this->getPathForSymbolCache());
 }
 protected final function executeStopCommand()
 {
     $console = PhutilConsole::getConsole();
     $pid = $this->getPID();
     if (!$pid) {
         $console->writeErr("%s\n", pht('Aphlict is not running.'));
         return 0;
     }
     $console->writeErr("%s\n", pht('Stopping Aphlict Server (%s)...', $pid));
     posix_kill($pid, SIGINT);
     $start = time();
     do {
         if (!PhabricatorDaemonReference::isProcessRunning($pid)) {
             $console->writeOut("%s\n", pht('Aphlict Server (%s) exited normally.', $pid));
             $pid = null;
             break;
         }
         usleep(100000);
     } while (time() < $start + 5);
     if ($pid) {
         $console->writeErr("%s\n", pht('Sending %s a SIGKILL.', $pid));
         posix_kill($pid, SIGKILL);
         unset($pid);
     }
     Filesystem::remove($this->getPIDPath());
     return 0;
 }
 public function didExecute(PhutilArgumentParser $args)
 {
     $api = $this->getSingleAPI();
     $patches = $this->getPatches();
     $console = PhutilConsole::getConsole();
     $applied = $api->getAppliedPatches();
     if ($applied === null) {
         $namespace = $api->getNamespace();
         $console->writeErr(pht('**Storage Not Initialized**: There is no database storage ' . 'initialized in this storage namespace ("%s"). Use ' . '**%s** to initialize storage.', $namespace, './bin/storage upgrade'));
         return 1;
     }
     $databases = $api->getDatabaseList($patches, true);
     list($host, $port) = $this->getBareHostAndPort($api->getHost());
     $has_password = false;
     $password = $api->getPassword();
     if ($password) {
         if (strlen($password->openEnvelope())) {
             $has_password = true;
         }
     }
     $output_file = $args->getArg('output');
     $is_compress = $args->getArg('compress');
     $is_overwrite = $args->getArg('overwrite');
     if ($is_compress) {
         if ($output_file === null) {
             throw new PhutilArgumentUsageException(pht('The "--compress" flag can only be used alongside "--output".'));
         }
     }
     if ($is_overwrite) {
         if ($output_file === null) {
             throw new PhutilArgumentUsageException(pht('The "--overwrite" flag can only be used alongside "--output".'));
         }
     }
     if ($output_file !== null) {
         if (Filesystem::pathExists($output_file)) {
             if (!$is_overwrite) {
                 throw new PhutilArgumentUsageException(pht('Output file "%s" already exists. Use "--overwrite" ' . 'to overwrite.', $output_file));
             }
         }
     }
     $argv = array();
     $argv[] = '--hex-blob';
     $argv[] = '--single-transaction';
     $argv[] = '--default-character-set=utf8';
     if ($args->getArg('for-replica')) {
         $argv[] = '--master-data';
     }
     $argv[] = '-u';
     $argv[] = $api->getUser();
     $argv[] = '-h';
     $argv[] = $host;
     if ($port) {
         $argv[] = '--port';
         $argv[] = $port;
     }
     $argv[] = '--databases';
     foreach ($databases as $database) {
         $argv[] = $database;
     }
     if ($has_password) {
         $command = csprintf('mysqldump -p%P %Ls', $password, $argv);
     } else {
         $command = csprintf('mysqldump %Ls', $argv);
     }
     // If we aren't writing to a file, just passthru the command.
     if ($output_file === null) {
         return phutil_passthru('%C', $command);
     }
     // If we are writing to a file, stream the command output to disk. This
     // mode makes sure the whole command fails if there's an error (commonly,
     // a full disk). See T6996 for discussion.
     if ($is_compress) {
         $file = gzopen($output_file, 'wb');
     } else {
         $file = fopen($output_file, 'wb');
     }
     if (!$file) {
         throw new Exception(pht('Failed to open file "%s" for writing.', $file));
     }
     $future = new ExecFuture('%C', $command);
     $lines = new LinesOfALargeExecFuture($future);
     try {
         foreach ($lines as $line) {
             $line = $line . "\n";
             if ($is_compress) {
                 $ok = gzwrite($file, $line);
             } else {
                 $ok = fwrite($file, $line);
             }
             if ($ok !== strlen($line)) {
                 throw new Exception(pht('Failed to write %d byte(s) to file "%s".', new PhutilNumber(strlen($line)), $output_file));
             }
         }
         if ($is_compress) {
             $ok = gzclose($file);
         } else {
             $ok = fclose($file);
         }
         if ($ok !== true) {
             throw new Exception(pht('Failed to close file "%s".', $output_file));
         }
     } catch (Exception $ex) {
         // If we might have written a partial file to disk, try to remove it so
         // we don't leave any confusing artifacts laying around.
         try {
             Filesystem::remove($output_file);
         } catch (Exception $ex) {
             // Ignore any errors we hit.
         }
         throw $ex;
     }
     return 0;
 }