コード例 #1
0
function setUpDirectory()
{
    //make source dir : source001, source 002 etc
    //make source file
    global $dir;
    makeDir();
    $source = stripslashes($_REQUEST['source']);
    file_put_contents($dir . '/source.cpp', $source);
}
コード例 #2
0
 function fileUpload($field)
 {
     $CI =& get_instance();
     $upload_config = $CI->config->item('upload_config');
     $upload_config['upload_path'] = makeDir($CI->config->item('upload_path'));
     $CI->load->library('upload', $upload_config);
     if (!$CI->upload->do_upload($field)) {
         return $CI->upload->display_errors();
     } else {
         return $CI->upload->data();
     }
 }
コード例 #3
0
ファイル: index.php プロジェクト: manhvu1212/videoplatform
function thumb_image_scale($width = 1, $height = 1, $partrelative = null, $partfull = '')
{
    $link2 = explode('/', $partfull);
    $name1 = $partrelative . '/' . $width . '/' . $height . '/' . $link2[count($link2) - 1];
    $name1 = $width . '/' . $height . '/' . $partrelative . $link2[count($link2) - 1];
    if (!file_exists(SITE_DIR_BASE . $partfull) || $partfull == '') {
        $name1 = SITE_DIR_BASE . 'notfound.jpg';
    }
    $check1 = explode('.', $partfull);
    if (!in_array($check1[count($check1) - 1], array('jpg', 'png', 'jpeg', 'gif'))) {
        $link1 = '';
    } else {
        $bien = getimagesize(DOMAIN_BASE . $partfull);
        $wimg = isset($bien[0]) ? $bien[0] : 1;
        //chieu rong thuc te
        $himg = isset($bien[1]) ? $bien[1] : 1;
        // chieu cao thuc te
        $x = $wimg;
        $y = $himg;
        $h = floor($wimg * $height / $width);
        if ($h <= $himg) {
            $y = $h;
        } else {
            $x = floor($y * $width / $height);
        }
        if ($x <= $width) {
            $tl = 100;
        } else {
            $tl = 100 - floor(($x - $width) * 100 / $x);
        }
        $link2 = explode('/', $partfull);
        $link1 = makeDir($name1);
        $name = 'tmp_' . $width . "x" . $height . '_' . $link2[count($link2) - 1];
        $name1 = $link1;
        $link1 = $link1 . $name;
        $name1 .= $link2[count($link2) - 1];
        if (!file_exists(SITE_DIR_BASE . $link1)) {
            $thumb = PhpThumbFactory::create(DOMAIN_BASE . $partfull);
            $thumb->cropFromCenter($x, $y);
            //$thumb->resizePercent($tl);
            $thumb->save(SITE_DIR_BASE . $link1);
            $thumb = PhpThumbFactory::create(SITE_DIR_BASE . $link1);
            $thumb->resizePercent($tl);
            $thumb->save(SITE_DIR_BASE . $name1);
            @unlink(SITE_DIR_BASE . $link1);
            header('Content-Type: image/jpeg');
            readfile(SITE_DIR_BASE . $name1);
            exit;
        }
    }
    return $name1;
}
コード例 #4
0
 /**
  * Initialise the Visitors object.
  */
 function Visitors()
 {
     global $PIVOTX;
     // Clean up user input to avoid HTML injection and/or stored XSS.
     // Also using strip_tags since none of the fields should contain HTML.
     $input = array_merge($_POST, $_GET);
     foreach ($input as $key => $value) {
         $input[$key] = htmlspecialchars(strip_tags(trim($value)));
     }
     $this->input = $input;
     $this->input['message'] = '';
     // Make sure the db/users/ folder is present.
     makeDir($PIVOTX['paths']['db_path'] . 'users/');
 }
コード例 #5
0
ファイル: pages_flat.php プロジェクト: laiello/pivotx-sqlite
    /**
     * Initialisation.
     *
     * @return PagesFlat
     */
    function PagesFlat()
    {
        global $PIVOTX;
        //init vars..
        static $initialisationchecks;
        if (!$initialisationchecks) {
            // Verify that the pages folder exists.
            if (!file_exists($PIVOTX['paths']['db_path'] . "pages")) {
                makeDir($PIVOTX['paths']['db_path'] . "pages");
            }
        }
        // Create the default pages. They can be recreated by setting
        // 'dont_recreate_default_pages' to 0 in the advanced config.
        if (!$initialisationchecks && !$PIVOTX['config']->get('dont_recreate_default_pages')) {
            $PIVOTX['config']->set('dont_recreate_default_pages', 1);
            $now = date("Y-m-d-H-i", getCurrentDate());
            $userdata = $PIVOTX['users']->getUsers();
            $username = $userdata[0]['username'];
            $this->index = $this->getIndex();
            $pages = array();
            $pages['1'] = array('user' => $username, 'sortorder' => 10, 'allow_comments' => 1, 'code' => 1, 'date' => $now . '-01', 'uri' => 'about', 'chapter' => 0, 'publish_date' => $now . '-01', 'edit_date' => $now . '-01', 'title' => __('About PivotX'), 'subtitle' => '', 'template' => '', 'introduction' => "<p>Hi! This website runs on <a href=\"http://pivotx.net\">PivotX</a>,\n                the coolest free and open tool to power your blog and website. To change this text, edit '<tt>About PivotX</tt>',\n                under '<tt>Pages</tt>' in the PivotX backend.</p>", 'body' => '<p>PivotX is a feature rich weblogging tool that is simple enough for the novice
weblogger to use and complex enough to meet the demands of advanced webmasters.
It can be used to publish a variety of websites from the most basic weblog to
very advanced CMS style solutions.</p>
<p>PivotX is - if we do say so ourselves - quite an impressive piece of software.
It is made even better through the use of several external libraries. We thank their
authors for the time taken to develop these very useful tools and for making
them available to others.</p>
<p>Development of PivotX (originally Pivot) started back in 2001 and has continuously
forged ahead thanks to the efforts of a lot of dedicated and very talented people. 
The PivotX core team is still very active but keep in mind that PivotX would not be 
what it is today without the valuable contributions made by several other people.</p>', 'convert_lb' => '', 'status' => 'publish', 'keywords' => '', 'uid' => 1, 'link' => '/page/welcome', 'extrafields' => array('image' => '', 'description' => ''));
            $pages['2'] = array('user' => $username, 'sortorder' => 10, 'allow_comments' => 1, 'code' => 2, 'date' => $now . '-01', 'uri' => 'links', 'chapter' => 0, 'publish_date' => $now . '-01', 'edit_date' => $now . '-01', 'title' => __('Links'), 'subtitle' => '', 'template' => '', 'introduction' => '<p>Some links to sites with more information:</p>
<ul>
<li>PivotX - <a href="http://pivotx.net">The PivotX website</a></li>
<li>Get help on <a href="http://forum.pivotx.net">the PivotX forum</a></li>
<li>Read <a href="http://book.pivotx.net">the PivotX documentation</a></li>
<li>Browse for <a href="http://themes.pivotx.net">PivotX Themes</a></li>
<li>Get more <a href="http://extensions.pivotx.net">PivotX Extensions</a></li>
<li>Follow <a href="http://twitter.com/pivotx">@pivotx on Twitter</a></li>
</ul>
<p><small>To change these links, edit \'<tt>Links</tt>\', under \'<tt>Pages</tt>\' in the PivotX backend.</small></p>', 'body' => '', 'convert_lb' => '', 'status' => 'publish', 'keywords' => '', 'uid' => 2, 'link' => '/page/about-pivotx', 'extrafields' => array('image' => '', 'description' => ''));
            for ($i = 1; $i < 3; $i++) {
                if (!file_exists($PIVOTX['paths']['db_path'] . "pages/page_{$i}.php")) {
                    $this->savePage($pages[$i]);
                }
            }
        }
        $initialisationchecks = true;
    }
コード例 #6
0
ファイル: weather.php プロジェクト: dlpc/weathercollection
/**
 * 保存文件
 *
 * @param string $fileName 文件名(含相对路径)
 * @param string $text 文件内容
 * @return boolean
 */
function saveFile($fileName, $text)
{
    if (!$fileName || !$text) {
        return false;
    }
    if (makeDir(dirname($fileName))) {
        if ($fp = fopen($fileName, "w")) {
            if (@fwrite($fp, $text)) {
                fclose($fp);
                return true;
            } else {
                fclose($fp);
                return false;
            }
        }
    }
    return false;
}
コード例 #7
0
ファイル: lib.php プロジェクト: viyancs/bolt
/**
 * Recursively creates chmodded directories. Returns true on success,
 * and false on failure.
 *
 * NB! Directories are created with permission 777 - worldwriteable -
 * unless you have set 'chmod_dir' to 0XYZ in the advanced config.
 *
 * @param string $name
 * @return boolean
 */
function makeDir($name)
{
    // if it exists, just return.
    if (file_exists($name)) {
        return true;
    }
    // If more than one level, try parent first..
    // If creating parent fails, we can abort immediately.
    if (dirname($name) != ".") {
        $success = makeDir(dirname($name));
        if (!$success) {
            return false;
        }
    }
    $mode_dec = octdec('0777');
    $oldumask = umask(0);
    $success = @mkdir($name, $mode_dec);
    @chmod($name, $mode_dec);
    umask($oldumask);
    return $success;
}
コード例 #8
0
ファイル: EmailController.php プロジェクト: xiaopingL/lcmedia
 public function upload()
 {
     error_reporting(0);
     $action = '';
     if (!empty($_GET['act'])) {
         $action = $_GET['act'];
     }
     if ($action == 'delimg') {
         $filename = $_POST['imagename'];
         if (!empty($filename)) {
             unlink('files/' . $filename);
             echo '1';
         } else {
             echo '删除失败。';
         }
     } else {
         $picname = $_FILES['mypic']['name'];
         $picsize = $_FILES['mypic']['size'];
         if ($picname != "") {
             if ($picsize > 10485760) {
                 echo '文件大小不能超过10M';
                 exit;
             }
             $upload_config = $this->config->item('upload_config');
             $upload_config['upload_path'] = makeDir($this->config->item('upload_path'));
             $ext = pathinfo($picname);
             $type = $ext['extension'];
             $allow_types = explode("|", $upload_config['allowed_types']);
             if (!in_array($type, $allow_types)) {
                 echo "文件格式不正确";
                 exit;
             }
             $pics = md5(date('YmdHis')) . '.' . $type;
             $path = $upload_config['upload_path'];
             //上传路径
             $pic_path = $path . $pics;
             move_uploaded_file($_FILES['mypic']['tmp_name'], $pic_path);
         }
         $size = round($picsize / 1024, 2);
         $arr = array('fileName' => $pics, 'filePath' => $path, 'origName' => str_replace("—", "-", $picname), 'fileExt' => '.' . $type, 'fileSize' => $size);
         $nameTitle = basename($arr['origName'], $arr['fileExt']);
         $length = mb_strlen($nameTitle);
         $lengthArr = 25 - $length;
         if ($lengthArr == 0) {
             //echo "<b style=color:red;font-size:16px;>标题不能超过25个字!</b>";
             //exit;
         }
         $signal = $this->PublicModel->insertSave('crm_file', $arr);
         if (!empty($signal)) {
             $arr['fid'] = $signal;
             $arr['bfs'] = '100';
         }
         $arr['nameTitle'] = $nameTitle;
         $arr['length'] = $lengthArr;
         $result = json_encode($arr);
         $data['rows'] = $result;
         echo $data['rows'];
     }
 }
コード例 #9
0
$key = $argv[1];
if (!$key) {
    echo "usage \$php getindex.php 'A', 'B' ...\n";
    exit;
}
$files = get_all_log_file("./data/{$key}/");
makeDir("./data/index/");
//存放论文目录,不会重复创建
makeDir("./data/index/{$key}");
foreach ($files as $file) {
    $fp = fopen($file, "r");
    $file = iconv("gb2312", "utf-8", $file);
    $subdir = basename($file, ".log");
    //$subdir = win_dir_format($subdir);
    $indexSavePath = "./data/index/{$key}/" . $subdir;
    makeDir($indexSavePath);
    $mapFile = $indexSavePath . "/paper_url_mapping.log";
    delFile($mapFile);
    $icount = 1;
    while ($line = readLine($fp)) {
        $arr = explode("\t", $line);
        $u = $arr[6];
        $paperName = $arr[0];
        $paperName = win_dir_format($paperName);
        //echo $paperName . "\n";
        $htmlFileName = $indexSavePath . "/" . $paperName . ".html";
        $tmpFile = iconv("utf-8", "gb2312//IGNORE", $htmlFileName);
        $dbCode = get_db_code($u);
        $fileName = get_file_name($u);
        $tableName = get_table_name($u);
        $realUrl = get_real_url($dbCode, $fileName, $tableName);
コード例 #10
0
 /**
  * 获取保存的路径
  * @param string $dir 指定的保存目录
  * @return string
  */
 function getTargetDir($dir)
 {
     if ($dir == 'temp') {
         $dir = './public/upload/temp/' . date('Y/m/d/H', NULL);
     } else {
         $dir = './public/upload/' . $dir . '/' . date('Y/m/d', NULL);
     }
     makeDir(FANWE_ROOT . $dir);
     return $dir;
 }
コード例 #11
0
	if ($_POST['insert_as_user_id'] >0 && L_auth::isAdmin($userID) ) $flights_user_id=$_POST['insert_as_user_id']+0;
	else $flights_user_id=$userID;

	$randName=sprintf("%05d",rand(1, 10000) );
	
	$tmpZIPfolder=LEONARDO_ABS_PATH.'/'.$CONF['paths']['tmpigc'].'/zipTmp_'.$flights_user_id.'_'.$randName ;
	// $tmpZIPfolder=$flightsAbsPath."/".$flights_user_id."/flights/zipTmp".$randName ;
	$tmpZIPPath=LEONARDO_ABS_PATH.'/'.$CONF['paths']['tmpigc'].'/zipFile'.$flights_user_id.'_'.$randName.'.zip';
	//$tmpZIPPath=$flightsAbsPath."/".$flights_user_id."/flights/zipFile".$randName.".zip";
	
	move_uploaded_file($_FILES['zip_datafile']['tmp_name'], $tmpZIPPath );

	//delDir($tmpZIPfolder);
	//exec("unzip -o -j ".$tmpZIPPath." -d '".$tmpZIPfolder."'" );

	makeDir($tmpZIPfolder);
	require_once dirname(__FILE__)."/lib/pclzip/pclzip.lib.php";
	$archive = new PclZip($tmpZIPPath);
    $list 	 = $archive->extract(PCLZIP_OPT_PATH, $tmpZIPfolder,
                                PCLZIP_OPT_REMOVE_ALL_PATH,
								PCLZIP_OPT_BY_PREG, "/(\.igc)|(\.olc)$/i");

	echo "<b>List of uploaded igc/olc files</b><BR>";
	$f_num=1;
	foreach($list as $fileInZip) {
		echo "$f_num) ".$fileInZip['stored_filename']. ' ('.floor($fileInZip['size']/1024).'Kb)<br>';
		$f_num++;
	}
	flush2Browser();
	flush2Browser();
コード例 #12
0
 public function saveAvatar($uid, $img)
 {
     $types = array('small' => '32', 'middle' => '64', 'big' => '160');
     $uid = sprintf("%09d", $uid);
     $dir1 = substr($uid, 0, 3);
     $dir2 = substr($uid, 3, 2);
     $dir3 = substr($uid, 5, 2);
     $file_path = PUBLIC_ROOT . './upload/avatar/' . $dir1 . '/' . $dir2 . '/' . $dir3;
     makeDir($file_path);
     $file_path .= '/' . substr($uid, -2) . '_';
     include_once fimport('class/image');
     $image = new Image();
     foreach ($types as $size => $wh) {
         $image->thumb($img, $wh, $wh, 1, true, $file_path . $size . '.jpg');
     }
     UserService::updateAvatar($uid);
     @unlink($img);
 }
コード例 #13
0
ファイル: install.php プロジェクト: Juribiyan/gsap-l00ps
  include 'install/pages/install.html';
  die();
}

message('Создаем таблицы...');

install_sql('install/sql/drop.sql');
install_sql('install/sql/loops.sql');
install_sql('install/sql/patterns.sql');

message('Создаем директории...');

makeDir('loops/live');
makeDir('loops/dead');
makeDir('loops/custom');

if($_POST['install_type'] != 'bare') {
  message('Устанавливаем базовый контент...');

  install_sql('install/sql/default_loops.sql');
  install_sql('install/sql/default_patterns.sql');

  xcopy('install/media/dead', 'loops/dead');
  xcopy('install/media/live', 'loops/live');
}

if($_POST['install_type'] == 'extra') {
  message('Устанавливаем екстра контент...');

  install_sql('install/sql/extra_loops.sql');
コード例 #14
0
    exit;
}
$files = get_all_log_file("./data/{$key}/");
makeDir("./data/abstract/");
//存放论文摘要,不会重复创建
makeDir("./data/abstract/{$key}");
//’A' , 'B'...
$httpClient = new HttpClient("epub.cnki.net");
foreach ($files as $file) {
    $fp = fopen($file, "r");
    $file = iconv("gb2312", "utf-8", $file);
    $subdir = basename($file, ".log");
    $subdir = win_dir_format($subdir);
    $dataSavePath = "./data/abstract/{$key}/" . $subdir;
    makeDir($dataSavePath);
    makeDir($dataSavePath . "/tmp");
    $mapFile = $dataSavePath . "/paper_abstract_url.log";
    $icount = 1;
    while ($line = readLine($fp)) {
        $sleep = true;
        $arr = explode("\t", $line);
        $u = $arr[6];
        $paperName = $arr[0];
        $code = $arr[7];
        /*获取Referer头*/
        $dbCode = get_db_code($u);
        //CDFD
        $refUrl = get_ref($dbCode);
        $cachedHtml = $dataSavePath . "/tmp/{$paperName}.html";
        $absPath = $dataSavePath . "/" . $paperName . ".log";
        //echo "Cache check $cachedHtml...";
コード例 #15
0
function newPkg()
{
    $pkg['vendor'] = cliInput("Package Vendor : ");
    $pkg['name'] = cliInput("Package Name : ");
    $pkg['description'] = cliInput("Package Description : ");
    $pkg['keywords'] = cliInput("Package Keywords : ");
    $pkg['license'] = cliInput("Package License : ");
    // $pkg['require'] = cliInput("Package Require : ");
    // $pkg['require-dev'] = cliInput("Package Require-dev : ");
    //
    makeDir(__DIR__ . "/" . $pkg['vendor']);
    makeDir(__DIR__ . "/" . $pkg['vendor'] . "/" . $pkg['name']);
    echo shell_exec("cd " . __DIR__ . "/" . $pkg['vendor'] . "/" . $pkg['name'] . " && git init");
    makeDir(__DIR__ . "/" . $pkg['vendor'] . "/" . $pkg['name'] . "/src");
    makeDir(__DIR__ . "/" . $pkg['vendor'] . "/" . $pkg['name'] . "/tests");
    makeDir(__DIR__ . "/" . $pkg['vendor'] . "/" . $pkg['name'] . "/src/config");
    makeDir(__DIR__ . "/" . $pkg['vendor'] . "/" . $pkg['name'] . "/src/controllers");
    makeDir(__DIR__ . "/" . $pkg['vendor'] . "/" . $pkg['name'] . "/src/translations");
    makeDir(__DIR__ . "/" . $pkg['vendor'] . "/" . $pkg['name'] . "/src/migrations");
    makeDir(__DIR__ . "/" . $pkg['vendor'] . "/" . $pkg['name'] . "/src/views");
    makeDir(__DIR__ . "/" . $pkg['vendor'] . "/" . $pkg['name'] . "/src/models");
    makeDir(__DIR__ . "/" . $pkg['vendor'] . "/" . $pkg['name'] . "/src/" . ucfirst($pkg['vendor']));
    makeDir(__DIR__ . "/" . $pkg['vendor'] . "/" . $pkg['name'] . "/src/" . ucfirst($pkg['vendor']) . "/" . ucfirst($pkg['name']));
    makeDir(__DIR__ . "/" . $pkg['vendor'] . "/" . $pkg['name'] . "/src/" . ucfirst($pkg['vendor']) . "/" . ucfirst($pkg['name']) . "/Facades");
    // Composer
    $temp = file_get_contents(__DIR__ . "/template/composer");
    $author = json_decode(@file_get_contents('author.json'), true);
    $keywords = explode(",", $pkg['keywords']);
    $find = ["<<PKGNAME>>", "<<PKGDESC>>", "<<LIC>>", "<<KEY>>", "<<AUTHNAME>>", "<<AUTHEMAIL>>", "<<REQ>>", "<<DEV>>", "<<AL>>"];
    $repl = [$pkg['vendor'] . "/" . $pkg['name'], $pkg['description'], $pkg['license'], json_encode($keywords), $author['name'], $author['email'], $pkg['require'], $pkg['require-dev'], ucfirst($pkg['vendor']) . "\\\\" . ucfirst($pkg['name'])];
    $temp = str_replace($find, $repl, $temp);
    file_put_contents(__DIR__ . "/" . $pkg['vendor'] . "/" . $pkg['name'] . "/composer.json", $temp);
    echo "composer.json created\n";
    // ServiceProvider
    $temp = file_get_contents(__DIR__ . "/template/ServiceProvider");
    $find = ["<<UCPKGPATH>>", "<<CLASS>>", "<<PKG>>", "<<PKGNAME>>"];
    $repl = [ucfirst($pkg['vendor']) . "\\" . ucfirst($pkg['name']), ucfirst($pkg['name']), strtolower($pkg['name']), $pkg['name']];
    $temp = str_replace($find, $repl, $temp);
    file_put_contents(__DIR__ . "/" . $pkg['vendor'] . "/" . $pkg['name'] . "/src/" . ucfirst($pkg['vendor']) . "/" . ucfirst($pkg['name']) . "/" . ucfirst($pkg['name']) . "ServiceProvider.php", $temp);
    echo "ServiceProvider created\n";
    // Main Class
    $temp = file_get_contents(__DIR__ . "/template/class");
    $find = ["<<UCPKGPATH>>", "<<CLASS>>"];
    $repl = [ucfirst($pkg['vendor']) . "\\" . ucfirst($pkg['name']), ucfirst($pkg['name'])];
    $temp = str_replace($find, $repl, $temp);
    file_put_contents(__DIR__ . "/" . $pkg['vendor'] . "/" . $pkg['name'] . "/src/" . ucfirst($pkg['vendor']) . "/" . ucfirst($pkg['name']) . "/" . ucfirst($pkg['name']) . ".php", $temp);
    echo "Main Class created\n";
    // Main Class
    $temp = file_get_contents(__DIR__ . "/template/facade");
    $find = ["<<UCPKGPATH>>", "<<CLASS>>", "<<NAME>>"];
    $repl = [ucfirst($pkg['vendor']) . "\\" . ucfirst($pkg['name']), ucfirst($pkg['name']), $pkg['name']];
    $temp = str_replace($find, $repl, $temp);
    file_put_contents(__DIR__ . "/" . $pkg['vendor'] . "/" . $pkg['name'] . "/src/" . ucfirst($pkg['vendor']) . "/" . ucfirst($pkg['name']) . "/Facades" . "/" . ucfirst($pkg['name']) . ".php", $temp);
    echo "Facade Class created\n";
    // Config
    file_put_contents(__DIR__ . "/" . $pkg['vendor'] . "/" . $pkg['name'] . "/src/config/config.php", file_get_contents(__DIR__ . "/template/config"));
    // ReadMe.md
    $temp = file_get_contents(__DIR__ . "/template/readme");
    $find = ["<<UNAME>>", "<<DESC>>", "<<UCPKG>>", '<<PKGPATH>>'];
    $repl = [ucfirst($pkg['name']), $pkg['description'], ucfirst($pkg['vendor']) . "\\" . ucfirst($pkg['name']), $pkg['vendor'] . '/' . $pkg['name']];
    $temp = str_replace($find, $repl, $temp);
    file_put_contents(__DIR__ . "/" . $pkg['vendor'] . "/" . $pkg['name'] . "/readme.md", $temp);
    echo "Readme created\n";
}
コード例 #16
0
ファイル: CL_pilot.php プロジェクト: Peter2121/leonardoxc
 function createDirs()
 {
     $pilotPath = $this->getAbsPath();
     if (!is_dir($pilotPath)) {
         makeDir($pilotPath);
     }
 }
コード例 #17
0
 public function saveAvatar($uid, $img)
 {
     $types = array('small' => '32', 'middle' => '64', 'big' => '190');
     $avatar_status = UserService::getIsAvatar($uid);
     $uid = sprintf("%09d", $uid);
     $dir1 = substr($uid, 0, 3);
     $dir2 = substr($uid, 3, 2);
     $dir3 = substr($uid, 5, 2);
     $file_path = PUBLIC_ROOT . './upload/avatar/' . $dir1 . '/' . $dir2 . '/' . $dir3;
     makeDir($file_path);
     $file_path .= '/' . substr($uid, -2) . '_';
     include_once fimport('class/image');
     $image = new Image();
     foreach ($types as $size => $wh) {
         $image->thumb($img, $wh, $wh, 1, true, $file_path . $size . '.jpg');
     }
     if (!$avatar_status) {
         UserService::updateUserScore($uid, 'user', 'avatar');
     }
     FDB::query("UPDATE " . FDB::table('user') . " SET avatar_status = 1 WHERE uid='{$uid}'");
     @unlink($img);
 }
コード例 #18
0
 function getFlightFromIGC($filename)
 {
     if (!is_file($filename)) {
         DEBUG("IGC", 1, "getFlightFromIGC: File was not found:{$filename}<br>");
         return 0;
     }
     set_time_limit(100);
     if ($this->forceBounds) {
         $startTime = $this->START_TIME;
         $endTime = $this->END_TIME;
     }
     $this->resetData();
     if ($this->forceBounds) {
         $this->START_TIME = $startTime;
         $this->END_TIME = $endTime;
     }
     $this->setAllowedParams();
     $this->filename = basename($filename);
     $this->checkForOLCfile($filename);
     $done = 0;
     $try_no_takeoff_detection = 0;
     $tm1 = time() + 3600 * 24 * 30;
     $tm2 = 0;
     while (!$done) {
         $lines = file($filename);
         $linesNum = count($lines);
         DEBUG("IGC", 1, "File has total {$linesNum} lines<br>");
         $points = 0;
         $outputBuffer = "";
         // process points
         // filter bad ones
         $p = 0;
         $Brecords = 0;
         $getPointsNum = 5;
         // + 4 points + this one
         for ($i = 0; $i < count($lines) - 10; $i++) {
             $pointOK = 1;
             $line = trim($lines[$i]);
             if (strlen($line) == 0) {
                 continue;
             }
             if ($line[0] != 'B') {
                 continue;
             }
             /* if ($i>2){
             				$prevline=trim($lines[$i-1]);
             				if  (!substr_compare($line,$prevline,1,6)) continue; 
             				//throw out Brecords with same time signatures P. Wild 4.11.2012
             			} */
             $Brecords++;
             // also check for bad points
             // 012345678901234567890123456789
             // B1522144902558N00848090EV0058400000
             if (strlen($line) < 23 || $line[24] == 'V') {
                 $lines[$i][1] = 'X';
                 continue;
             }
             $neighboors = array();
             $nextPointPos = $i;
             for ($t1 = 0; $t1 < $getPointsNum; $t1++) {
                 $thisPoint = new gpsPoint(trim($lines[$nextPointPos]), $this->timezone);
                 $neighboors[$t1] = $thisPoint;
                 $nextPointPos = $this->getNextPointPos($lines, $nextPointPos);
             }
             // got all next points
             // find mean values
             $mean_speed = 0;
             $mean_vario = 0;
             for ($t1 = 1; $t1 < $getPointsNum; $t1++) {
                 // for 4 (5-1) points in a row
                 // create arrays
                 $T_distance[$t1] = $neighboors[$t1]->calcDistance($neighboors[$t1 - 1]);
                 $T_alt[$t1] = $neighboors[$t1]->getAlt();
                 $T_deltaseconds[$t1] = $neighboors[$t1]->getTime() - $neighboors[$t1 - 1]->getTime();
                 $T_speed[$t1] = $T_deltaseconds[$t1] ? $T_distance[$t1] * 3.6 / $T_deltaseconds[$t1] : 0.0;
                 /* in km/h */
                 if ($T_deltaseconds[$t1]) {
                     $T_vario[$t1] = ($T_alt[$t1] - $neighboors[$t1 - 1]->getAlt()) / $T_deltaseconds[$t1];
                 }
                 $mean_speed += $T_speed[$t1];
                 $mean_vario += $T_vario[$t1];
             }
             $mean_speed = $mean_speed / ($getPointsNum - 1);
             $mean_vario = ($neighboors[$getPointsNum - 1]->getAlt() - $neighboors[0]->getAlt()) / ($neighboors[$getPointsNum - 1]->getTime() - $neighboors[0]->getTime());
             //if ($mean_vario<0) {
             //		DEBUG("IGC",8,"[$Brecords-$p] mean_vario :$mean_vario <0 <br>");
             //}
             $data_speed[$i] = $mean_speed;
             $data_vario[$i] = $mean_vario;
             // $mean_vario = $mean_vario/($getPointsNum-1); // mean vario is wrong
             if ($neighboors[0]->getTime() < $tm1) {
                 $tm1 = $neighboors[0]->getTime();
             }
             if ($neighboors[0]->getTime() > $tm2) {
                 $tm2 = $neighboors[0]->getTime();
             }
             if ($neighboors[0]->getTime() - $neighboors[1]->getTime() > 0) {
                 // the next point is more than one hour in the past
                 // echo "#"; $pointOK=0;
             }
             if ($T_distance[1] < 0.5 && $T_deltaseconds[1] > 2) {
                 // less than 0.5 m distance
                 $pointOK = 0;
                 DEBUG("IGC", 8, "[{$Brecords}-{$p}] Distance <0.5 m <br>");
                 $REJ_T_distance++;
                 // we dont go through the other tests
                 //echo "{$lines[$i]} =>";
                 $lines[$i][1] = 'X';
                 //echo "{$lines[$i]}<br>";
                 continue;
                 //echo $T_distance[1]."*<br>";
             }
             if (abs($mean_speed - $T_speed[1]) > 40) {
                 // diff more than 40 km/h
                 $pointOK = 0;
                 $REJ_T_mean_speed++;
                 DEBUG("IGC", 8, "[{$Brecords}-{$p}] Mean speed > 40 km/h <br>");
                 //echo "@";
             }
             //if ( abs ($mean_vario - $T_vario[1] ) > 6 ) {  // diff more than 6 m/sec
             //	$pointOK=0;
             //echo "#";
             //}
             if ($T_deltaseconds[1] == 0) {
                 $pointOK = 0;
                 $REJ_T_zero_time_diff++;
                 DEBUG("IGC", 8, "[{$Brecords}-{$p}] No time Diff<br>");
             }
             if ($T_alt[1] > $this->maxAllowedHeight) {
                 $pointOK = 0;
                 $REJ_max_alt++;
             }
             if (abs($T_speed[1]) > $this->maxAllowedSpeed) {
                 $pointOK = 0;
                 $REJ_max_speed++;
                 DEBUG("IGC", 8, "[{$Brecords}-{$p}] > " . abs($T_speed[1]) . "km/h max allowed speed<br>");
                 // echo "S";
             }
             if (abs($T_vario[1]) > $this->maxAllowedVario) {
                 $pointOK = 0;
                 $REJ_max_vario++;
                 // echo "V";
                 DEBUG("IGC", 8, "[{$Brecords}-{$p}] > " . abs($T_vario[1]) . "m/sec  > max allowed vario<br>");
             }
             if ($p < 5 && !$try_no_takeoff_detection && !$this->forceBounds) {
                 // first 5 points need special care
                 $takeoffMaxSpeed = $this->maxAllowedSpeed * 0.5;
                 DEBUG("IGC", 8, "[{$Brecords}-{$p}] TAKEOFF sequence SPEED: " . abs($T_speed[1]) . " max:{$takeoffMaxSpeed}<br>");
                 if (abs($T_speed[1]) > $takeoffMaxSpeed) {
                     $pointOK = 0;
                     $REJ_max_speed_start++;
                     // echo "s";
                 }
                 if (abs($T_vario[1]) > $this->maxAllowedVario * 0.4) {
                     $pointOK = 0;
                     $REJ_max_vario_start++;
                     //echo "v";
                 }
             }
             if (!$pointOK) {
                 $lines[$i][1] = 'X';
             } else {
                 $p++;
                 if ($p == 5) {
                     DEBUG("IGC", 1, "Passed the strict testing (p=5)<br>");
                 }
             }
         }
         DEBUG("IGC", 1, "REJ: [{$REJ_T_distance}] <0.5 distance<br>");
         DEBUG("IGC", 1, "REJ: [{$REJ_T_zero_time_diff}] zero_time_diff<br>");
         DEBUG("IGC", 1, "REJ: [{$REJ_T_mean_speed}] mean_speed diff >40km/h<br>");
         DEBUG("IGC", 1, "REJ: [{$REJ_max_alt}] >max_alt<br>");
         DEBUG("IGC", 1, "REJ: [{$REJ_max_speed}] >max_speed<br>");
         DEBUG("IGC", 1, "REJ: [{$REJ_max_vario}] >max_vario<br>");
         DEBUG("IGC", 1, "REJ: [{$REJ_max_speed_start}] >max_speed_start<br>");
         DEBUG("IGC", 1, "REJ: [{$REJ_max_vario_start}] >max_vario_start<br>");
         DEBUG("IGC", 1, "Found {$p} valid B records out of {$Brecords} total<br>");
         if ($p > 0) {
             $done = 1;
         } else {
             if ($Brecords > 0 && $REJ_T_zero_time_diff / $Brecords > 0.9) {
                 // more than 90% stopped points
                 $lines = file($filename);
                 $done = 1;
                 $garminSpecialCase = 1;
                 $p = $Brecords;
                 DEBUG("IGC", 1, "Many Stopped points, it is a Garmin Special Case<br>");
             } else {
                 if (!$try_no_takeoff_detection) {
                     $try_no_takeoff_detection = 1;
                     DEBUG("IGC", 1, "Will try no_takeoff_detection<br>");
                 } else {
                     $done = 1;
                 }
             }
         }
     }
     // while not done
     //
     if ($p == 0) {
         DEBUG("IGC", 1, "NO VALID POINTS FOUND");
         return 0;
         // no valid points found
     }
     $mod = 0;
     if ($p > $this->maxPointNum) {
         $reduceArray = getReduceArray($p, $this->maxPointNum);
         // print_r($recudeArray);
         $mod = count($reduceArray);
         // $mod= ceil( $p / $this->maxPointNum );
     }
     DEBUG("IGC", 1, "will use a reduce array of length {$mod}<br>");
     $duration = $tm2 - $tm1;
     $intervalSecs = round($duration / $p);
     // echo "<hr>good points: $p duration:$duration, intervalSecs:$intervalSecs<hr>";
     $pointsNeededForTakeoff = 5;
     if ($intervalSecs >= 8) {
         $pointsNeededForTakeoff = 2;
     }
     $alreadyInPoints = 0;
     $stopReadingPoints = 0;
     $this->timezone = 1000;
     $day_offset = 0;
     $foundNewTrack = 0;
     $slow_points = 0;
     $slow_points_dt = 0;
     $stillOnGround = 1;
     $tmpDate = 0;
     foreach ($lines as $iii => $line) {
         if ($foundNewTrack) {
             break;
         }
         $outputLine = $line;
         $line = trim($line);
         if (strlen($line) == 0) {
             continue;
         }
         // if (strtoupper(substr($line,0,1)) !="B" ) echo "@$line<BR>";
         if (strtoupper(substr($line, 0, 3)) == "OLC") {
             continue;
         }
         // it is an olc file , dont put the OLC... line in to the saned file
         if (strtoupper(substr($line, 0, 5)) == "HFDTE" || strtoupper(substr($line, 0, 5)) == "HPDTE") {
             // HFDTE170104  OR HPDTE310805
             if ($alreadyInPoints && $points > 0) {
                 if ($prevPoint->gpsTime < 86200) {
                     // if last good point is > 86200 (200 secs before day change at 86400) we dont treat this as a new track
                     $stopReadingPoints = 1;
                     DEBUG("IGC", 1, "[{$points}] {$line}<br>");
                     DEBUG("IGC", 1, "[{$points}] Found a new track (NEW HFDTE)<br>");
                 }
             } else {
                 $this->DATE = substr($line, 5, 6);
                 $yr_last = substr($this->DATE, 4, 2);
                 // case of YY=0 (1 digit) HFDTE08070
                 if ($yr_last == "0") {
                     $yr_last = "00";
                 }
                 if ($yr_last > 80) {
                     $yr = "19" . $yr_last;
                 } else {
                     $yr = "20" . $yr_last;
                 }
                 $this->DATE = $yr . "-" . substr($this->DATE, 2, 2) . "-" . substr($this->DATE, 0, 2);
                 $alreadyInPoints = 1;
             }
         } else {
             if (strtoupper(substr($line, 0, 13)) == "HFTZOTIMEZONE") {
                 // HFTZOTimezone:3 OR HFTZOTimezone:-8
                 $this->timezone = substr($line, 14) + 0;
                 // echo $this->timezone."#^^";
             } else {
                 if (strtoupper(substr($line, 2, 13)) == "GTYGLIDERTYPE") {
                     // HOGTYGLIDERTYPE: Gradient Bliss 26  OR  HPGTYGliderType:Gradient Nevada
                     if (!$this->glider) {
                         $this->glider = trim(substr($line, 16));
                     }
                     // HFGTYGLIDERTYPE
                     // HOGTYGLIDERTYPE
                 } else {
                     if ($line[0] == 'B') {
                         if ($stopReadingPoints) {
                             continue;
                         }
                         if ($line[1] == 'X') {
                             DEBUG("IGC", 1, "[{$points}] BAD : {$line}<br>");
                             continue;
                             // MARKED BAD from BEFORE
                         }
                         if (strlen($line) < 23 || strlen($line) > 100) {
                             continue;
                         }
                         if ($points == 0) {
                             // first point
                             //				echo "######## first point <br>";
                             $firstPoint = new gpsPoint($line, $this->timezone);
                             if ($this->timezone == 1000) {
                                 // no timezone in the file
                                 // echo "calc timezone<br>";
                                 $this->timezone = getUTMtimeOffset($firstPoint->lat, $firstPoint->lon, $this->DATE);
                                 $this->timezone = getTZ($firstPoint->lat, $firstPoint->lon, $this->DATE);
                                 // echo 	$this->timezone;
                                 $firstPoint->timezone = $this->timezone;
                             }
                             $tmpTime = $firstPoint->gpsTime + $this->timezone * 3600;
                             // Now also check if we are one day minus (for US flights )
                             if ($tmpTime < 0 && $tmpDate == 0) {
                                 // one day before!
                                 $this->DATE = dates::moveDaysFromDate($this->DATE, -1);
                                 $tmpDate = 1;
                             }
                             // take care of day change for timezones in australia/nz etc
                             if ($tmpTime > 86400 && $tmpDate == 0) {
                                 // UTC date in the igc file  needs to be +1
                                 $this->DATE = dates::moveDaysFromDate($this->DATE, 1);
                                 $tmpDate = 1;
                             }
                             // sanity checks
                             if ($firstPoint->getAlt() > $this->maxAllowedHeight) {
                                 continue;
                             }
                             // echo "times: ".$firstPoint->gpsTime.", ".$firstPoint->getTime()." start_time: ".$this->START_TIME ."<BR> ";
                             if ($this->forceBounds && !$this->checkBound($firstPoint->getTime())) {
                                 continue;
                             }
                             // not inside time window
                             //$this->FIRST_POINT=$line;
                             $this->firstPointTM = $firstPoint->gpsTime;
                             $this->firstLat = $firstPoint->lat();
                             $this->firstLon = $firstPoint->lon();
                             $this->TAKEOFF_ALT = $firstPoint->getAlt();
                             $this->MIN_ALT = $firstPoint->getAlt();
                             if (!$this->forceBounds) {
                                 $this->START_TIME = $firstPoint->getTime();
                             }
                             $prevPoint = new gpsPoint($line, $this->timezone);
                             $prevPoint2 = new gpsPoint($line, $this->timezone);
                         } else {
                             $lastPoint = new gpsPoint($line, $this->timezone);
                             $lastPoint->gpsTime += $day_offset;
                             if ($this->forceBounds && !$this->checkBound($lastPoint->getTime())) {
                                 $lastPoint = $prevPoint;
                                 continue;
                                 // not inside time window
                             }
                             $time_diff = $lastPoint->getTime() - $prevPoint->getTime();
                             $time_diff2 = $lastPoint->getTime() - $prevPoint2->getTime();
                             // echo "time diff: $time_diff # $line<br>";
                             if ($time_diff < 0 && $time_diff > -36000) {
                                 // if the time is less than 10 hours in the past  we just ignore it
                                 // $day_offset = 86400; // if time seems to have gone backwards, add a day
                                 DEBUG("IGC", 1, "[{$points}] {$line}<br>");
                                 DEBUG("IGC", 1, "[{$points}] Point in the past<br>");
                                 continue;
                             } else {
                                 if ($time_diff < 0 && $time_diff > -86000) {
                                     // CHANGING DAY , means the flight is at night
                                     $lastPoint = $prevPoint;
                                     $foundNewTrack = 1;
                                     DEBUG("IGC", 1, "[{$points}] {$line}<br>");
                                     DEBUG("IGC", 1, "[{$points}] Flight at night ????<br>");
                                     continue;
                                 } else {
                                     if ($time_diff > $this->max_allowed_time_gap) {
                                         // found time gap
                                         // if we are forceBounds check to see if inside window
                                         if ($this->forceBounds && !$this->checkBound($lastPoint->getTime()) || !$this->forceBounds) {
                                             // if we are still on the ground  we dont care about time gap
                                             if (!$stillOnGround) {
                                                 // not inside time window  OR not checking go ahead
                                                 $lastPoint = $prevPoint;
                                                 $foundNewTrack = 1;
                                                 DEBUG("IGC", 1, "[{$points}] {$line}<br>");
                                                 DEBUG("IGC", 1, "[{$points}] Found a new track (Time diff of {$time_diff} secs)<br>");
                                                 continue;
                                             }
                                         } else {
                                             // inside the window, forced to continue
                                         }
                                     }
                                 }
                             }
                             $this->LAST_POINT = $line;
                             // compute some things
                             $tmp = $lastPoint->calcDistance($prevPoint);
                             $alt = $lastPoint->getAlt();
                             // GUS begin
                             $deltaseconds = $lastPoint->getTime() - $prevPoint->getTime();
                             $speedDeltaSecs = $deltaseconds + ($deltaseconds < -85000 ? 86400 : 0);
                             $speed = $speedDeltaSecs ? $tmp * 3.6 / $speedDeltaSecs : 0.0;
                             /* in km/h */
                             if ($speedDeltaSecs) {
                                 $vario = ($alt - $prevPoint->getAlt()) / $speedDeltaSecs;
                             }
                             // GUS end
                             if (!$garminSpecialCase && !$this->forceBounds) {
                                 if (($fast_points >= $pointsNeededForTakeoff || $fast_points_dt > 30) && $stillOnGround) {
                                     // found 5 flying points or 30 secs
                                     $stillOnGround = 0;
                                     DEBUG("IGC", 1, "[{$points}] {$line}<br>");
                                     DEBUG("IGC", 1, "[{$points}] Found Takeoff <br>");
                                 }
                                 if ($stillOnGround) {
                                     //takeoff scan
                                     // either speed >= 15 or if we already have 2 fast points settle with speed>=10
                                     if ($speed >= 15 || $speed >= 10 && $fast_points >= 2) {
                                         $fast_points++;
                                         $fast_points_dt += $speedDeltaSecs;
                                         DEBUG("IGC", 1, "[{$points}] {$line}<br>");
                                         DEBUG("IGC", 1, "[{$points}] Found a fast speed point <br>");
                                     } else {
                                         // reset takeoff scan
                                         DEBUG("IGC", 1, "[{$points}] {$line}<br>");
                                         DEBUG("IGC", 1, "[{$points}] takeoff scan: speed: {$speed}  time_diff: {$time_diff}<br>");
                                         $fast_points = 0;
                                         $fast_points_dt = 0;
                                     }
                                     $points = 0;
                                     continue;
                                 } else {
                                     //landing  scan
                                     if ($speed < 5) {
                                         $slow_points++;
                                         $slow_points_dt += $speedDeltaSecs;
                                         DEBUG("IGC", 1, "[{$points}] {$line}<br>");
                                         DEBUG("IGC", 1, "[{$points}] Found a slow speed point (speed, dt)=({$speed},{$speedDeltaSecs})<br>");
                                     } else {
                                         $slow_points = 0;
                                         $slow_points_dt = 0;
                                     }
                                 }
                                 // found landing (5 stopped points and >2mins) or 5 mins (300 secs)
                                 if ($slow_points > $pointsNeededForTakeoff && $slow_points_dt > 180 || $slow_points_dt > 300) {
                                     $foundNewTrack = 1;
                                     DEBUG("IGC", 1, "[{$points}] {$line}<br>");
                                     DEBUG("IGC", 1, "[{$points}] Found a new track  /landing <br>");
                                 }
                             }
                             // sanity checks
                             if ($deltaseconds == 0 && !$garminSpecialCase) {
                                 continue;
                             }
                             if ($alt > $this->maxAllowedHeight) {
                                 continue;
                             }
                             if (abs($speed) > $this->maxAllowedSpeed) {
                                 continue;
                             }
                             if (abs($vario) > $this->maxAllowedVario) {
                                 continue;
                             }
                             $takeoffDistance = $lastPoint->calcDistance($firstPoint);
                             if ($takeoffDistance > $this->LINEAR_DISTANCE) {
                                 $this->LINEAR_DISTANCE = $takeoffDistance;
                             }
                             if ($time_diff2 > 10) {
                                 $tmp = $lastPoint->calcDistance($prevPoint2);
                                 $alt = $lastPoint->getAlt();
                                 $deltaseconds = $time_diff2;
                                 // GUS begin
                                 $speedDeltaSecs = $deltaseconds + ($deltaseconds < -85000 ? 86400 : 0);
                                 $speed = $speedDeltaSecs ? $tmp * 3.6 / $speedDeltaSecs : 0.0;
                                 /* in km/h */
                                 if ($speedDeltaSecs) {
                                     $vario = ($alt - $prevPoint2->getAlt()) / $speedDeltaSecs;
                                 }
                                 // GUS end
                                 $prevPoint2 = new gpsPoint($line, $this->timezone);
                                 $prevPoint2->gpsTime += $day_offset;
                                 // update maximum speed
                                 if ($speed > $this->MAX_SPEED) {
                                     $this->MAX_SPEED = $speed;
                                 }
                                 $this->MEAN_SPEED += $speed;
                                 $MEAN_SPEED_POINTS++;
                                 // UPDATE MIN-MAX VARIO
                                 if ($vario > $this->MAX_VARIO) {
                                     $this->MAX_VARIO = $vario;
                                 }
                                 if ($vario < $this->MIN_VARIO) {
                                     $this->MIN_VARIO = $vario;
                                 }
                             }
                             //$speed=$data_speed[$iii-1]+0;
                             // $vario=$data_vario[$iii-1]+0;
                             // UPDATE MIN-MAX ALT
                             if ($alt > $this->MAX_ALT) {
                                 $this->MAX_ALT = $alt;
                             }
                             if ($alt < $this->MIN_ALT) {
                                 $this->MIN_ALT = $alt;
                             }
                             // end computing
                             $prevPoint = new gpsPoint($line, $this->timezone);
                             $prevPoint->gpsTime += $day_offset;
                             if ($mod >= 1) {
                                 if ($reduceArray[$points % $mod] == 0) {
                                     $outputLine = "";
                                 }
                             }
                         }
                         $points++;
                     }
                 }
             }
         }
         // end else
         $outputBuffer .= $outputLine;
     }
     // end main loop
     // echo "<HR>MIN VARIO".$this->MIN_VARIO."<HR>";
     //
     if ($stillOnGround && $this->LINEAR_DISTANCE < 50) {
         DEBUG("IGC", 1, "NO TAKEOFF FOUND: ");
         return 0;
         // no valid points found
     }
     $path_igc = dirname($this->getIGCFilename(1));
     if (!is_dir($path_igc)) {
         makeDir($path_igc, 0755);
     }
     /*write the full saned file */
     $fullSanedFile = '';
     foreach ($lines as $line) {
         $line = trim($line);
         if (strlen($line) == 0) {
             continue;
         }
         if ($line[0] == 'B' && $line[1] == 'X') {
             continue;
         }
         // MARKED BAD from BEFORE
         // if  ( strlen($line) < 23 || strlen($line) > 100  ) continue;
         $fullSanedFile .= $line . "\n";
     }
     if (!writeFile($this->getIGCFilename(2), $fullSanedFile)) {
         echo "Problem writing to file (" . $this->getIGCFilename(2) . ")";
     }
     DEBUG("IGC", 1, "<HR>" . $this->getIGCFilename(2) . ' size: ' . strlen($fullSanedFile) . "<HR>");
     // echo "<HR><HR>". $this->getIGCFilename(2) .strlen($fullSanedFile)."<HR><HR>";
     /* done wrting the full saned file */
     // write saned IGC file
     if (!writeFile($this->getIGCFilename(1), $outputBuffer)) {
         echo "Problem writing to file (" . $this->getIGCFilename(1) . ")";
     }
     // done write saned IGC file
     DEBUG("IGC", 1, "<HR>" . $this->getIGCFilename(1) . ' size: ' . strlen($outputBuffer) . "<HR>");
     if ($lastPoint) {
         $this->lastPointTM = $lastPoint->gpsTime;
         $this->lastLon = $lastPoint->lon();
         $this->lastLat = $lastPoint->lat();
         $this->LANDING_ALT = $lastPoint->getAlt();
         $this->END_TIME = $lastPoint->getTime();
     } else {
         $this->lastPointTM = 0;
         $this->lastLon = 0;
         $this->lastLat = 0;
         $this->LANDING_ALT = 0;
         $this->END_TIME = 0;
     }
     $this->DURATION = $this->END_TIME - $this->START_TIME;
     if ($this->DURATION < 0) {
         $this->DURATION += 86400;
     }
     $this->MEAN_SPEED = $this->MEAN_SPEED / $MEAN_SPEED_POINTS;
     return 1;
 }
コード例 #19
0
ファイル: init.php プロジェクト: hung5s/yap
function makeWritable($path)
{
    if (!file_exists($path) && !makeDir($path)) {
        return 0;
    }
    @chmod($path, 0777);
    if (is_writable($path)) {
        return 1;
    } else {
        return 0;
    }
}
コード例 #20
0
function main($subDir, $class, $cookieURL, $indexURL, $totalClass, $curClass, $code)
{
    $isSleep = true;
    makeDir("./html/{$subDir}/{$class}/");
    $dataFileName = "data/{$subDir}/{$class}.log";
    $httpClient = new HttpClient("epub.cnki.net");
    $content = "";
    $indexFname = "./html/{$subDir}/{$class}/index.html";
    $tf = iconv("utf-8", "gb2312", $indexFname);
    $cookies = "";
    if (file_exists($tf)) {
        $isSleep = false;
        $content = file_get_contents($tf);
        echo "From cache get index.....\n";
    } else {
        /*获取并设置cookie*/
        $httpClient->get($cookieURL);
        $cookies = $httpClient->getCookies();
        $httpClient->setCookies($cookies);
        if (!$cookies) {
            die("cookie error");
        }
        $isSleep = true;
        $httpClient->get($indexURL);
        $content = $httpClient->getContent();
        save($indexFname, $content);
        //保存
        echo "save index file...\n";
    }
    /* 解析出一共有多少页面 */
    $pageCount = parsePageCount($content);
    echo "Page is {$pageCount} ****\n";
    $articleCount = ARTICLE_PRE_PAGE * $pageCount;
    //计算一共有多少篇文章,大于等于实际文章数目,不影响结果
    echo "total article is {$articleCount}\n";
    $pageCount = $articleCount / ARTICLE_PRE_PAGE;
    $pageCount = ceil($pageCount);
    //向上取整,不放过任何数据
    if ($pageCount == 0) {
        $pageCount = 1;
    }
    if ($pageCount > 50) {
        echo "page count is big than 50\n";
    }
    echo "total page of {$class} is : {$pageCount}...............{$curClass} of {$totalClass}\n";
    if ($isSleep) {
        fakeSleep();
    }
    /* 抓取每一个页面并且保存下来,保存的同时进行解析 */
    for ($i = 1; $i <= $pageCount; $i++) {
        $content = NULL;
        $pageI = getPageI($indexURL, $i);
        //第i页的地址
        $htmlI = "./html/{$subDir}/{$class}/{$i}.html";
        if (!file_exists(iconv("utf-8", "gb2312", $htmlI))) {
            $isSleep = true;
            $httpClient->setCookies($cookies);
            $httpClient->get($pageI);
            $content = $httpClient->getContent();
            save($htmlI, $content);
            echo "From newwork & save {$i}.html..........[{$i} of {$pageCount}]\n";
        } else {
            $tmpf2 = iconv("utf-8", "gb2312", $htmlI);
            $content = file_get_contents($tmpf2);
            $ok = validatePageContent($content);
            //是否出现了验证码
            if (!$ok) {
                $i = $i - 1;
                delFile($htmlI);
            } else {
                $isSleep = false;
                echo "Find local file {$htmlI} & skip\n";
            }
            //continue;
        }
        $logName = "./data/{$subDir}/{$class}.log";
        if (!validatePageContent($content)) {
            $i = $i - 1;
            delFile($htmlI);
            dosleep(60);
            $httpClient = new HttpClient("epub.cnki.net");
            $httpClient->get($cookieURL);
            $cookies = $httpClient->getCookies();
            $httpClient->setCookies($cookies);
            continue;
        }
        parseContent($content, $logName, $code);
        if ($i != $pageCount && $isSleep) {
            fakeSleep();
        } else {
            echo "+\n";
            echo "+\n";
            echo "+ {$class} done\n";
            echo "+\n";
            echo "+\n";
        }
    }
}
コード例 #21
0
/**
 * 创建前台管理锁定
 * @return void
 */
function createManageLock($module, $id)
{
    global $_FANWE;
    $module = strtolower($module);
    $phth = PUBLIC_ROOT . './manage/' . $module;
    makeDir($phth);
    $lock_file = $phth . '/' . $id . '.lock';
    $data = array('uid' => $_FANWE['uid'], 'user_name' => $_FANWE['user_name'], 'time' => TIME_UTC);
    $data = "<?php\n" . '$lock = ' . var_export($data, true) . ";\n?>";
    return writeFile($lock_file, $data);
}
コード例 #22
0
ファイル: Content.php プロジェクト: viyancs/bolt
 public function setFromPost($values, $contenttype)
 {
     $values = cleanPostedData($values);
     if (!$this->id) {
         // this is a new record: current user becomes the owner.
         $user = $this->app['users']->getCurrentUser();
         $this['ownerid'] = $user['id'];
     }
     // If the owner is set explicitly, check if the current user is allowed
     // to do this.
     if (isset($values['ownerid'])) {
         if ($this['ownerid'] != $values['ownerid']) {
             if (!$this->app['users']->isAllowed("contenttype:{$contenttype}:change-ownership:{$this->id}")) {
                 throw new \Exception("Changing ownership is not allowed.");
             }
             $this['ownerid'] = intval($values['ownerid']);
         }
     }
     // Make sure we have a proper status..
     if (!in_array($values['status'], array('published', 'timed', 'held', 'draft'))) {
         if ($this['status']) {
             $values['status'] = $this['status'];
         } else {
             $values['status'] = "draft";
         }
     }
     // If we set a 'publishdate' in the future, and the status is 'published', set it to 'timed' instead.
     if ($values['datepublish'] > date("Y-m-d H:i:s") && $values['status'] == "published") {
         $values['status'] = "timed";
     }
     // Get the taxonomies from the POST-ed values. We don't support 'order' for taxonomies that
     // can have multiple values.
     // @todo use $this->setTaxonomy() for this
     if (!empty($values['taxonomy'])) {
         foreach ($values['taxonomy'] as $taxonomytype => $value) {
             if (!is_array($value)) {
                 $value = explode(",", $value);
             }
             if (isset($values['taxonomy-order'][$taxonomytype])) {
                 foreach ($value as $k => $v) {
                     $value[$k] = $v . "#" . $values['taxonomy-order'][$taxonomytype];
                 }
             }
             $this->taxonomy[$taxonomytype] = $value;
         }
         unset($values['taxonomy']);
         unset($values['taxonomy-order']);
     }
     // Get the relations from the POST-ed values.
     // @todo use $this->setRelation() for this
     if (!empty($values['relation'])) {
         $this->relation = $values['relation'];
         unset($values['relation']);
     }
     // @todo check for allowed file types..
     // Handle file-uploads.
     if (!empty($_FILES)) {
         foreach ($_FILES as $key => $file) {
             if (empty($file['name'][0])) {
                 continue;
                 // Skip 'empty' uploads..
             }
             $filename = sprintf("%s/files/%s/%s", $this->app['paths']['rootpath'], date("Y-m"), safeString($file['name'][0], false, "[]{}()"));
             $basename = sprintf("/%s/%s", date("Y-m"), safeString($file['name'][0], false, "[]{}()"));
             if ($file['error'][0] != UPLOAD_ERR_OK) {
                 $this->app['log']->add("Upload: Error occured during upload: " . $file['error'][0] . " - " . $filename, 2);
                 continue;
             }
             if (substr($key, 0, 11) != "fileupload-") {
                 $this->app['log']->add("Upload: skipped an upload that wasn't for Content. - " . $filename, 2);
                 continue;
             }
             $fieldname = substr($key, 11);
             // Make sure the folder exists.
             makeDir(dirname($filename));
             // Check if we don't have doubles.
             if (is_file($filename)) {
                 while (is_file($filename)) {
                     $filename = $this->upcountName($filename);
                     $basename = $this->upcountName($basename);
                 }
             }
             if (is_writable(dirname($filename))) {
                 // Yes, we can create the file!
                 move_uploaded_file($file['tmp_name'][0], $filename);
                 $this->app['log']->add("Upload: uploaded file '{$basename}'.", 2);
                 $values[$fieldname] = $basename;
             } else {
                 $this->app['log']->add("Upload: couldn't write upload '{$basename}'.", 2);
             }
         }
     }
     $this->setValues($values);
 }
コード例 #23
0
ファイル: index.php プロジェクト: viyancs/bolt
/*
 * jQuery File Upload Plugin PHP Example 5.7
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2010, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/MIT
 */
error_reporting(E_ALL | E_STRICT);
if (strpos(__DIR__, DIRECTORY_SEPARATOR . 'bolt-public' . DIRECTORY_SEPARATOR) !== false) {
    // installed bolt with composer
    require_once __DIR__ . '/../../../../vendor/bolt/bolt/app/bootstrap.php';
} else {
    require_once __DIR__ . '/../../bootstrap.php';
}
// Make sure the session is started.
if (session_id() == "") {
    session_start();
}
// Don't do anything if we're not logged in..
if (!isset($_SESSION['_sf2_attributes']['user']['id'])) {
    echo "Not logged in.";
    die;
}
// Make sure the folder exists.
makeDir(__DIR__ . '/../../../files/' . date('Y-m'));
require 'upload.class.php';
$upload_handler = new UploadHandler(array('upload_dir' => dirname(dirname(dirname(dirname($_SERVER['SCRIPT_FILENAME'])))) . '/files/' . date('Y-m') . "/", 'upload_url' => '/files/' . date('Y-m') . "/", 'accept_file_types' => '/\\.(gif|jpe?g|png|zip|tgz|txt|md|docx?|pdf|xlsx?|pptx?|mp3|ogg|wav|m4a|mp4|m4v|ogv|wmv|avi|webm)$/i'));
コード例 #24
0
 function execute()
 {
     global $PIVOTX;
     if (!$this->active) {
         return;
     }
     $messages[] = "Checking email..";
     // Create the class and fetch the list of available emails..
     if ($this->cfg['use_imap']) {
         $mail = new Mail();
         $protocol = strtolower(substr($this->cfg['imap_protocol'], 0, 4));
         if (str_replace($protocol, '', $this->cfg['imap_protocol']) == 's') {
             $secure = true;
         } else {
             $secure = false;
         }
         $server = array('type' => $protocol, 'server' => $this->cfg['server'], 'secure' => $secure, 'mailbox' => $this->cfg['imap_mailbox'], 'username' => $this->cfg['username'], 'password' => $this->cfg['password']);
         if (!$mail->connect($server)) {
             debug("Moblog: No connection (using IMAP extension).");
             exit(1);
         } else {
             $messages[] = "Moblog: OK connection (using IMAP extension).\n";
         }
         $mail->parse_messages();
         if (is_array($mail->messages)) {
             $listing = $mail->messages;
         } else {
             $listing = array();
         }
     } else {
         $pop3 = new Net_POP3();
         $ret = $pop3->connect($this->cfg['server'], $this->cfg['pop_port']);
         if (!$ret) {
             debug("Moblog: No connection.");
             exit(1);
         } elseif (PEAR::isError($ret = $pop3->login($this->cfg['username'], $this->cfg['password'], 'USER'))) {
             debug("Moblog: error logging in: " . $ret->getMessage());
             exit(1);
         } else {
             $messages[] = "Moblog: OK connection.\n";
         }
         $listing = $pop3->getListing();
     }
     $messages[] = count($listing) . " email found on the server.";
     $regen = false;
     // Then we iterate through the list..
     foreach ($listing as $list_item) {
         if ($this->cfg['use_imap']) {
             $msg_id = $list_item['message_id'];
             $email = $list_item['rawdata'];
         } else {
             $msg_id = $list_item['msg_id'];
             $email = $pop3->getMsg($msg_id);
         }
         $messages[] = "fetched mail {$msg_id}";
         if (!$this->cfg['leave_on_server']) {
             if ($this->cfg['use_imap']) {
                 $mail->delete($list_item['msgno']);
             } else {
                 $pop3->deleteMsg($msg_id);
             }
             $messages[] = "Message was deleted from the server..";
         } else {
             $messages[] = "Message was left on the server (if supported)..";
         }
         // Perhaps save a local copy..
         if ($this->cfg['save_mail']) {
             $maildir = $PIVOTX['paths']['db_path'] . 'mail/';
             if (!file_exists($maildir)) {
                 makeDir($maildir);
             }
             $msg_id = str_replace(array('<', '>'), '', $msg_id);
             $filename = $maildir . date("Ymd-His") . "-" . $msg_id . ".eml";
             if ($fp = fopen($filename, "w")) {
                 fwrite($fp, $email);
                 $messages[] = "Local copy saved as: {$filename}";
                 fclose($fp);
             } else {
                 $messages[] = "Alas! Woe is me! I couldn't save a local copy.";
             }
         }
         $this->entry = array();
         // Parse and post the email..
         $this->parse_email($email);
         $messages[] = $this->compose_entry();
         $regen = true;
     }
     if ($this->cfg['use_imap']) {
         $mail->close();
     } else {
         $pop3->disconnect();
     }
     if ($regen) {
         // Clear cache?
         // $messages[] = "Cleared cache after adding new moblog entry";
     }
     $messages[] = "Done!";
     return $messages;
 }
コード例 #25
0
ファイル: common.php プロジェクト: snowtl/tanglang
/**
 +----------------------------------------------------------
* 功能:检测一个目录是否存在,不存在则创建它
 +----------------------------------------------------------
* @param string    $path      待检测的目录
 +----------------------------------------------------------
* @return boolean
 +----------------------------------------------------------
*/
function makeDir($path)
{
    return is_dir($path) or makeDir(dirname($path)) and @mkdir($path, 0777);
}
コード例 #26
0
ファイル: content.php プロジェクト: LeonB/site
 public function setFromPost($values, $contenttype)
 {
     global $app;
     $values = cleanPostedData($values);
     // Some field type need to do things to the POST-ed value.
     foreach ($contenttype['fields'] as $fieldname => $field) {
         if ($field['type'] == "video" && isset($values[$fieldname])) {
             $video = $values[$fieldname];
             // update the HTML, according to given width and height
             if (!empty($video['width']) && !empty($video['height'])) {
                 $video['html'] = preg_replace("/width=(['\"])([0-9]+)(['\"])/i", 'width=${1}' . $video['width'] . '${3}', $video['html']);
                 $video['html'] = preg_replace("/height=(['\"])([0-9]+)(['\"])/i", 'height=${1}' . $video['height'] . '${3}', $video['html']);
             }
             $responsiveclass = "responsive-video";
             // See if it's widescreen or not..
             if ($video['width'] / $video['height'] > 1.76) {
                 $responsiveclass .= " widescreen";
             }
             if (strpos($video['url'], "vimeo") !== false) {
                 $responsiveclass .= " vimeo";
             }
             $video['responsive'] = sprintf('<div class="%s">%s</div>', $responsiveclass, $video['html']);
             $values[$fieldname] = $video;
         }
     }
     // TODO: check for allowed file types..
     // Handle file-uploads.
     if (!empty($_FILES)) {
         foreach ($_FILES as $key => $file) {
             $filename = sprintf("%s/files/%s/%s", $app['paths']['rootpath'], date("Y-m"), safeString($file['name'][0], false, "[]{}()"));
             $basename = sprintf("/%s/%s", date("Y-m"), safeString($file['name'][0], false, "[]{}()"));
             if ($file['error'][0] != UPLOAD_ERR_OK) {
                 $app['log']->add("Upload: Error occured during upload: " . $file['error'][0], 2);
                 continue;
             }
             if (substr($key, 0, 11) != "fileupload-") {
                 $app['log']->add("Upload: skipped an upload that wasn't for Content.", 2);
                 continue;
             }
             $fieldname = substr($key, 11);
             // Make sure the folder exists.
             makeDir(dirname($filename));
             // Check if we don't have doubles.
             if (is_file($filename)) {
                 while (is_file($filename)) {
                     $filename = $this->upcount_name($filename);
                     $basename = $this->upcount_name($basename);
                 }
             }
             if (is_writable(dirname($filename))) {
                 // Yes, we can create the file!
                 move_uploaded_file($file['tmp_name'][0], $filename);
                 $app['log']->add("Upload: uploaded file '{$basename}'.", 2);
                 $values[$fieldname] = $basename;
             } else {
                 $app['log']->add("Upload: couldn't write upload '{$basename}'.", 2);
             }
         }
     }
     $this->setValues($values);
 }
コード例 #27
0
    $htaccessFiledir = '/' . $htaccessFiledir;
}
$mod_conf_File = dirname(__FILE__) . '/site/config_mod_rewrite.php';
if ($_POST['writeFile'] == 1) {
    $conf_str = '<?
	$CONF[\'links\'][\'type\']=3;
	$CONF[\'links\'][\'baseURL\']=\'' . $virtPath . '\';
?>';
    if (writeFile($mod_conf_File, $conf_str)) {
        echo "<span class='ok'>config_mod_rewrite.php updated</span>";
    } else {
        echo "<span class='alert'>PROBLEM in updating config_mod_rewrite.php</span>";
    }
    if (!is_dir($htaccessFiledir)) {
        echo "<span class='note'>Creating folder {$htaccessFiledir}</span>";
        makeDir($htaccessFiledir);
    }
    if (writeFile($htaccessFile, $str)) {
        echo "<span class='ok'>htaccess file written</span>";
    } else {
        echo "<span class='alert'>PROBLEM In writing htaccess file </span>";
    }
    // echo "<script lang='javascript'>window.location=''	< /script>";
    echo "<span class='info'><a href='javascript:window.location=\"\";'>Click here to reload</a></span>";
} else {
    if ($_POST['writeFile'] == -1) {
        $conf_str = '<?
	$CONF[\'links\'][\'type\']=1;
	$CONF[\'links\'][\'baseURL\']=\'' . $virtPath . '\';
?>';
        if (writeFile($mod_conf_File, $conf_str)) {
コード例 #28
0
ファイル: timthumb.php プロジェクト: nirolph/bolt
 /**
  * Saves a copy of the created thumbnail with a 'nice' filename, like /thumbs/320x240/sample.jpg.
  * This makes it possible for subsequent requests to the same image, to circumvent the PHP layer altogether.
  *
  * @param $filename
  */
 protected function boltSaveCopy($filename)
 {
     global $config;
     if ($config['general']['thumbnails']['save_files'] != true) {
         return;
     }
     // Make sure the paths exists. Try to create it, if possible.
     $pathparts = explode("/", $_GET['requestname']);
     $path = dirname(dirname(__DIR__)) . "/" . implode("/", array_slice($pathparts, 0, count($pathparts) - 1));
     makeDir($path);
     // Copy the file, and chmod
     $newfilename = dirname(dirname(__DIR__)) . "/" . urldecode($_GET['requestname']);
     copy($filename, $newfilename);
     @chmod($newfilename, octdec('0666'));
 }
コード例 #29
0
 public function getPrice($img)
 {
     $dir = './public/upload/temp/' . fToDate(NULL, 'Y/m/d/H');
     $file_name = md5(microtime(true)) . random('6') . '.png';
     makeDir(FANWE_ROOT . $dir);
     $file_path = FANWE_ROOT . $dir . "/" . $file_name;
     $img_data = getUrlContent($img);
     if (empty($img_data) || @file_put_contents($file_path, $img_data) == 0) {
         return false;
     }
     $xs_count = 2;
     $keys = array('7' => array('011111011000111100011110001111000111100011110001111000110111110' => 0, '000110001111000001100000110000011000001100000110000011000111111' => 1, '011111011000111100011000001100001100001100001100001100001111111' => 2, '011111011000111100011000001100011100000011110001111000110111110' => 3, '000011000011100010110010011010001101111111000011000001100000110' => 4, '011111101100000110000011111000000110000011110001111000110111110' => 5, '001111001100001100000111111011000111100011110001111000110111110' => 6, '111111100000110000011000011000001100001100000110000110000011000' => 7, '011111011000111100011110001101111101100011110001111000110111110' => 8, '011111011000111100011110001111000110111111000001100001100111100' => 9), '9' => array('001111100011000110110000011110000011110000011110000011110000011110000011110000011011000110001111100' => 0, '000011000001111000000011000000011000000011000000011000000011000000011000000011000000011000001111110' => 1, '011111100110000110110000011000000011000000110000001100000011000000110000001100000011000000111111111' => 2, '011111100110000110110000011000000011000000110000111100000000110000000011110000011110000110011111100' => 3, '000000110000001110000010110000100110001000110010000110100000110111111111000000110000000110000000110' => 4, '011111111011000000011000000011000000011111100000000110000000011000000011110000011110000110011111100' => 5, '000111110001100000011000000110000000110111100111000110110000011110000011110000011011000110001111100' => 6, '111111111000000011000000110000000110000001100000001100000011000000011000000110000000110000001100000' => 7, '001111100011000110110000011110000011011000110001111100011000110110000011110000011011000110001111100' => 8, '001111100011000110110000011110000011110000011011000111001111011000000011000000110000001100011111000' => 9));
     $configs = array('1' => array('word_width' => 9, 'offset_l' => 20, 'offset_t' => 4, 'word_spacing' => 2, 'd_width' => 5), '2' => array('word_width' => 7, 'offset_l' => 18, 'offset_t' => 4, 'word_spacing' => 2, 'd_width' => 5), '3' => array('word_width' => 7, 'offset_l' => 17, 'offset_t' => 3, 'word_spacing' => 2, 'd_width' => 4));
     $res = imagecreatefrompng($file_path);
     $size = getimagesize($file_path);
     $data = array();
     $offset_r = 0;
     for ($j = $size[0] - 1; $j >= 0; $j--) {
         $rgb = imagecolorat($res, $j, 6);
         $rgbarray = imagecolorsforindex($res, $rgb);
         if ($rgbarray['red'] < 125 || $rgbarray['green'] < 125 || $rgbarray['blue'] < 125) {
             break;
         } else {
             $offset_r++;
         }
     }
     $offset_b = 0;
     for ($i = $size[1] - 1; $i >= 0; $i--) {
         $rgb = imagecolorat($res, 9, $i);
         $rgbarray = imagecolorsforindex($res, $rgb);
         if ($rgbarray['red'] < 125 || $rgbarray['green'] < 125 || $rgbarray['blue'] < 125) {
             break;
         } else {
             $offset_b++;
         }
     }
     $img_width = $size[0];
     if ($offset_b == 9) {
         $config = $configs[2];
     } elseif ($offset_b == 10) {
         $config = $configs[3];
     } else {
         $config = $configs[1];
         $offset_b++;
     }
     $word_width = $config['word_width'];
     $key = $keys[$word_width];
     $offset_l = $config['offset_l'];
     $offset_t = $config['offset_t'];
     $word_spacing = $config['word_spacing'];
     $d_width = $config['d_width'];
     $no_l = $size[0] - ($xs_count * ($word_width + $word_spacing) + $d_width + $offset_r);
     $no_r = $no_l + $d_width;
     for ($i = $offset_t; $i < $size[1] - $offset_b; $i++) {
         $w = 0;
         for ($j = $offset_l; $j < $size[0] - $offset_r; $j++) {
             if ($j >= $no_l && $j < $no_r) {
                 continue;
             }
             $rgb = imagecolorat($res, $j, $i);
             $rgbarray = imagecolorsforindex($res, $rgb);
             if ($rgbarray['red'] < 125 || $rgbarray['green'] < 125 || $rgbarray['blue'] < 125) {
                 $data[$i - $offset_t][$w] = 1;
             } else {
                 $data[$i - $offset_t][$w] = 0;
             }
             $w++;
         }
     }
     $prices = array();
     $length = count($data[0]);
     $height = count($data);
     $count = ($length + $word_spacing) / ($word_width + $word_spacing);
     for ($i = 0; $i < $count; $i++) {
         $x = $i * ($word_width + $word_spacing);
         for ($h = 0; $h < $height; $h++) {
             $temp = '';
             for ($w = $x; $w < $x + $word_width; $w++) {
                 $prices[$i] .= $data[$h][$w];
             }
         }
     }
     $number = '';
     foreach ($prices as $price) {
         $number .= $key[$price];
     }
     @unlink($file_path);
     return (double) $number / 100;
 }
コード例 #30
0
/**
 * Returns the Javascript code and creates the key for hardened trackbacks.
 */
function getTracbackKeyJS($uri, $date)
{
    global $PIVOTX;
    // Abort immediately if hardened trackbacks isn't enabled.
    if ($PIVOTX['config']->get('hardened_trackback') != 1) {
        exit;
    }
    // Get the entry from the DB..
    $entry = $PIVOTX['db']->read_entry($uri, $date);
    // Exit if non-existing ID supplied
    if (empty($entry['code'])) {
        debug('Entry not found');
    } else {
        $id = intval($entry['code']);
    }
    $keydir = $PIVOTX['paths']["db_path"] . "tbkeys/";
    $tburl = $PIVOTX['paths']['host'] . makeFileLink($entry['code'], '', '');
    $trackback = getDefault($PIVOTX['config']->get('localised_trackback_name'), "trackback");
    if ($PIVOTX['config']->get('mod_rewrite') == 0) {
        $tburl .= "&amp;{$trackback}&amp;key=";
    } else {
        $tburl .= "/{$trackback}/?key=";
    }
    if (!strstr($_SERVER["HTTP_REFERER"], $_SERVER["SERVER_NAME"])) {
        // Creating a bogus key
        $tbkey = md5(microtime());
        debug("hardened trackbacks: illegal request - creating bogus key");
    } else {
        makeDir($keydir);
        $tbkey = md5($PIVOTX['config']->get('server_spam_key') . $_SERVER["REMOTE_ADDR"] . $id . time());
        if (!touch($keydir . $tbkey)) {
            debug("hardened trackbacks: directory {$keydir} isn't writable - can't create key");
        } else {
            chmodFile($keydir . $tbkey);
        }
    }
    // Getting the time offset between the web and file server (if there is any)
    $offset = timeDiffWebFile($tbkey_debug);
    // delete keys older than 15 minutes
    $nNow = time();
    $handle = opendir($keydir);
    while (false !== ($file = readdir($handle))) {
        $filepath = $keydir . $file;
        if (!is_dir($filepath) && $file != "index.html") {
            $Diff = $nNow - filectime($filepath);
            if ($Diff > 60 * 15 + $offset) {
                unlink($filepath);
            }
        }
    }
    closedir($handle);
    header('Content-Type: text/javascript');
    echo <<<EOM

function showTBURL_{$entry['code']}(element_id)  {
    var element = document.getElementById(element_id);
    element.innerHTML = '<br />{$tburl}' + '{$tbkey}';
}

function showTBURLgen_{$entry['code']}(element_id, tburl_gen)  {
    var element = document.getElementById(element_id);
    element.innerHTML = tburl_gen;
}

EOM;
    exit;
}