function handle() { global $conf; if (isset($_POST['sqlite_rename'])) { $path = $conf['metadir'] . '/' . $_REQUEST['db']; if (io_rename($path . '.sqlite', $path . '.sqlite3')) { msg('Renamed database file succesfull!', 1); //set to new situation $_REQUEST['version'] = 'sqlite3'; } else { msg('Renaming database file fails!', -1); } } elseif (isset($_POST['sqlite_convert'])) { /** @var $DBI helper_plugin_sqlite */ $DBI =& plugin_load('helper', 'sqlite'); $time_start = microtime(true); if ($dumpfile = $DBI->dumpDatabase($_REQUEST['db'], DOKU_EXT_SQLITE)) { msg('Database temporary dumped to file: ' . hsc($dumpfile) . '. Now loading in new database...', 1); if (!$DBI->fillDatabaseFromDump($_REQUEST['db'], $dumpfile)) { msg('Conversion failed!', -1); return false; } //TODO delete dumpfile //return @unlink($dumpfile); //TODO delete old sqlite2-db // return @unlink($conf['metadir'].'/'.$_REQUEST['db'].'.sqlite'); msg('Conversion succeed!', 1); //set to new situation $_REQUEST['version'] = 'sqlite3'; } $time_end = microtime(true); $time = $time_end - $time_start; msg('Database "' . hsc($_REQUEST['db']) . '" converted from sqlite 2 to 3 in ' . $time . ' seconds.', 0); } }
/** * Writes the Configuration if it is being set */ public function writeCronSettings() { global $conf; if (!$this->configFile) { // Nothing has changed. return true; } // backup current file (remove any existing backup) if (@file_exists($this->configFile)) { if (@file_exists($this->configFile . '.bak')) { @unlink($this->configFile . '.bak'); } if (!io_rename($this->configFile, $this->configFile . '.bak')) { return false; } } if (!($fh = @fopen($this->configFile, 'wb'))) { io_rename($this->configFile . '.bak', $this->configFile); // problem opening, restore the backup return false; } $out = $this->cronHeading(); $out .= $this->recurseSettingsToOut($this->configuration); $out .= $this->cronFooter(); // Finally write it out. @fwrite($fh, $out); fclose($fh); if ($conf['fperm']) { chmod($this->configFile, $conf['fperm']); } return true; }
function test_rename_to_new_page() { $newid = 'new_id_1'; $oldpid = $this->indexer->getPID($this->old_id); $this->assertTrue($this->indexer->renamePage($this->old_id, $newid), 'Renaming the page to a new id failed'); io_rename(wikiFN($this->old_id), wikiFN($newid)); $this->assertNotEquals($this->indexer->getPID($this->old_id), $oldpid, 'PID for the old page unchanged after rename.'); $this->assertEquals($this->indexer->getPID($newid), $oldpid, 'New page has not the old pid.'); $query = array('old'); $this->assertEquals(array('old' => array($newid => 1)), $this->indexer->lookup($query), '"Old" doesn\'t find the new page'); }
public function checkIfCacheFileExistsForFileWithPattern($file, $pattern) { if (!@file_exists($file)) { // If the cache File does not exist, move the newly created one over ... $newCacheFile = mediaFN($this->getSpecialExportFileName($this->settings->origZipFile, $pattern)); if (!@file_exists($newCacheFile)) { $this->debug->message("The export must have gone wrong. The cached file does not exist.", array("pattern" => $pattern, "original File" => $this->settings->origZipFile, "expected cached file" => $newCacheFile), 3); } $status = io_rename($newCacheFile, $file); $this->debug->message("had to move another original file over. Did it work? " . ($status ? 'Yes, it did.' : 'No, it did not.'), null, 2); } }
function save_settings($id, $header = '', $backup = true) { global $conf; if ($this->locked) { return false; } # $file = eval('return '.$this->_local_file.';'); $file = $this->_local_files[0]; // backup current file (remove any existing backup) if (@file_exists($file) && $backup) { if (@file_exists($file . '.bak')) { @unlink($file . '.bak'); } if (!io_rename($file, $file . '.bak')) { return false; } } if (!($fh = @fopen($file, 'wb'))) { io_rename($file . '.bak', $file); // problem opening, restore the backup return false; } if (empty($header)) { $header = $this->_heading; } $out = $this->_out_header($id, $header); foreach ($this->setting as $setting) { $out .= $setting->out($this->_name, $this->_format); } $out .= $this->_out_footer(); @fwrite($fh, $out); fclose($fh); if ($conf['fperm']) { chmod($file, $conf['fperm']); } return true; }
/** * Save changed Metadata * * @author Sebastian Delmont <*****@*****.**> * @author Andreas Gohr <*****@*****.**> */ function save($fileName = "") { if ($fileName == "") { $tmpName = tempnam(dirname($this->_fileName), '_metatemp_'); $this->_writeJPEG($tmpName); if (@file_exists($tmpName)) { return io_rename($tmpName, $this->_fileName); } } else { return $this->_writeJPEG($fileName); } return false; }
/** * Write a line into the index. * * @param string $idx name of the index * @param string $suffix subpart identifier * @param int $id the line number * @param string $line line to write * @return bool If saving succeeded * @author Tom N Harris <*****@*****.**> */ protected function saveIndexKey($idx, $suffix, $id, $line) { global $conf; if (substr($line, -1) != "\n") { $line .= "\n"; } $fn = $conf['indexdir'] . '/' . $idx . $suffix; $fh = @fopen($fn . '.tmp', 'w'); if (!$fh) { return false; } $ih = @fopen($fn . '.idx', 'r'); if ($ih) { $ln = -1; while (($curline = fgets($ih)) !== false) { fwrite($fh, ++$ln == $id ? $line : $curline); } if ($id > $ln) { while ($id > ++$ln) { fwrite($fh, "\n"); } fwrite($fh, $line); } fclose($ih); } else { $ln = -1; while ($id > ++$ln) { fwrite($fh, "\n"); } fwrite($fh, $line); } fclose($fh); if (isset($conf['fperm'])) { chmod($fn . '.tmp', $conf['fperm']); } io_rename($fn . '.tmp', $fn . '.idx'); return true; }
public function handle_action_act_preprocess(Doku_Event &$event, $param) { global $ID; global $TEXT; global $ACT; global $SUM; global $RANGE; global $REV; $act = $event->data; if ($act != 'dokutranslate_review') { $act = act_clean($act); $act = act_permcheck($act); } # Ignore drafts if the page is being translated # FIXME: Find a way to save $_REQUEST['parid'] into the draft if (@file_exists(metaFN($ID, '.translate')) && in_array($act, array('draft', 'recover'))) { act_draftdel('draftdel'); $ACT = $act = 'edit'; } if ($act == 'save') { # Take over save action if translation is in progress # or we're starting it if (!@file_exists(metaFN($ID, '.translate')) && empty($_REQUEST['translate'])) { return; } if (!checkSecurityToken()) { return; } # We're starting a translation if (!@file_exists(metaFN($ID, '.translate')) && !empty($_REQUEST['translate'])) { # Check if the user has permission to start # translation in this namespace if (!isModerator($ID)) { return; } # Take the event over $event->stopPropagation(); $event->preventDefault(); # Save the data but exit if it fails $ACT = act_save($act); if ($ACT != 'show') { return; } # Page was deleted, exit if (!@file_exists(wikiFN($ID))) { return; } # Prepare data path $datapath = dataPath($ID); io_mkdir_p($datapath, 0755, true); # Backup the original page io_rename(wikiFN($ID), $datapath . '/orig.txt'); # Backup old revisions $revisions = allRevisions($ID); foreach ($revisions as $rev) { $tmp = wikiFN($ID, $rev); io_rename($tmp, $datapath . '/' . basename($tmp)); } # Backup meta files $metas = metaFiles($ID); foreach ($metas as $f) { io_rename($f, $datapath . '/' . basename($f)); } # Generate empty page to hold translated text $data = getCleanInstructions($datapath . '/orig.txt'); saveWikiText($ID, genTranslateFile($data), $SUM, $_REQUEST['minor']); $translateMeta = genMeta(count($data)); # create meta file for current translation state io_saveFile(metaFN($ID, '.translate'), serialize($translateMeta)); # create separate meta file for translation history io_saveFile(metaFN($ID, '.translateHistory'), serialize(array('current' => $translateMeta))); } else { # Translation in progress, take the event over $event->preventDefault(); # Save the data but exit if it fails $ACT = act_save($act); # Save failed, exit if ($ACT != 'show') { return; } # Save successful, update translation metadata $lastrev = getRevisions($ID, 0, 1, 1024); updateMeta($ID, getParID(), $lastrev[0]); } } else { if ($act == 'revert') { # Take over save action if translation is in progress if (!@file_exists(metaFN($ID, '.translate'))) { return; } if (!checkSecurityToken()) { return; } # Translation in progress, take the event over $event->preventDefault(); # Save the data but exit if it fails $revert = $REV; $ACT = act_revert($act); # Revert failed, exit if ($ACT != 'show') { return; } # Revert successful, update translation metadata $lastrev = getRevisions($ID, 0, 1, 1024); updateMeta($ID, getParID(), $lastrev[0], $revert); } else { if (in_array($act, array('edit', 'preview'))) { if (!@file_exists(metaFN($ID, '.translate')) || isset($TEXT)) { return; } $parid = getParID(); $instructions = p_cached_instructions(wikiFN($ID)); $separators = array(); # Build array of paragraph separators foreach ($instructions as $ins) { if ($ins[0] == 'plugin' && $ins[1][0] == 'dokutranslate' && in_array($ins[1][1][0], array(DOKU_LEXER_ENTER, DOKU_LEXER_SPECIAL, DOKU_LEXER_EXIT))) { $separators[] = $ins[1][1]; } } # Validate paragraph ID if ($parid >= count($separators) - 1) { $parid = 0; } # Build range for paragraph $RANGE = strval($separators[$parid][2] + 1) . '-' . strval($separators[$parid + 1][1] - 1); } else { if ($act == 'dokutranslate_review') { # This action is mine $event->stopPropagation(); $event->preventDefault(); # Show the page when done $ACT = 'show'; # Load data $meta = unserialize(io_readFile(metaFN($ID, '.translateHistory'), false)); $parid = getParID(); $writeRev = empty($REV) ? 'current' : intval($REV); $writeRev = empty($meta[$writeRev][$parid]['changed']) ? $writeRev : $meta[$writeRev][$parid]['changed']; $user = $_SERVER['REMOTE_USER']; # Check for permission to write reviews if (!canReview($ID, $meta[$writeRev], $parid)) { return; } # Add review to meta array $data['message'] = $_REQUEST['review']; $data['quality'] = intval($_REQUEST['quality']); $data['incomplete'] = !empty($_REQUEST['incomplete']); $meta[$writeRev][$parid]['reviews'][$user] = $data; # Review applies to latest revision as well if (empty($REV) || $meta['current'][$parid]['changed'] == $writeRev) { $meta['current'][$parid]['reviews'][$user] = $data; io_saveFile(metaFN($ID, '.translate'), serialize($meta['current'])); } # Save metadata io_saveFile(metaFN($ID, '.translateHistory'), serialize($meta)); } } } } }
/** * Create a pagewords index from the existing index. * * @author Tom N Harris <*****@*****.**> */ function idx_upgradePageWords() { global $conf; $page_idx = idx_getIndex('page', ''); if (empty($page_idx)) { return; } $pagewords = array(); $len = count($page_idx); for ($n = 0; $n < $len; $n++) { $pagewords[] = array(); } unset($page_idx); $n = 0; foreach (idx_indexLengths($n) as $wlen) { $lines = idx_getIndex('i', $wlen); $len = count($lines); for ($wid = 0; $wid < $len; $wid++) { $wkey = "{$wlen}*{$wid}"; foreach (explode(':', trim($lines[$wid])) as $part) { if ($part == '') { continue; } list($doc, $cnt) = explode('*', $part); $pagewords[(int) $doc][] = $wkey; } } } $fn = $conf['indexdir'] . '/pageword'; $fh = @fopen($fn . '.tmp', 'w'); if (!$fh) { trigger_error("Failed to write word index", E_USER_ERROR); return false; } foreach ($pagewords as $line) { fwrite($fh, join(':', $line) . "\n"); } fclose($fh); if ($conf['fperm']) { chmod($fn . '.tmp', $conf['fperm']); } io_rename($fn . '.tmp', $fn . '.idx'); return true; }
/** * Append a PHP extension to a given file and adds an exit call * * This is used to migrate some old configfiles. An added PHP extension * ensures the contents are not shown to webusers even if .htaccess files * do not work * * @author Jan Decaluwe <*****@*****.**> */ function scriptify($file) { // checks if (!is_readable($file)) { return; } $fn = $file . '.php'; if (@file_exists($fn)) { return; } $fh = fopen($fn, 'w'); if (!$fh) { nice_die($fn . ' is not writable. Check your permission settings!'); } // write php exit hack first fwrite($fh, "# {$fn}\n"); fwrite($fh, '# <?php exit()?>' . "\n"); fwrite($fh, "# Don't modify the lines above\n"); fwrite($fh, "#\n"); // copy existing lines $lines = file($file); foreach ($lines as $line) { fwrite($fh, $line); } fclose($fh); //try to rename the old file io_rename($file, "{$file}.old"); }
/** * Read $dumpfile and try to add it to database. * A existing database is backuped first as e.g. dbname.copy2.sqlite3 * * @param string $dbname * @param string $dumpfile * @return bool true on succes */ public function fillDatabaseFromDump($dbname, $dumpfile) { global $conf; //backup existing stuff $dbf = $conf['metadir'] . '/' . $dbname; $dbext = $this->adapter->getFileextension(); $dbfile = $dbf . $dbext; if (@file_exists($dbfile)) { $i = 0; $backupdbfile = $dbfile; do { $i++; $backupdbfile = $dbf . ".copy{$i}" . $dbext; } while (@file_exists($backupdbfile)); io_rename($dbfile, $backupdbfile); } $init = false; if (!$this->adapter->initdb($dbname, $init, $sqliteupgrade = true)) { msg('Initialize db fails'); return false; } $sql = io_readFile($dumpfile, false); $sql = $this->SQLstring2array($sql); //skip preparing, because it interprets question marks as placeholders. return $this->doTransaction($sql, $sqlpreparing = false); }
/** * Executes the move op * * @param string $dir The root path of the files (e.g. $conf['metadir'] or $conf['olddir'] * @param string $src_ns The original namespace * @param string $src_name The original basename of the moved doc (empty for namespace moves) * @param string $dst_ns The namespace after the move * @param string $dst_name The basename after the move (empty for namespace moves) * @param string $extregex Regular expression for matching the extension of the file that shall be moved * @return bool If the files were moved successfully */ protected function execute($dir, $src_ns, $src_name, $dst_ns, $dst_name, $extregex) { $old_path = $dir; if ($src_ns != '') { $old_path .= '/' . utf8_encodeFN(str_replace(':', '/', $src_ns)); } $new_path = $dir; if ($dst_ns != '') { $new_path .= '/' . utf8_encodeFN(str_replace(':', '/', $dst_ns)); } $regex = '/^' . preg_quote(utf8_encodeFN($src_name)) . '(' . $extregex . ')$/u'; if (!is_dir($old_path)) { return true; } // no media files found $dh = @opendir($old_path); if ($dh) { while (($file = readdir($dh)) !== false) { if ($file == '.' || $file == '..') { continue; } $match = array(); if (is_file($old_path . '/' . $file) && preg_match($regex, $file, $match)) { if (!is_dir($new_path)) { if (!io_mkdir_p($new_path)) { msg('Creating directory ' . hsc($new_path) . ' failed.', -1); return false; } } if (!io_rename($old_path . '/' . $file, $new_path . '/' . utf8_encodeFN($dst_name . $match[1]))) { msg('Moving ' . hsc($old_path . '/' . $file) . ' to ' . hsc($new_path . '/' . utf8_encodeFN($dst_name . $match[1])) . ' failed.', -1); return false; } } } closedir($dh); } else { msg('Directory ' . hsc($old_path) . ' couldn\'t be opened.', -1); return false; } return true; }
/** * Execute a media file move/rename * * @param string $src original ID * @param string $dst new ID * @return bool true if the move was successfully executed */ public function moveMedia($src, $dst) { if (!$this->checkMedia($src, $dst)) { return false; } // get all pages using this media $affected_pages = idx_get_indexer()->lookupKey('relation_media', $src); $src_ns = getNS($src); $src_name = noNS($src); $dst_ns = getNS($dst); $dst_name = noNS($dst); // pass this info on to other plugins $eventdata = array('opts' => array('ns' => $src_ns, 'name' => $src_name, 'newns' => $dst_ns, 'newname' => $dst_name), 'affected_pages' => &$affected_pages, 'src_id' => $src, 'dst_id' => $dst); // give plugins the option to add their own meta files to the list of files that need to be moved // to the oldfiles/newfiles array or to adjust their own metadata, database, ... // and to add other pages to the affected pages $event = new Doku_Event('PLUGIN_MOVE_MEDIA_RENAME', $eventdata); if ($event->advise_before()) { /** @var helper_plugin_move_file $FileMover */ $FileMover = plugin_load('helper', 'move_file'); /** @var helper_plugin_move_rewrite $Rewriter */ $Rewriter = plugin_load('helper', 'move_rewrite'); // Move the Subscriptions & Indexes (new feature since Spring 2013 release) $Indexer = idx_get_indexer(); if (($idx_msg = $Indexer->renameMetaValue('relation_media', $src, $dst)) !== true) { msg(sprintf($this->getLang('indexerror'), $idx_msg), -1); return false; } if (!$FileMover->moveMediaMeta($src_ns, $src_name, $dst_ns, $dst_name)) { msg(sprintf($this->getLang('mediametamoveerror'), $src), -1); return false; } // prepare directory io_createNamespace($dst, 'media'); // move it FIXME this does not create a changelog entry! if (!io_rename(mediaFN($src), mediaFN($dst))) { msg(sprintf($this->getLang('mediamoveerror'), $src), -1); return false; } // clean up old ns io_sweepNS($src, 'mediadir'); // Move the old revisions if (!$FileMover->moveMediaAttic($src_ns, $src_name, $dst_ns, $dst_name)) { // it's too late to stop the move, so just display a message. msg(sprintf($this->getLang('mediaatticmoveerror'), $src), -1); } // Add meta data to all affected pages, so links get updated later foreach ($affected_pages as $id) { $Rewriter->setMoveMeta($id, $src, $dst, 'media'); } } $event->advise_after(); // store this for later use $this->affectedPages = $affected_pages; return true; }
/** * Internal function for moving and renaming meta/attic files between namespaces * * @param string $dir The root path of the files (e.g. $conf['metadir'] or $conf['olddir'] * @param array $opts Move options (used here: ns, newns, name, newname) * @param string $extregex Regular expression for matching the extension of the file that shall be moved * @return bool If the files were moved successfully */ private function move_files($dir, $opts, $extregex) { $old_path = $dir; if ($opts['ns'] != '') $old_path .= '/'.utf8_encodeFN(str_replace(':', '/', $opts['ns'])); $new_path = $dir; if ($opts['newns'] != '') $new_path .= '/'.utf8_encodeFN(str_replace(':', '/', $opts['newns'])); $regex = '/^'.preg_quote(utf8_encodeFN($opts['name'])).'('.$extregex.')$/u'; if (!is_dir($old_path)) return true; // no media files found $dh = @opendir($old_path); if($dh) { while(($file = readdir($dh)) !== false) { if (substr($file, 0, 1) == '.') continue; $match = array(); if (is_file($old_path.'/'.$file) && preg_match($regex, $file, $match)) { if (!is_dir($new_path)) { if (!io_mkdir_p($new_path)) { msg('Creating directory '.hsc($new_path).' failed.', -1); return false; } } if (!io_rename($old_path.'/'.$file, $new_path.'/'.utf8_encodeFN($opts['newname'].$match[1]))) { msg('Moving '.hsc($old_path.'/'.$file).' to '.hsc($new_path.'/'.utf8_encodeFN($opts['newname'].$match[1])).' failed.', -1); return false; } } } closedir($dh); } else { msg('Directory '.hsc($old_path).' couldn\'t be opened.', -1); return false; } return true; }
function _apply_moves(&$opts) { foreach ($opts['oldfiles'] as $i => $oldfile) { $newfile = $opts['newfiles'][$i]; $newdir = dirname($newfile); if (!io_mkdir_p($newdir)) { continue; } io_rename($oldfile, $newfile); } }
/** * Write a line to an index file. * * @author Tom N Harris <*****@*****.**> */ function idx_saveIndexLine($pre, $wlen, $idx, $line) { global $conf; if (substr($line, -1) != "\n") { $line .= "\n"; } $fn = $conf['indexdir'] . '/' . $pre . $wlen; $fh = @fopen($fn . '.tmp', 'w'); if (!$fh) { return false; } $ih = @fopen($fn . '.idx', 'r'); if ($ih) { $ln = -1; while (($curline = _freadline($ih)) !== false) { if (++$ln == $idx) { fwrite($fh, $line); } else { fwrite($fh, $curline); } } if ($idx > $ln) { fwrite($fh, $line); } fclose($ih); } else { fwrite($fh, $line); } fclose($fh); if ($conf['fperm']) { chmod($fn . '.tmp', $conf['fperm']); } io_rename($fn . '.tmp', $fn . '.idx'); return true; }
/** * Returns original filename if exists */ function _getOriginalFileName($id) { $metaFilePath = mediaMetaFN($id, '.filename'); $meta = unserialize(io_readFile($metaFilePath, false)); if (empty($meta['filename'])) { // check old meta file (for backward compatibility) $filename = parent::_getOriginalFileName($id); // move old meta file to media_meta directory if ($filename !== false) { $oldMetaFilePath = metaFN($id, '.filename'); io_rename($oldMetaFilePath, $metaFilePath); } return $filename; } else { return $this->common->_sanitizeFileName($meta['filename']); } }
/** * Get the list of lengths indexed in the wiki. * * Read the index directory or a cache file and returns * a sorted array of lengths of the words used in the wiki. * * @author YoBoY <*****@*****.**> */ protected function listIndexLengths() { global $conf; $cachename = $conf['indexdir'] . '/lengths'; clearstatcache(); if (@file_exists($cachename . '.idx')) { $lengths = @file($cachename . '.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); if ($lengths !== false) { $idx = array(); foreach ($lengths as $length) { $idx[] = (int) $length; } return $idx; } } $dir = @opendir($conf['indexdir']); if ($dir === false) { return array(); } $lengths[] = array(); while (($f = readdir($dir)) !== false) { if (substr($f, 0, 1) == 'i' && substr($f, -4) == '.idx') { $i = substr($f, 1, -4); if (is_numeric($i)) { $lengths[] = (int) $i; } } } closedir($dir); sort($lengths); // save this in a file $fh = @fopen($cachename . '.tmp', 'w'); if (!$fh) { trigger_error("Failed to write index cache", E_USER_ERROR); return; } @fwrite($fh, implode("\n", $lengths)); @fclose($fh); if (isset($conf['fperm'])) { chmod($cachename . '.tmp', $conf['fperm']); } io_rename($cachename . '.tmp', $cachename . '.idx'); return $lengths; }