/** */ public function minify() { if (!is_executable($this->_opts['java']) || !is_readable($this->_opts['closure'])) { $this->_opts['logger']->log('The java path or Closure location can not be accessed.', Horde_Log::ERR); return parent::minify(); } $cmd = trim(escapeshellcmd($this->_opts['java']) . ' -jar ' . escapeshellarg($this->_opts['closure'])); if (isset($this->_opts['sourcemap']) && is_array($this->_data)) { $this->_sourcemap = Horde_Util::getTempFile(); $cmd .= ' --create_source_map ' . escapeshellarg($this->_sourcemap) . ' --source_map_format=V3'; $suffix = "\n//# sourceMappingURL=" . $this->_opts['sourcemap']; } else { $suffix = ''; } if (isset($this->_opts['cmdline'])) { $cmd .= ' ' . trim($this->_opts['cmdline']); } if (is_array($this->_data)) { $js = ''; foreach ($this->_data as $val) { $cmd .= ' ' . $val; } } else { $js = $this->_data; } $cmdline = new Horde_JavascriptMinify_Util_Cmdline(); return $cmdline->runCmd($js, $cmd, $this->_opts['logger']) . $suffix . $this->_sourceUrls(); }
/** */ public function minify() { if (!is_executable($this->_opts['java']) || !is_readable($this->_opts['closure'])) { $this->_opts['logger']->log('The java path or Closure location can not be accessed.', Horde_Log::ERR); return parent::minify(); } /* --warning_level QUIET - closure default is "DEFAULT" which will * cause code with compiler warnings to output bad js (see Bug * #13789) */ $cmd = trim(escapeshellcmd($this->_opts['java']) . ' -jar ' . escapeshellarg($this->_opts['closure']) . ' --warning_level QUIET'); if (isset($this->_opts['sourcemap']) && is_array($this->_data)) { $this->_sourcemap = Horde_Util::getTempFile(); $cmd .= ' --create_source_map ' . escapeshellarg($this->_sourcemap) . ' --source_map_format=V3'; $suffix = "\n//# sourceMappingURL=" . $this->_opts['sourcemap']; } else { $suffix = ''; } if (isset($this->_opts['cmdline'])) { $cmd .= ' ' . trim($this->_opts['cmdline']); } if (is_array($this->_data)) { $js = ''; foreach ($this->_data as $val) { $cmd .= ' ' . $val; } } else { $js = $this->_data; } $cmdline = new Horde_JavascriptMinify_Util_Cmdline(); return $cmdline->runCmd($js, $cmd, $this->_opts['logger']) . $suffix . $this->_sourceUrls(); }
function getPDF() { $tmp_file = Horde_Util::getTempFile('fax', true, '/tmp'); $fp = fopen($tmp_file, 'wb'); fwrite($fp, $this->_data); fclose($fp); /* Convert the page from the postscript file to PDF. */ $command = sprintf('%s %s -', $this->_cmd['ps2pdf'], $tmp_file); Horde::log('Executing command: ' . $command, 'DEBUG'); passthru($command); }
/** * Test storing attachments. * * @return NULL */ public function testCacheAttachmentInFile() { $data = new Horde_Kolab_Storage_Data('contact'); $data->setFolder($this->folder); $atc1 = Horde_Util::getTempFile(); $fh = fopen($atc1, 'w'); fwrite($fh, 'test'); fclose($fh); $object = array('uid' => '1', 'full-name' => 'User Name', 'email' => '*****@*****.**', 'inline-attachment' => array('test.txt'), '_attachments' => array('test.txt' => array('type' => 'text/plain', 'path' => $atc1, 'name' => 'test.txt'))); $result = $data->save($object); $this->assertNoError($result); $result = $data->getObject(1); $this->assertNoError($result); $this->assertTrue(isset($result['_attachments']['test.txt'])); // @todo: what introduces the \r? $this->assertEquals("test\r", $data->getAttachment($result['_attachments']['test.txt']['key'])); }
/** * Validate the preconditions required for this release task. * * @param array $options Additional options. * * @return array An empty array if all preconditions are met and a list of * error messages otherwise. */ public function validate($options) { $errors = array(); $testpkg = Horde_Util::getTempFile(); $archive = new Archive_Tar($testpkg, 'gz'); $archive->addString('a', 'a'); $archive->addString('b', 'b'); $results = exec('tar tzvf ' . $testpkg . ' 2>&1'); // MacOS tar doesn't error out, but only returns the first string (ending in 'a'); if (strpos($results, 'lone zero block') !== false || substr($results, -1, 1) == 'a') { $errors[] = 'Broken Archive_Tar, upgrade first.'; } $remote = new Horde_Pear_Remote(); try { $exists = $remote->releaseExists($this->getComponent()->getName(), $this->getComponent()->getVersion()); if ($exists) { $errors[] = sprintf('The remote server already has version "%s" for component "%s".', $this->getComponent()->getVersion(), $this->getComponent()->getName()); } } catch (Horde_Http_Exception $e) { $errors[] = 'Failed accessing the remote PEAR server.'; } try { Components_Helper_Version::validateReleaseStability($this->getComponent()->getVersion(), $this->getComponent()->getState('release')); } catch (Components_Exception $e) { $errors[] = $e->getMessage(); } try { Components_Helper_Version::validateApiStability($this->getComponent()->getVersion(), $this->getComponent()->getState('api')); } catch (Components_Exception $e) { $errors[] = $e->getMessage(); } if (empty($options['releaseserver'])) { $errors[] = 'The "releaseserver" option has no value. Where should the release be uploaded?'; } if (empty($options['releasedir'])) { $errors[] = 'The "releasedir" option has no value. Where is the remote pirum install located?'; } return $errors; }
/** */ public function minify() { if (!is_readable($this->_opts['uglifyjs'])) { $this->_opts['logger']->log('The UglifyJS binary cannot be accessed.', Horde_Log::ERR); return parent::minify(); } $cmd = escapeshellcmd($this->_opts['uglifyjs']); if (isset($this->_opts['sourcemap']) && is_array($this->_data)) { $this->_sourcemap = Horde_Util::getTempFile(); $cmd .= ' --source-map ' . escapeshellarg($this->_sourcemap) . ' --source-map-url ' . escapeshellarg($this->_opts['sourcemap']); } if (is_array($this->_data)) { $js = ''; foreach ($this->_data as $val) { $cmd .= ' ' . $val; } } else { $js = $this->_data; } $cmdline = new Horde_JavascriptMinify_Util_Cmdline(); return $cmdline->runCmd($js, trim($cmd . ' ' . $this->_opts['cmdline']), $this->_opts['logger']) . $this->_sourceUrls(); }
/** */ public function process($css, $cacheid) { global $registry; if (!empty($this->_params['filemtime'])) { foreach ($css as &$val) { $val['mtime'] = @filemtime($val['fs']); } } $sig = hash(version_compare(PHP_VERSION, '5.4', '>=') ? 'fnv164' : 'sha1', json_encode($css) . $cacheid); $filename = $sig . '.css'; $js_fs = $registry->get('staticfs', 'horde'); $path = $js_fs . '/' . $filename; if (!file_exists($path)) { $compress = new Horde_Themes_Css_Compress(); $temp = Horde_Util::getTempFile('staticcss', true, $js_fs); if (!file_put_contents($temp, $compress->compress($css), LOCK_EX) || !chmod($temp, 0777 & ~umask()) || !rename($temp, $path)) { Horde::log('Could not write cached CSS file to disk.', 'EMERG'); return array(); } } return array(Horde::url($registry->get('staticuri', 'horde') . '/' . $filename, true, array('append_session' => -1))); }
/** * Checks for a file uploaded via the pluploader. If one is found, handle * it, send the server json response and exit. */ protected function _handleFileUpload() { if ($filename = Horde_Util::getFormData('name')) { if (isset($_SERVER["HTTP_CONTENT_TYPE"])) { $type = $_SERVER["HTTP_CONTENT_TYPE"]; } elseif (isset($_SERVER["CONTENT_TYPE"])) { $type = $_SERVER["CONTENT_TYPE"]; } if (empty($type) || $type == 'application/octet-stream') { $temp = Horde_Util::getTempFile('', true); $out = fopen($temp, 'w+'); if ($out) { // Read binary input stream and append it to temp file $in = fopen("php://input", "rb"); if ($in) { stream_copy_to_stream($in, $out); rewind($out); fclose($in); } else { fclose($out); header('Content-Type: application/json'); echo '{ "status" : "500", "file": "' . $temp . '", error" : { "message": "Failed to open input stream." } }'; exit; } } else { header('Content-Type: application/json'); echo '{ "status" : "500", "file": "' . $temp . '", error" : { "message": "Failed to open output stream." } }'; exit; } // // Don't know type. Try to deduce it. if (!($type = Horde_Mime_Magic::analyzeFile($temp, isset($GLOBALS['conf']['mime']['magic_db']) ? $GLOBALS['conf']['mime']['magic_db'] : null))) { $type = Horde_Mime_Magic::filenameToMime($filename); } } elseif (strpos($type, "multipart") !== false) { // Handle mulitpart uploads $temp = Horde_Util::getTempFile('', true); $out = fopen($temp, 'w+'); if ($out) { $in = fopen($_FILES['file']['tmp_name'], 'rb'); if ($in) { stream_copy_to_stream($in, $out); rewind($out); fclose($in); } else { fclose($out); header('Content-Type: application/json'); echo '{ "status" : "500", "file": "' . $temp . '", error" : { "message": "Failed to open input stream." } }'; exit; } } else { header('Content-Type: application/json'); echo '{ "status" : "500", "file": "' . $temp . '", error" : { "message": "Failed to open output stream." } }'; exit; } } // Figure out what to do with the file if (in_array($type, array('x-extension/zip', 'application/x-compressed', 'application/x-zip-compressed', 'application/zip')) || Horde_Mime_Magic::filenameToMime($temp) == 'application/zip') { // ZIP file try { $image_ids = $this->_handleZip($temp); } catch (Ansel_Exception $e) { $notification->push(sprintf(_("There was an error processing the uploaded archive: %s"), $e->getMessage()), 'horde.error'); } } else { // Try and make sure the image is in a recognizeable format. if (getimagesize($temp) === false) { header('Content-Type: application/json'); echo '{ "status" : "400", "error" : { "message": "Not a valid, supported image file." }, "id" : "id" }'; exit; } // Add the image to the gallery $image_data = array('image_filename' => $filename, 'image_type' => $type, 'data' => stream_get_contents($out)); fclose($out); try { $image_ids = array($this->_gallery->addImage($image_data)); } catch (Ansel_Exception $e) { header('Content-Type: application/json'); echo '{ "status" : "400", "error" : { "message": "Not a valid, supported image file." }, "id" : "id" }'; exit; } unset($data); } // Try to auto generate some thumbnails. $qtask = new Ansel_Queue_ProcessThumbs($image_ids); $queue = $GLOBALS['injector']->getInstance('Horde_Queue_Storage'); $queue->add($qtask); header('Content-Type: application/json'); echo '{ "status" : "200", "error" : {} }'; exit; } }
/** * TODO * * @throws Horde_Vcs_Exception */ public function annotate($fileob, $rev) { $this->assertValidRevision($rev); $tmpfile = Horde_Util::getTempFile('vc', true, $this->_paths['temp']); $where = $fileob->getSourcerootPath(); $pipe = popen(escapeshellcmd($this->getPath('cvs')) . ' -n server > ' . escapeshellarg($tmpfile), VC_WINDOWS ? 'wb' : 'w'); $out = array('Root ' . $this->sourceroot, 'Valid-responses ok error Valid-requests Checked-in Updated Merged Removed M E', 'UseUnchanged', 'Argument -r', 'Argument ' . $rev, 'Argument ' . $where); $dirs = explode('/', dirname($where)); while (count($dirs)) { $out[] = 'Directory ' . implode('/', $dirs); $out[] = $this->sourceroot . '/' . implode('/', $dirs); array_pop($dirs); } $out[] = 'Directory .'; $out[] = $this->sourceroot; $out[] = 'annotate'; foreach ($out as $line) { fwrite($pipe, "{$line}\n"); } pclose($pipe); if (!($fl = fopen($tmpfile, VC_WINDOWS ? 'rb' : 'r'))) { return false; } $lines = array(); $line = fgets($fl, 4096); // Windows versions of cvs always return $where with forwards slashes. if (VC_WINDOWS) { $where = str_replace(DIRECTORY_SEPARATOR, '/', $where); } while ($line && !preg_match("|^E\\s+Annotations for {$where}|", $line)) { $line = fgets($fl, 4096); } if (!$line) { throw new Horde_Vcs_Exception('Unable to annotate; server said: ' . $line); } $lineno = 1; while ($line = fgets($fl, 4096)) { if (preg_match('/^M\\s+([\\d\\.]+)\\s+\\((.+)\\s+(\\d+-\\w+-\\d+)\\):.(.*)$/', $line, $regs)) { $lines[] = array('rev' => $regs[1], 'author' => trim($regs[2]), 'date' => $regs[3], 'line' => $regs[4], 'lineno' => $lineno++); } } fclose($fl); return $lines; }
/** */ protected function _process($scripts) { global $registry; if (empty($scripts)) { return array(); } $tmp = array(); foreach ($scripts as $val) { $tmp[] = $val->modified; } $mtime = max($tmp); $hashes = array_keys($scripts); sort($hashes); /* Use 64-bit FNV algo (instead of 32-bit) since this is a * publicly accessible key and we want to guarantee filename * is unique. */ $sig = hash(version_compare(PHP_VERSION, '5.4', '>=') ? 'fnv164' : 'sha1', json_encode($hashes) . $mtime); $js_filename = $sig . '.js'; $js_fs = $registry->get('staticfs', 'horde'); $js_path = $js_fs . '/' . $js_filename; $js_url = $registry->get('staticuri', 'horde') . '/' . $js_filename; $out = array($js_url); if (file_exists($js_path)) { return $out; } /* Check for existing process creating compressed file. Maximum 15 * seconds wait time. */ for ($i = 0; $i < 15; ++$i) { if (file_exists($js_path . '.lock')) { sleep(1); } elseif ($i) { return $out; } else { touch($js_path . '.lock'); break; } } if (!isset($this->_compress)) { $this->_compress = new Horde_Script_Compress($this->_params['compress'], $this->_params); } $sourcemap_url = $js_url . '.map'; $jsmin = $this->_compress->getMinifier($scripts, $sourcemap_url); $temp = Horde_Util::getTempFile('staticjs', true, $js_fs); if (!file_put_contents($temp, $jsmin->minify(), LOCK_EX) || !chmod($temp, 0777 & ~umask()) || !rename($temp, $js_path)) { Horde::log('Could not write cached JS file to disk.', Horde_Log::EMERG); } elseif ($this->_compress->sourcemap_support) { file_put_contents($js_path . '.map', $jsmin->sourcemap(), LOCK_EX); } unlink($js_path . '.lock'); return $out; }
/** */ public function set($key, $data, $lifetime = 0) { $filename = $this->_keyToFile($key, true); $tmp_file = Horde_Util::getTempFile('HordeCache', true, $this->_params['dir']); if (isset($this->_params['umask'])) { chmod($tmp_file, 0666 & ~$this->_params['umask']); } if (file_put_contents($tmp_file, $data) === false) { throw new Horde_Cache_Exception('Cannot write to cache directory ' . $this->_params['dir']); } @rename($tmp_file, $filename); if ($lifetime && ($fp = @fopen(dirname($filename) . '/' . self::GC_FILE, 'a'))) { // This may result in duplicate entries in GC_FILE, but we // will take care of these whenever we do GC and this is quicker // than having to check every time we access the file. fwrite($fp, $filename . "\t" . (time() + $lifetime) . "\n"); fclose($fp); } }
/** * Stores changed preferences in the storage backend. * * @param Horde_Prefs_Scope $scope_ob The scope object. * * @throws Horde_Prefs_Exception */ public function store($scope_ob) { $this->_loadFileCache(); /* Driver has no support for storing locked status. */ foreach ($scope_ob->getDirty() as $name) { $value = $scope_ob->get($name); if (is_null($value)) { unset($this->_fileCache[$scope_ob->scope][$name]); } else { $this->_fileCache[$scope_ob->scope][$name] = $value; } } $tmp_file = Horde_Util::getTempFile('PrefsFile', true, $this->_params['directory']); if (file_put_contents($tmp_file, serialize($this->_fileCache)) === false || @rename($tmp_file, $this->_fullpath) === false) { throw new Horde_Prefs_Exception(sprintf('Write of preferences to %s failed', $this->_fullpath)); } }
/** * Saves image data to file. * * If $data is false, saves current image data after performing any pending * operations on the data. If $data contains raw image data, saves that * data to file without regard for the current image data. * * @param string String of binary image data. * * @return string Path to temporary file. */ public function toFile($data = null) { $tmp = Horde_Util::getTempFile('img', false, $this->_tmpdir); $fp = fopen($tmp, 'wb'); fwrite($fp, $data ?: $this->raw()); fclose($fp); return $tmp; }
/** * Method to execute a raw command directly in convert. * * Useful for executing more involved operations that may require multiple * convert commands piped into each other for example. Really designed for * use by Im based Horde_Image_Effect objects. * * The input and output files are quoted and substituted for __FILEIN__ and * __FILEOUT__ respectfully. In order to support piped convert commands, * the path to the convert command is substitued for __CONVERT__ (but the * initial convert command is added automatically). * * @param string $cmd The command string, with substitutable tokens * @param array $values Any values that should be substituted for tokens. */ public function executeConvertCmd($cmd, $values = array()) { // First, get a temporary file for the input if (strpos($cmd, '__FILEIN__') !== false) { $tmpin = $this->toFile($this->_data); } else { $tmpin = ''; } // Now an output file $tmpout = Horde_Util::getTempFile('img', false, $this->_tmpdir); // Substitue them in the cmd string $cmd = str_replace(array('__FILEIN__', '__FILEOUT__', '__CONVERT__'), array('"' . $tmpin . '"', '"' . $tmpout . '"', $this->_convert), $cmd); //TODO: See what else needs to be replaced. $cmd = $this->_convert . ' ' . $cmd . ' 2>&1'; // Log it $this->_logDebug(sprintf("convert command executed by Horde_Image_im::executeConvertCmd(): %s", $cmd)); exec($cmd, $output, $retval); if ($retval) { $this->_logErr(sprintf("Error running command: %s", $cmd . "\n" . implode("\n", $output))); } $this->_data = file_get_contents($tmpout); @unlink($tmpin); @unlink($tmpout); }
/** * Downloads a timezone database. * * @throws Horde_Timezone_Exception if downloading fails. */ protected function _download() { $url = @parse_url($this->_params['location']); if (!isset($url['scheme'])) { throw new Horde_Timezone_Exception('"location" parameter is missing an URL scheme.'); } if (!in_array($url['scheme'], array('http', 'ftp', 'file'))) { throw new Horde_Timezone_Exception(sprintf('Unsupported URL scheme "%s"', $url['scheme'])); } if ($url['scheme'] == 'http') { if (isset($this->_params['client'])) { $client = $this->_params['client']; } else { $client = new Horde_Http_Client(); } $response = $client->get($this->_params['location']); $this->_tmpfile = Horde_Util::getTempFile('', true, isset($this->_params['temp']) ? $this->_params['temp'] : ''); stream_copy_to_stream($response->getStream(), fopen($this->_tmpfile, 'w')); return; } if ($url['scheme'] == 'ftp') { try { $vfs = new Horde_Vfs_Ftp(array('hostspec' => $url['host'], 'username' => 'anonymous', 'password' => 'anonymous', 'pasv' => true)); $this->_tmpfile = $vfs->readFile(dirname($url['path']), basename($url['path'])); } catch (Horde_Vfs_Exception $e) { throw new Horde_Timezone_Exception($e); } } else { $this->_tmpfile = $this->_params['location']; if (!is_readable($this->_tmpfile)) { $e = new Horde_Timezone_Exception(sprintf('Unable to open file %s.', $this->_params['location'])); if (isset($php_errormsg)) { $e->details = $php_errormsg; } throw $e; } } }
/** * Adds an attachment to a ticket. * * @param integer $ticket_id The ticket number. * @param string $name The name of the attachment. * @param string $data The attachment data. * * @throws Whups_Exception */ public function addAttachment($ticket_id, $name, $data) { $ticket_id = (int) $ticket_id; if (empty($ticket_id)) { throw new Whups_Exception(_("Invalid Ticket Id")); } $ticket = Whups_Ticket::makeTicket($ticket_id); if (!strlen($name) || !strlen($data)) { throw new Whups_Exception(_("Empty attachment")); } $tmp_name = Horde_Util::getTempFile('whups', true, $GLOBALS['conf']['tmpdir']); $fp = fopen($tmp_name, 'wb'); fwrite($fp, $data); fclose($fp); $ticket->change('attachment', array('name' => $name, 'tmp_name' => $tmp_name)); $ticket->commit(); }
/** * Create a temporary file that will be deleted at the end of this * process. * * @param string $descrip Description string to use in filename. * @param boolean $delete Delete the file automatically? * * @return string Filename of a temporary file. */ protected function _createTempFile($descrip = 'horde-crypt', $delete = true) { return Horde_Util::getTempFile($descrip, $delete, $this->_tempdir, true); }
/** * Returns a temporary file name. * * @return string A temp filename. */ protected function _getTempFile() { return ($temp_file = $this->getConfigParam('temp_file')) ? call_user_func($temp_file, __CLASS__) : Horde_Util::getTempFile(__CLASS__); }
/** * TODO * * @throws Horde_Vcs_Exception */ public function annotate($fileob, $rev) { $this->assertValidRevision($rev); $tmpfile = Horde_Util::getTempFile('vc', true, $this->_paths['temp']); $where = $fileob->getSourcerootPath(); $language = getenv('LC_MESSAGES'); putenv('LC_MESSAGES=C'); $proc = proc_open(escapeshellcmd($this->getPath('cvs')) . ' -n server', array(array('pipe', 'r'), array('pipe', 'w'), array('pipe', 'w')), $pipes); if (!$proc) { throw new Horde_Vcs_Exception('Unable to annotate'); } $out = array('Root ' . $this->sourceroot, 'Valid-responses ok error Valid-requests Checked-in Updated Merged Removed M E', 'UseUnchanged', 'Argument -r', 'Argument ' . $rev, 'Argument ' . $where); $dirs = explode('/', dirname($where)); while (count($dirs)) { $out[] = 'Directory ' . implode('/', $dirs); $out[] = $this->sourceroot . '/' . implode('/', $dirs); array_pop($dirs); } $out[] = 'Directory .'; $out[] = $this->sourceroot; $out[] = 'annotate'; foreach ($out as $line) { fwrite($pipes[0], "{$line}\n"); } fclose($pipes[0]); putenv('LC_MESSAGES=' . $language); stream_set_blocking($pipes[2], 0); if ($error = stream_get_contents($pipes[2])) { fclose($pipes[2]); fclose($pipes[1]); proc_close($proc); throw new Horde_Vcs_Exception($error); } fclose($pipes[2]); $lines = array(); $line = fgets($pipes[1]); // Windows versions of cvs always return $where with forwards slashes. if (VC_WINDOWS) { $where = str_replace(DIRECTORY_SEPARATOR, '/', $where); } while ($line && !preg_match("|^E\\s+Annotations for {$where}|", $line)) { $line = fgets($pipes[1]); } if (!$line) { fclose($pipes[1]); proc_close($proc); throw new Horde_Vcs_Exception('Unable to annotate'); } $lineno = 1; while ($line = fgets($pipes[1])) { if (preg_match('/^M\\s+([\\d\\.]+)\\s+\\((.+)\\s+(\\d+-\\w+-\\d+)\\):.(.*)$/', $line, $regs)) { $lines[] = array('rev' => $regs[1], 'author' => trim($regs[2]), 'date' => $regs[3], 'line' => $regs[4], 'lineno' => $lineno++); } } fclose($pipes[1]); proc_close($proc); return $lines; }
/** * Update the Application.php or Bundle.php file in case it exists. * * @param string $new_version Version string that should be added. * * @return NULL */ public function updateApplication($version) { if ($application = $this->applicationFileExists()) { $tmp = Horde_Util::getTempFile(); $oldmode = fileperms($application); $oldfp = fopen($application, 'r'); $newfp = fopen($tmp, 'w'); while ($line = fgets($oldfp)) { $line = preg_replace('/public \\$version = \'[^\']*\';/', 'public \\$version = \'' . $version . '\';', $line); fwrite($newfp, $line); } fclose($oldfp); fclose($newfp); chmod($tmp, $oldmode); system("mv -f {$tmp} {$application}"); } elseif ($bundle = $this->bundleFileExists()) { $tmp = Horde_Util::getTempFile(); $oldmode = fileperms($bundle); $oldfp = fopen($bundle, 'r'); $newfp = fopen($tmp, 'w'); while ($line = fgets($oldfp)) { $line = preg_replace('/const VERSION = \'[^\']*\';/', 'const VERSION = \'' . $version . '\';', $line); fwrite($newfp, $line); } fclose($oldfp); fclose($newfp); chmod($tmp, $oldmode); system("mv -f {$tmp} {$bundle}"); } }
public function sendFixture($infile, $outfile, $user, $client, $from, $to, $host, $params = array()) { $_SERVER['argv'] = array($_SERVER['argv'][0], '--sender=' . $from, '--recipient=' . $to, '--user='******'--host=' . $host, '--client=' . $client); $in = file_get_contents($infile, 'r'); $tmpfile = Horde_Util::getTempFile('KolabFilterTest'); $tmpfh = @fopen($tmpfile, 'w'); if (empty($params['unmodified_content'])) { @fwrite($tmpfh, sprintf($in, $from, $to)); } else { @fwrite($tmpfh, $in); } @fclose($tmpfh); $inh = @fopen($tmpfile, 'r'); /* Setup the class */ if (empty($params['incoming'])) { require_once 'Horde/Kolab/Filter/Content.php'; $parser = new Horde_Kolab_Filter_Content(); } else { require_once 'Horde/Kolab/Filter/Incoming.php'; $parser = new Horde_Kolab_Filter_Incoming(); } ob_start(); /* Parse the mail */ $result = $parser->parse($inh, 'echo'); if (empty($params['error'])) { $this->assertNoError($result); $this->assertTrue(empty($result)); $output = ob_get_contents(); ob_end_clean(); $out = file_get_contents($outfile); $replace = array('/^Received:.*$/m' => '', '/^Date:.*$/m' => '', '/DTSTAMP:.*$/m' => '', '/^--+=.*$/m' => '----', '/^Message-ID.*$/m' => '----', '/boundary=.*$/m' => '----', '/\\s/' => ''); foreach ($replace as $pattern => $replacement) { $output = preg_replace($pattern, $replacement, $output); $out = preg_replace($pattern, $replacement, $out); } if (empty($params['unmodified_content'])) { $this->assertEquals(sprintf($out, $from, $to), $output); } else { $this->assertEquals($out, $output); } } else { $this->assertError($result, $params['error']); } }
/** * Creates a temporary filename for the lifetime of the script, and * (optionally) registers it to be deleted at request shutdown. * * @param string $prefix Prefix to make the temporary name more * recognizable. * @param boolean $delete Delete the file at the end of the * request? * @param string $dir Directory to create the temporary file * in. * @param boolean $secure If deleting file, should we securely * delete the file? * @param boolean $session_remove Delete this file when session is * destroyed? * * @return string Returns the full path-name to the temporary file or * false if a temporary file could not be created. */ public static function getTempFile($prefix = 'Horde', $delete = true, $dir = '', $secure = false, $session_remove = false) { if (empty($dir) || !is_dir($dir)) { $dir = self::getTempDir(); } $tmpfile = Horde_Util::getTempFile($prefix, $delete, $dir, $secure); if ($session_remove) { $gcfiles = $GLOBALS['session']->get('horde', 'gc_tempfiles', Horde_Session::TYPE_ARRAY); $gcfiles[] = $tmpfile; $GLOBALS['session']->set('horde', 'gc_tempfiles', $gcfiles); } return $tmpfile; }
/** * Return the package.xml file from the archive. * * Function copied from Pirum. * * (c) 2009 - 2011 Fabien Potencier * * @return string The path to the package.xml file. */ private function _loadPackageFromArchive() { if (!function_exists('gzopen')) { $tmpDir = Horde_Util::createTempDir(); copy($this->_archive, $tmpDir . '/archive.tgz'); system('cd ' . $tmpDir . ' && tar zxpf archive.tgz'); if (!is_file($tmpDir . '/package.xml')) { throw new Horde_Component_Exception(sprintf('Found no package.xml in "%s"!', $this->_archive)); } return $tmpDir . '/package.xml'; } $gz = gzopen($this->_archive, 'r'); if ($gz === false) { throw new Horde_Component_Exception(sprintf('Failed extracting archive "%s"!', $this->_archive)); } $tar = ''; while (!gzeof($gz)) { $tar .= gzread($gz, 10000); } gzclose($gz); while (strlen($tar)) { $filename = rtrim(substr($tar, 0, 100), chr(0)); $filesize = octdec(rtrim(substr($tar, 124, 12), chr(0))); if ($filename != 'package.xml') { $offset = $filesize % 512 == 0 ? $filesize : $filesize + (512 - $filesize % 512); $tar = substr($tar, 512 + $offset); continue; } $checksum = octdec(rtrim(substr($tar, 148, 8), chr(0))); $cchecksum = 0; $tar = substr_replace($tar, ' ', 148, 8); for ($i = 0; $i < 512; $i++) { $cchecksum += ord($tar[$i]); } if ($checksum != $cchecksum) { throw new Horde_Component_Exception(sprintf('Invalid archive "%s"!', $this->_archive)); } $package = substr($tar, 512, $filesize); $tmpFile = Horde_Util::getTempFile(); file_put_contents($tmpFile, $package); return $tmpFile; } throw new Horde_Component_Exception(sprintf('Found no package.xml in "%s"!', $this->_archive)); }
/** * Add a change log entry to CHANGES * * @param string $entry Change log entry to add. * @param string $changes Path to the CHANGES file. * * @return NULL */ public function addChange($entry, $changes) { $tmp = Horde_Util::getTempFile(); $entry = Horde_String::wrap($entry, 79, "\n "); $oldfp = fopen($changes, 'r'); $newfp = fopen($tmp, 'w'); $counter = 0; while ($line = fgets($oldfp)) { if ($counter == 4) { fwrite($newfp, $entry . "\n"); } $counter++; fwrite($newfp, $line); } fclose($oldfp); fclose($newfp); system("mv -f {$tmp} {$changes}"); }
/** * Stores a file in the VFS from raw data. * * @param string $path The path to store the file in. * @param string $name The filename to use. * @param string $data The file data. * @param boolean $autocreate Automatically create directories? * * @throws Horde_Vfs_Exception */ public function writeData($path, $name, $data, $autocreate = false) { $tmpFile = Horde_Util::getTempFile('vfs'); file_put_contents($tmpFile, $data); try { $this->write($path, $name, $tmpFile, $autocreate); unlink($tmpFile); } catch (Horde_Vfs_Exception $e) { unlink($tmpFile); throw $e; } }
/** * Copies a file through the backend. * * @param string $path The path of the original file. * @param string $name The name of the original file. * @param string $dest The name of the destination directory. * @param boolean $autocreate Auto-create the directory if it doesn't * exist? * * @throws Horde_Vfs_Exception */ public function copy($path, $name, $dest, $autocreate = false) { $this->_checkDestination($path, $dest); $this->_connect(); if ($autocreate) { $this->autocreatePath($dest); } foreach ($this->listFolder($dest, null, true) as $file) { if ($file['name'] == $name) { throw new Horde_Vfs_Exception(sprintf('%s already exists.', $this->_getPath($dest, $name))); } } if ($this->isFolder($path, $name)) { $this->_copyRecursive($path, $name, $dest); } else { $tmpFile = Horde_Util::getTempFile('vfs'); if (!$this->_recv($this->_getPath($path, $name), $tmpFile)) { throw new Horde_Vfs_Exception(sprintf('Failed to copy from "%s".', $this->_getPath($path, $name))); } clearstatcache(); $this->_checkQuotaWrite('file', $tmpFile); if (!$this->_send($tmpFile, $this->_getPath($dest, $name))) { throw new Horde_Vfs_Exception(sprintf('Failed to copy to "%s".', $this->_getPath($dest, $name))); } } }
/** * Retrieves a file from the VFS as an on-disk local file. * * This function provides a file on local disk with the data of a VFS file * in it. This file <em>cannot</em> be modified! The behavior if you do * modify it is undefined. It will be removed at the end of the request. * * @param string $path The pathname to the file. * @param string $name The filename to retrieve. * * @return string A local filename. * @throws Horde_Vfs_Exception */ public function readFile($path, $name) { // Create a temporary file and register it for deletion at the // end of this request. if (!($localFile = Horde_Util::getTempFile('vfs'))) { throw new Horde_Vfs_Exception('Unable to create temporary file.'); } if (is_callable(array($this, 'readStream'))) { // Use a stream from the VFS if possible, to avoid reading all data // into memory. $stream = $this->readStream($path, $name); if (!($localStream = fopen($localFile, 'w'))) { throw new Horde_Vfs_Exception('Unable to open temporary file.'); } stream_copy_to_stream($stream, $localStream); fclose($localStream); } else { // We have to read all of the data in one shot. $data = $this->read($path, $name); file_put_contents($localFile, $data); } // $localFile now has $path/$name's data in it. return $localFile; }
/** * Returns the array of differences. * * @param array $from_lines lines of text from old file * @param array $to_lines lines of text from new file * * @return array all changes made (array with Horde_Text_Diff_Op_* objects) */ public function diff($from_lines, $to_lines) { array_walk($from_lines, array('Horde_Text_Diff', 'trimNewlines')); array_walk($to_lines, array('Horde_Text_Diff', 'trimNewlines')); // Execute gnu diff or similar to get a standard diff file. $from_file = Horde_Util::getTempFile('Horde_Text_Diff'); $to_file = Horde_Util::getTempFile('Horde_Text_Diff'); $fp = fopen($from_file, 'w'); fwrite($fp, implode("\n", $from_lines)); fclose($fp); $fp = fopen($to_file, 'w'); fwrite($fp, implode("\n", $to_lines)); fclose($fp); $diff = shell_exec($this->_diffCommand . ' ' . $from_file . ' ' . $to_file); unlink($from_file); unlink($to_file); if (is_null($diff)) { // No changes were made return array(new Horde_Text_Diff_Op_Copy($from_lines)); } $from_line_no = 1; $to_line_no = 1; $edits = array(); // Get changed lines by parsing something like: // 0a1,2 // 1,2c4,6 // 1,5d6 preg_match_all('#^(\\d+)(?:,(\\d+))?([adc])(\\d+)(?:,(\\d+))?$#m', $diff, $matches, PREG_SET_ORDER); foreach ($matches as $match) { if (!isset($match[5])) { // This paren is not set every time (see regex). $match[5] = false; } if ($match[3] == 'a') { $from_line_no--; } if ($match[3] == 'd') { $to_line_no--; } if ($from_line_no < $match[1] || $to_line_no < $match[4]) { // copied lines assert('$match[1] - $from_line_no == $match[4] - $to_line_no'); $edits[] = new Horde_Text_Diff_Op_Copy($this->_getLines($from_lines, $from_line_no, $match[1] - 1), $this->_getLines($to_lines, $to_line_no, $match[4] - 1)); } switch ($match[3]) { case 'd': // deleted lines $edits[] = new Horde_Text_Diff_Op_Delete($this->_getLines($from_lines, $from_line_no, $match[2])); $to_line_no++; break; case 'c': // changed lines $edits[] = new Horde_Text_Diff_Op_Change($this->_getLines($from_lines, $from_line_no, $match[2]), $this->_getLines($to_lines, $to_line_no, $match[5])); break; case 'a': // added lines $edits[] = new Horde_Text_Diff_Op_Add($this->_getLines($to_lines, $to_line_no, $match[5])); $from_line_no++; break; } } if (!empty($from_lines)) { // Some lines might still be pending. Add them as copied $edits[] = new Horde_Text_Diff_Op_Copy($this->_getLines($from_lines, $from_line_no, $from_line_no + count($from_lines) - 1), $this->_getLines($to_lines, $to_line_no, $to_line_no + count($to_lines) - 1)); } return $edits; }
/** * Takes all necessary actions for the given import step, parameters and * form values and returns the next necessary step. * * @param integer $action The current step. One of the IMPORT_* constants. * @param array $param An associative array containing needed * parameters for the current step. Keys for this * driver: * - check_charset: (boolean) Do some checks to see if the correct * charset has been provided. Throws charset exception * on error. * - import_mapping: TODO * * @return mixed Either the next step as an integer constant or imported * data set after the final step. * @throws Horde_Data_Exception * @throws Horde_Data_Exception_Charset */ public function nextStep($action, array $param = array()) { switch ($action) { case Horde_Data::IMPORT_FILE: parent::nextStep($action, $param); /* Move uploaded file so that we can read it again in the next step after the user gave some format details. */ $file_name = $_FILES['import_file']['tmp_name']; if (($file_data = file_get_contents($file_name)) === false) { throw new Horde_Data_Exception(Horde_Data_Translation::t("The uploaded file could not be saved.")); } /* Do charset checking now, if requested. */ if (isset($param['check_charset'])) { $charset = isset($this->_vars->charset) ? Horde_String::lower($this->_vars->charset) : 'utf-8'; switch ($charset) { case 'utf-8': $error = !Horde_String::validUtf8($file_data); break; default: $error = $file_data != Horde_String::convertCharset(Horde_String::convertCharset($file_data, $charset, 'UTF-8'), 'UTF-8', $charset); break; } if ($error) { $e = new Horde_Data_Exception_Charset(Horde_Data_Translation::t("Incorrect charset given for the data.")); $e->badCharset = $charset; throw $e; } } $this->storage->set('charset', $this->_vars->charset); $this->storage->set('file_data', $file_data); /* Read the file's first two lines to show them to the user. */ $first_lines = ''; if ($fp = @fopen($file_name, 'r')) { for ($line_no = 1, $line = fgets($fp); $line_no <= 3 && $line; $line_no++, $line = fgets($fp)) { $line = Horde_String::convertCharset($line, $this->_vars->charset, 'UTF-8'); $first_lines .= Horde_String::truncate($line); if (Horde_String::length($line) > 100) { $first_lines .= "\n"; } } } $this->storage->set('first_lines', $first_lines); /* Import the first line to guess the number of fields. */ if ($first_lines) { rewind($fp); $line = self::getCsv($fp); if ($line) { $this->storage->set('fields', count($line)); } } return Horde_Data::IMPORT_CSV; case Horde_Data::IMPORT_CSV: $this->storage->set('header', $this->_vars->header); $import_mapping = array(); if (isset($param['import_mapping'])) { $import_mapping = $param['import_mapping']; } $file_name = Horde_Util::getTempFile('import'); file_put_contents($file_name, $this->storage->get('file_data')); $this->storage->set('data', $this->importFile($file_name, $this->_vars->header, $this->_vars->sep, $this->_vars->quote, $this->_vars->fields, $import_mapping, $this->storage->get('charset'), $this->storage->get('crlf'))); $this->storage->set('map'); return Horde_Data::IMPORT_MAPPED; default: return parent::nextStep($action, $param); } }
/** * Takes all necessary actions for the given import step, parameters and * form values and returns the next necessary step. * * @param integer $action The current step. One of the IMPORT_* constants. * @param array $param An associative array containing needed * parameters for the current step. * * @return mixed Either the next step as an integer constant or imported * data set after the final step. * @throws Horde_Data_Exception */ public function nextStep($action, array $param = array()) { switch ($action) { case Horde_Data::IMPORT_FILE: parent::nextStep($action, $param); $format = $this->storage->get('format'); if (in_array($format, array('mulberry', 'pine'))) { $filedata = $this->importFile($_FILES['import_file']['tmp_name']); switch ($format) { case 'mulberry': $appKeys = array('alias', 'name', 'email', 'company', 'workAddress', 'workPhone', 'homePhone', 'fax', 'notes'); $dataKeys = array(0, 1, 2, 3, 4, 5, 6, 7, 9); break; case 'pine': $appKeys = array('alias', 'name', 'email', 'notes'); $dataKeys = array(0, 1, 2, 4); break; } foreach ($appKeys as $key => $app) { $map[$dataKeys[$key]] = $app; } $data = array(); foreach ($filedata as $row) { $hash = array(); switch ($format) { case 'mulberry': if (preg_match("/^Grp:/", $row[0]) || empty($row[1])) { continue; } $row[1] = preg_replace('/^([^,"]+),\\s*(.*)$/', '$2 $1', $row[1]); foreach ($dataKeys as $key) { if (array_key_exists($key, $row)) { $hash[$key] = stripslashes(preg_replace('/\\\\r/', "\n", $row[$key])); } } break; case 'pine': if (count($row) < 3 || preg_match("/^#DELETED/", $row[0]) || preg_match("/[()]/", $row[2])) { continue; } $row[1] = preg_replace('/^([^,"]+),\\s*(.*)$/', '$2 $1', $row[1]); /* Address can be a full RFC822 address */ $addr_ob = new Horde_Mail_Rfc822_Address($row[2]); if (!$addr_ob->valid) { continue; } $row[2] = $addr_ob->bare_address; if (empty($row[1]) && !is_null($addr_ob->personal)) { $row[1] = $addr_ob->personal; } foreach ($dataKeys as $key) { if (array_key_exists($key, $row)) { $hash[$key] = $row[$key]; } } break; } $data[] = $hash; } $this->storage->set('data', $data); $this->storage->set('map', $map); return $this->nextStep(Horde_Data::IMPORT_DATA, $param); } /* Store uploaded file data so that we can read it again in the * next step after the user gives some format details. */ try { $this->_browser->wasFileUploaded('import_file', Horde_Data_Translation::t("TSV file")); } catch (Horde_Browser_Exception $e) { throw new Horde_Data_Exception($e); } $file_name = $_FILES['import_file']['tmp_name']; if (($file_data = file_get_contents($file_name)) === false) { throw new Horde_Data_Exception(Horde_Data_Translation::t("The uploaded file could not be saved.")); } $this->storage->set('file_data', $file_data); /* Read the file's first two lines to show them to the user. */ $first_lines = ''; if ($fp = @fopen($file_name, 'r')) { $line_no = 1; while ($line_no < 3 && ($line = fgets($fp))) { $newline = Horde_String::length($line) > 100 ? "\n" : ''; $first_lines .= substr($line, 0, 100) . $newline; ++$line_no; } } $this->storage->set('first_lines', $first_lines); return Horde_Data::IMPORT_TSV; case Horde_Data::IMPORT_TSV: $file_name = Horde_Util::getTempFile('import'); file_put_contents($file_name, $this->storage->get('file_data')); $this->storage->set('header', $this->_vars->header); $this->storage->set('data', $this->importFile($file_name, $this->storage->get('header'))); $this->storage->set('map'); return Horde_Data::IMPORT_MAPPED; } return parent::nextStep($action, $param); }