function WriteToLog($txt, $level) { $this->logLevel = IntVal(COption::GetOptionString("mail", "smtp_log_level", "4")); if ($this->logLevel < $level) { return; } if (MicroTime(true) - $this->startPeriodTimeTruncate > 600) { if ($this->logFile) { FClose($this->logFile); } $this->logFile = null; if (File_Exists($_SERVER["DOCUMENT_ROOT"] . $this->logFileName)) { $logSize = @FileSize($_SERVER["DOCUMENT_ROOT"] . $this->logFileName); $logSize = IntVal($logSize); if ($logSize > $this->logMaxSize) { if (($fp = @FOpen($_SERVER["DOCUMENT_ROOT"] . $this->logFileName, "rb")) && ($fp1 = @FOpen($_SERVER["DOCUMENT_ROOT"] . $this->logFileName . "_", "wb"))) { $iSeekLen = IntVal($logSize - $this->logMaxSize / 2.0); FSeek($fp, $iSeekLen); @FWrite($fp1, "Truncated " . Date("Y-m-d H:i:s") . "\n---------------------------------\n"); do { $data = FRead($fp, 8192); if (StrLen($data) == 0) { break; } @FWrite($fp1, $data); } while (true); @FClose($fp); @FClose($fp1); @Copy($_SERVER["DOCUMENT_ROOT"] . $this->logFileName . "_", $_SERVER["DOCUMENT_ROOT"] . $this->logFileName); @UnLink($_SERVER["DOCUMENT_ROOT"] . $this->logFileName . "_"); } } ClearStatCache(); } $this->startPeriodTimeTruncate = MicroTime(true); } if (!$this->logFile || $this->logFile == null) { $this->logFile = FOpen($_SERVER["DOCUMENT_ROOT"] . $this->logFileName, "a"); } if (!$this->logFile) { echo "Can't write to log\n---------------------------------\n"; return; } FWrite($this->logFile, Date("Y-m-d H:i:s") . "\t" . trim($txt) . "\n"); FFlush($this->logFile); //if ($level > 4) echo trim($txt) . "\n---------------------------------\n"; }
function uploadFile($tmpLocation, $fileName) { // upload images and put them in sensible places // check images are to be uploaded //get some details about the current user $userID = get_user_id($_SESSION['valid_user']); //the dir to upload the file to on the server //this dir must be writiable by php (chmod 757 ought to do it) //$dir = "./attachments/"; if ($tmpLocation) { // check file name and make it unix friendly $pattern = '/[^a-zA-Z0-9_\\.]/'; $replacement = "_"; $fileName = preg_replace($pattern, $replacement, $fileName); //$dest = $dir . $fileName ; $dest = DIR_FS_ATTACHMENTS . $fileName; if (copy($tmpLocation, $dest)) { //it worked, now note this in the database $query = "INSERT INTO " . EMAILSHOT_ATTACHMENTS_TEMP . " ( attachment_id, user_id, filename ) VALUES ( '', '" . $userID . "', '" . mysql_real_escape_string($fileName) . "' );"; //echo "<hr>$query" ; if ($result = wrap_db_query($query)) { //get the attachment_id (auto) for the entry just added to the temp attachments table //$thisAttachmentID = wrap_db_insert_id() ; //and finally, return the filesize to the item that called this function return FileSize($dest); } //if you get here then the db insert failed so echo "<!-- Insert to DB failed -->"; return false; } else { echo "<!-- Copy to server failed -->"; return false; } } else { echo "<!-- hmmm, somethings a bit dodgy... -->"; } }
$Logs = SPrintF('%s/logs', $Tmp); #------------------------------------------------------------------------------- if (File_Exists($Logs)) { #----------------------------------------------------------------------------- $Files = IO_Scan($Logs); if (Is_Error($Files)) { return ERROR | @Trigger_Error(500); } #----------------------------------------------------------------------------- foreach ($Files as $Log) { #--------------------------------------------------------------------------- $Path = SPrintF('%s/%s', $Logs, $Log); #--------------------------------------------------------------------------- if (Preg_Match('/^.+\\.log+$/', $Log)) { #------------------------------------------------------------------------- if (FileSize($Path) > 1048576) { #----------------------------------------------------------------------- $Time = Date('[d.m.Y]'); #----------------------------------------------------------------------- if (!ReName($Path, SPrintF('%s/%s%s', $Logs, $Log, $Time))) { return ERROR | @Trigger_Error(SPrintF('[comp/Tasks/Logs]: не удалось произвести ротацию лога (%s)', $Path)); } } } else { #------------------------------------------------------------------------- if (Time() - FileMTime($Path) > 604800) { #----------------------------------------------------------------------- if (!@UnLink($Path)) { return ERROR | @Trigger_Error(SPrintF('[comp/Tasks/Logs]: не удалось удалить устаревший лог (%s)', $Path)); } }
function check_for_cached_file() { // Take a look over the cache. Maybe there is this file already if ($this->use_cache && Is_File($this->cache_file_path) && FileSize($this->cache_file_path) > 0 && FileMTime($this->cache_file_path) > FileMTime($this->attachment_file)) { Header('Location: ' . $this->cache_file_url); exit; } }
function calc_size($adr,&$total,&$dir,&$size){ $adr=realpath($adr); $dp=OpenDir($adr); do{ $itm=ReadDir($dp); if (($itm!=".")&&($itm!="..")&&($itm!="")&&Is_Dir("$adr/$itm")){ calc_size("$adr/$itm",$total,$dir,$size); $dir++; } elseif (($itm!=".")&&($itm!="..")&&($itm!="")){ $size = $size+FileSize("$adr/$itm"); $total++; } } while ($itm!=false); CloseDir($dp); }
function __Error_Handler__($Number, $Error, $File, $Line) { #------------------------------------------------------------------------------- $Message = SPrintF('[!!%s]-%s в линии %s файла %s', $Number, $Error, $Line, $File); #------------------------------------------------------------------------------- $__ERR_CODE =& $GLOBALS['__ERR_CODE']; #------------------------------------------------------------------------------- if ((int) $Error && $__ERR_CODE == 100) { $__ERR_CODE = $Error; } #------------------------------------------------------------------------------- Debug(SPrintF('[!] %s', $Message)); //Debug(SPrintF('[!] %s',debug_print_backtrace())); #------------------------------------------------------------------------------- //Error_Reporting(E_ALL); #------------------------------------------------------------------------------- if (Error_Reporting()) { #------------------------------------------------------------------------------- $JBsErrorID = SPrintF('%s[%s]', HOST_ID, Md5(Implode(':', array($Number, $Error, $Line, $File)))); #------------------------------------------------------------------------------- $__SYSLOG =& $GLOBALS['__SYSLOG']; #------------------------------------------------------------------------------- $Log = Implode("\n", $__SYSLOG); #------------------------------------------------------------------------------- Report($JBsErrorID, $JBsErrorID); #------------------------------------------------------------------------------- foreach (array(SYSTEM_PATH, '/tmp') as $Folder) { #------------------------------------------------------------------------------- $Path = SPrintF('%s/jbs-errors.log', $Folder); #------------------------------------------------------------------------------- if (File_Exists($Path)) { if (FileSize($Path) > 1024 * 1024) { UnLink($Path); } } #------------------------------------------------------------------------------- umask(077); #------------------------------------------------------------------------------- if (!@File_Put_Contents($Path, SPrintF("%s\n\n%s\n\n", $JBsErrorID, $Log), FILE_APPEND)) { #------------------------------------------------------------------------------- Debug(SPrintF('[__Error_Handler__]: не удалось осуществить запись ошибки в системный лог (%s)', $Path)); #------------------------------------------------------------------------------- continue; #------------------------------------------------------------------------------- } #------------------------------------------------------------------------------- break; #------------------------------------------------------------------------------- } #------------------------------------------------------------------------------- if (File_Exists(SPrintF('%s/DEBUG.OUT', SYSTEM_PATH)) || !isset($_SERVER["REMOTE_PORT"])) { #------------------------------------------------------------------------------- exit($Log); } else { #------------------------------------------------------------------------------- $Errors = array(100 => 'Ошибка выполнения', 101 => 'Неизвестный результат', 201 => 'Неверные параметры', 400 => 'Ошибка данных', 500 => 'Системная ошибка', 600 => 'Ошибка политики безопасности', 601 => 'Неверный реферер', 602 => 'Отсутствует реферер', 603 => 'Неверный ключ CSRF', 700 => 'Нарушение политики прав'); #------------------------------------------------------------------------------- $FilePath = SPrintF('%s/hosts/root/templates/modules/Trigger.Error.html', SYSTEM_PATH); #------------------------------------------------------------------------------- if (Is_Readable($FilePath)) { #------------------------------------------------------------------------------- $Result = @File_Get_Contents($FilePath); #------------------------------------------------------------------------------- } else { #------------------------------------------------------------------------------- $Result = SPrintF("Cannot read error file: %s<BR />\nError: %%s<BR />\n<!--%%s-->\nErrorID: %%s\n<!--%%s-->", $FilePath); #------------------------------------------------------------------------------- } #------------------------------------------------------------------------------- $String = SPrintF('%s (%s)', $Errors[$__ERR_CODE], $__ERR_CODE); #------------------------------------------------------------------------------- @Header(SPrintF('JBs-ErrorID: %s', $JBsErrorID)); #------------------------------------------------------------------------------- if (isset($_POST['XMLHttpRequest'])) { #------------------------------------------------------------------------------- $Answer = array('Error' => array('CodeID' => $__ERR_CODE, 'String' => $String), 'Status' => 'Error'); #------------------------------------------------------------------------------- exit(JSON_Encode($Answer)); #------------------------------------------------------------------------------- } else { #------------------------------------------------------------------------------- exit(SPrintF($Result, $String, $String, $JBsErrorID, Date('Y', Time()))); #------------------------------------------------------------------------------- } #------------------------------------------------------------------------------- } #------------------------------------------------------------------------------- } #------------------------------------------------------------------------------- }
function ProcessDirectory($Directory, $Options = False) { $bRecursive = $Options; /*if(Is_Bool($Options)) $bRecursive = $Options; elseif(Is_Numeric($Options)) $IntDeep = $Options; // 0 - unlim elseif(Is_Array($Options)){ $IntDeep = ArrayValue('Deep', $Options, '0'); $bRecursive = ArrayValue('Recursive', $Options, False); }*/ if (!is_dir($Directory)) { return False; } $List = array(); $Handle = opendir($Directory); while (False !== ($File = ReadDir($Handle))) { $Path = $Directory . DS . $File; if ($File == '.' || $File == '..' || !file_exists($Path)) { continue; } if (is_dir($Path) && $bRecursive) { $NextDirectory = ProcessDirectory($Path, True); if (is_array($NextDirectory)) { $List = array_merge($List, $NextDirectory); } } else { $Entry = new StdClass(); $Entry->Filename = $File; $Entry->Directory = $Directory; $Entry->Modtime = filemtime($Path); if (!is_dir($Path)) { // files $Entry->Size = FileSize($Path); } else { // directories $Entry->IsWritable = Is_Writable($Path); $Entry->bDirectory = True; } $List[] = $Entry; } } closedir($Handle); return $List; }
/** download a file @access Public @param string [$_content] data to write into the file @return boolean */ function Download() { header("Content-type: " . $this->File_Type); header("Content-Length: " . FileSize($this->File_Path . $this->{$File_Name})); //header( "Content-Length: ".$this->File_Size ); header("Content-Disposition: filename=" . $this->File_Path . $this->File_Name); header("Content-Description: Download Data"); echo $this->Content; }
$text = fwrite($file, ";"); $text = fwrite($file, $GPIO10); $text = fwrite($file, ";"); $text = fwrite($file, $GPIO11); $text = fwrite($file, ";"); $text = fwrite($file, $GPS_VALID); $text = fwrite($file, ";"); $text = fwrite($file, $GPS_LATITUDE); $text = fwrite($file, ";"); $text = fwrite($file, $GPS_LONGITUDE); fclose($file); // send data back if ($file = @fopen("WebData2Client.dat", "r")) { echo "RET_S;OK;"; // RET_S = RET_START $text = fread($file, FileSize("WebData2Client.dat")); fclose($file); list($user_led, $GPIO12, $GPIO13) = Explode(";", $text); echo $user_led; echo ";"; echo $GPIO12; echo ";"; echo $GPIO13; echo ";"; echo "RET_E"; // RET_E ´RET_END } else { echo "RET_S;ERROR;Cannot open a file WebData2Client.dat!;RET_E"; } } else { echo "RET_S;ERROR;File Client2WebData.dat doesn't have rights for write!;RET_E";
return; } #------------------------------------------------------------------------------- } #------------------------------------------------------------------------------- if (!File_Exists($File)) { #------------------------------------------------------------------------------- echo "ERROR: файл резервной копии не был создан\n"; #------------------------------------------------------------------------------- if (!$Force) { return; } #------------------------------------------------------------------------------- } #------------------------------------------------------------------------------- $Size = @FileSize($File); #------------------------------------------------------------------------------- if ($Size < 1024) { #------------------------------------------------------------------------------- echo "ERROR: файл резервной копии поврежден\n"; #------------------------------------------------------------------------------- if (!$Force) { return; } #------------------------------------------------------------------------------- } else { #------------------------------------------------------------------------------- echo SPrintF("Файл (%s) резервной копии имеет размер %u Кб.\n", $File, $Size / 1024); #------------------------------------------------------------------------------- } #-------------------------------------------------------------------------------
function IO_Read($Path, $IsUseLinks = TRUE) { /******************************************************************************/ $__args_types = array('string', 'boolean'); #------------------------------------------------------------------------------- $__args__ = Func_Get_Args(); eval(FUNCTION_INIT); /******************************************************************************/ Debug(SPrintF('[IO_Read]: открытие файла (%s)', $Path)); #------------------------------------------------------------------------------- if (!File_Exists($Path)) { return ERROR | @Trigger_Error('[IO_Read]: файл не существует'); } #------------------------------------------------------------------------------- if (!($File = @Fopen($Path, 'r'))) { return ERROR | @Trigger_Error('[IO_Read]: ошибка открытия файла'); } #------------------------------------------------------------------------------- $Size = @FileSize($Path); if (!$Size) { return ''; } #------------------------------------------------------------------------------- if (!($Result = @Fread($File, $Size))) { return ERROR | @Trigger_Error('[IO_Read]: ошибка чтения файла'); } #------------------------------------------------------------------------------- if (!Fclose($File)) { return ERROR | @Trigger_Error('[IO_Read]: ошибка закрытия файла'); } #------------------------------------------------------------------------------- if (Mb_StrLen($Result) > 4) { #------------------------------------------------------------------------------- if (Mb_SubStr($Result, 1, 4) == 'link' && $IsUseLinks) { #------------------------------------------------------------------------------- $LinkPath = Trim(Mb_SubStr($Result, Mb_StrPos($Result, ':') + 1)); #------------------------------------------------------------------------------- switch ($Result[0]) { case '#': # Абсолюная ссылка # No more... break; case '@': # Относительная ссылка #------------------------------------------------------------------------------- $Folder = Mb_SubStr($Path, 0, Mb_StrrPos($Path, '/')); #------------------------------------------------------------------------------- $LinkPath = SPrintF('%s/%s', $Folder, $LinkPath); #------------------------------------------------------------------------------- break; #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- default: return ERROR | @Trigger_Error('[IO_Read]: тип ссылки не определён'); } #------------------------------------------------------------------------------- if ($Path == $LinkPath) { return ERROR | @Trigger_Error(SPrintF('[IO_Read]: ссылка сама на себя в файле(%s)', $Path)); } #------------------------------------------------------------------------------- Debug(SPrintF('[IO_Read]: символическая ссылка (%s) на (%s)', $Path, $LinkPath)); #------------------------------------------------------------------------------- $Result = IO_Read($LinkPath); if (Is_Error($Result)) { return ERROR | @Trigger_Error('[IO_Read]: ошибка рекурсивного вызова'); } #------------------------------------------------------------------------------- } #------------------------------------------------------------------------------- } #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- return $Result; #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- }
FUNCTION RunSQL($link, $file) { IF(File_Exists($file)) { $fd = FOpen($file, "r"); $sql = FRead($fd, FileSize($file)); FClose($fd); $query = Split(";( )?(\r)?\n(\r)?", $sql); FOR($i = 0; $i < Count($query); $i++) { IF($query[$i] != "") { $link->Query($query[$i]); } } RETURN TRUE; } ELSE {RETURN FALSE;} }
function Resampled_Image_URL($attachment_id, $width = 0, $height = 0, $crop = False, $grayscale = False, $negate = False, $qualy = 80) { global $blog_id; // Mime Type list($attachment_mime, $attachment_type) = Explode('/', get_post_mime_type($attachment_id)); // Attachment file $attachment_file = RealPath(get_attached_file($attachment_id)); // Read Cache Directory and URL $cache_file_name = '/image_thumbs/' . IntVal($blog_id) . '-' . IntVal($attachment_id) . '-' . IntVal($width) . '-' . IntVal($height) . '-' . IntVal($crop) . '-' . IntVal($grayscale) . '-' . IntVal($negate) . '-' . IntVal($qualy) . '.' . $attachment_type; if (Is_File(WP_CONTENT_DIR . $cache_file_name) && Is_File($attachment_file) && FileSize(WP_CONTENT_DIR . $cache_file_name) > 0 && FileMTime(WP_CONTENT_DIR . $cache_file_name) > FileMTime($attachment_file)) { return WP_CONTENT_URL . $cache_file_name; } else { return $this->base_url . '/wp-thumb.php?' . HTTP_Build_Query(array('a' => IntVal($attachment_id), 'w' => IntVal($width), 'h' => IntVal($height), 'c' => IntVal($crop), 'g' => IntVal($grayscale), 'n' => IntVal($negate), 'q' => IntVal($qualy))); } }
?> </ul><?php } ?> <h2>Upload a new file in this directory</h2><form action="?action=uploadfile" method="post" enctype="multipart/form-data"><p><input type="hidden" name="dir" value="<?php echo $filebrowser->directory; ?> "><input type="file" name="file"><input type="submit" value="Upload"></p></form><h2>Create a new folder in this directory</h2><form action="?action=createfolder" method="post"><p><input type="hidden" name="dir" value="<?php echo $filebrowser->directory; ?> "><input type="text" name="folder"><input type="submit" value="Create"></p></form></body></html><?php } elseif ($filebrowser->action == 'getfile') { Header('Status: 200'); Header('Content-Type: application/' . PathInfo($filebrowser->file, PATHINFO_EXTENSION)); Header(SPrintF('Content-Disposition: attachment; filename="%s"', BaseName($filebrowser->file))); Header('Content-Length:' . FileSize($filebrowser->file)); ReadFile($filebrowser->file); exit; } elseif ($filebrowser->action == 'delfile') { Unlink($filebrowser->file); Header('Status: 307'); Header('Location: ' . $filebrowser->build_link('browse', DirName($filebrowser->file))); exit; } elseif ($filebrowser->action == 'uploadfile') { Copy($_FILES['file']['tmp_name'], $filebrowser->directory . $_FILES['file']['name']); Header('Status: 307'); Header('Location: ' . $filebrowser->build_link('browse', $filebrowser->directory)); exit; } elseif ($filebrowser->action == 'createfolder') { $new_folder = $filebrowser->directory . Trim($_REQUEST['folder']); MKDir($new_folder, 0777, True);
echo "<font color=\"red\"><p>Dosavadní data budou nenávratnì ztracena!!!</font>"; echo "<form action=\"./ic_katalog_akt.php?kod=$kod\" method=post enctype=\"multipart/form-data\">"; echo "soubor: <input type=\"file\" name=\"soubor\" value=\"$soubor\">"; echo "<p>"; echo "<input type = \"submit\" value=\"odeslat soubor\" name=\"odeslano_kat\">"; echo "</form>"; if($odeslano_kat) { $SQL = "delete from ic_knihy"; DB_exec($SQL); $novy = "./files_ic/seznam.txt"; echo "<p>velikost souboru = ".FileSize($soubor); if(FileSize($soubor)<>0) { copy($soubor, $novy); /*$katalog = fopen($novy, r);*/ $katalog = file($novy); $i = 0; while($i<count($katalog)) { $polozka = explode('|', $katalog[$i]); /*echo "<p>id = ".$polozka[0]; echo "<p>autor = ".$polozka[1]; echo "<p>nazev = ".$polozka[2]; echo "<p>vypujcni doba = ".$polozka[3]; echo "<p>pocet ks = ".$polozka[4];*/ $id = $polozka[0]; $autor = $polozka[1];
if (FileSize($Files[$FileName]) == 0) { continue; } #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- # удаляем явно мусорные расширения $Array = Explode('.', $FileName); #------------------------------------------------------------------------------- $Extension = $Array[Count($Array) - 1]; #------------------------------------------------------------------------------- if (In_Array($Extension, array('sig'))) { continue; } #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- $FileData = array('size' => FileSize($Files[$FileName]), 'error' => 0, 'tmp_name' => $Files[$FileName], 'name' => $FileName); #------------------------------------------------------------------------------- $_FILES = array('Upload' => $FileData); #------------------------------------------------------------------------------- global $_FILES; #------------------------------------------------------------------------------- $Hash = Comp_Load('www/API/Upload'); if (Is_Error($Hash)) { return ERROR | @Trigger_Error(500); } #------------------------------------------------------------------------------- } #------------------------------------------------------------------------------- # надо ли вырезать цитаты из текста if ($Settings['CutQuotes']) { #-------------------------------------------------------------------------------
} #------------------------------------------------------------------------------- if (!@File_Put_Contents($MyCnf, SPrintF("[client]\nhost = %s\nport = %u\nuser = %s\npassword = %s\n", $DBConnection['Server'], $DBConnection['Port'], $DBConnection['User'], $DBConnection['Password']))) { Error(SPrintF('<P>Не удалось сохранить текущие настройки соединения с базой данных в файле (%s)</P>', $MyCnf)); } #------------------------------------------------------------------------------- $File = SPrintF('%s/%s.sql', $Folder, Date('D')); #------------------------------------------------------------------------------- $Command = SPrintF('mysqldump --defaults-extra-file=%s --quote-names -r %s %s', $MyCnf, $File, $DBConnection['DbName']); #------------------------------------------------------------------------------- Debug(SPrintF('[comp/Tasks/BackUp]: команда консоли (%s)', $Command)); #------------------------------------------------------------------------------- $Log = array(); #------------------------------------------------------------------------------- if (Exec($Command, $Log)) { return ERROR | @Trigger_Error(SPrintF("[comp/Tasks/BackUp]: ошибка выполнения команды:\n%s", Implode("\n", $Log))); } #------------------------------------------------------------------------------- if (!File_Exists($File)) { return ERROR | @Trigger_Error('[comp/Tasks/BackUp]: файл резервной копии не был создан'); } #------------------------------------------------------------------------------- UnLink($MyCnf); #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- $GLOBALS['TaskReturnInfo'] = array(SPrintF('DB dump size: %s Mb', Ceil(FileSize($File) / (1024 * 1024)))); #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- return $ExecuteTime; #------------------------------------------------------------------------------- #-------------------------------------------------------------------------------