+ protected function getServerNumber()
+ {
+ //clean stale lock files
+ $this->cleanup();
+
+ $num = 100;
+ $bFound = false;
+ do {
+ ++$num;
+ $f = $this->config->cacheDir . 'tmp-curlycapt-server-' . $num . '.lock';
+ $this->lockHdl = fopen($f, 'w');
+ if (flock($this->lockHdl, LOCK_EX | LOCK_NB)) {
+ $this->lockFile = $f;
+ $bFound = true;
+ break;
+ } else {
+ fclose($this->lockHdl);
+ }
+ } while ($num < 200);
+
+ if (!$bFound) {
+ throw new \Exception('Too many requests running');
+ }
+
+ $this->lockFile = $f;
+ return $num;
+ }
+
+ public function cleanup()
+ {
+ if ($this->lockFile !== null && $this->lockHdl) {
+ flock($this->lockHdl, LOCK_UN);
+ unlink($this->lockFile);
+ }
+
+ $lockFiles = glob(
+ $this->config->cacheDir . 'tmp-curlycapt-server-*.lock'
+ );
+
+ $now = time();
+ foreach ($lockFiles as $file) {
+ if ($now - filemtime($file) > 120) {
+ //delete stale lock file; probably something crashed.
+ unlink($file);
+ }
+ }
+ }
+