<commit_before><?php

/**
 * Copyright (c) 2009, <NAME>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms,
 * with or without modification, are permitted provided
 * that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 *       copyright notice, this list of conditions and the following
 *       disclaimer in the documentation and/or other materials provided
 *       with the distribution.
 *     * Neither the name of the Mujserver.net nor the names of its
 *       contributors may be used to endorse or promote products derived
 *       from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * @author     <NAME>
 * @copyright  Copyright (c) 2009 <NAME> (http://mujserver.net)
 * @license    New BSD License
 * @link       http://nettephp.com/cs/extras/multiplefileupload
 */

class MultipleFileUpload extends FileUpload {

    // TODO: dodělat JavaScriptovou validaci - hidden field kde se budou cpát hodnoty pro Nettí validátor
    // TODO: Thread-safe cache pro seznamy souborů ve frontě. Tip: http://forum.nettephp.com/cs/viewtopic.php?pid=16547#p16547
    //  Už to mám! :) Vytvořit další soubor v cache s funkcí lock-unlock.
    // TODO: Vytvořit nějaký obecný Storage na data, který je thread-safe a bude nahrozovat časté nesprávné použití cache.
    // TODO: Nejdříve vygenerovat nějaký jednorázový token, kterým se uživatel následně ověří, že je to opravdu on.

    static function register(){
        $application = Environment::getApplication();
        $application->onStartup[]  = "MultipleFileUpload::handleUploads";
        $application->onShutdown[] = "MultipleFileUpload::cleanCache";
    }

    /* ##########  HANDLING UPLOADS  ########### */


    /**
     * Directory for temporary uploads
     * @var string
     */
    public static $uploadFileDirectory = "%tempDir%/MultipleFileUpload-uploads";

    /**
     * Cache object
     * @var Cache
     */
    private static $cache;

    /**
     * Is files proccessed?
     * @var bool
     */
    private static $filesProccessed = false;

    /**
     * Check if handleUploads was called
     * @var bool
     */
    public static $handleUploadsCheck = false;

    /**
     * Lifetime of files in queue
     * When clean up is running, it is watching if there is any added file in their lifetime.
     *
     * @var int Time in seconds
     */
    public static $lifeTime = 3600; // 1 hour

    /**
     * Cleaning up interval
     * @var int In seconds
     */
    public static $cleanInterval = 18000; // 5 hours

    /**
     * Handles uploading files
     */
    static function handleUploads() {

        // Checks
        self::$handleUploadsCheck = true;
        if(self::$filesProccessed === true) return;

        $req = Environment::getHttpRequest();
        if(!$req->getMethod() === "POST" OR !stristr($req->getHeader("Content-type"),"multipart/form-data"))
            return;

        // V PHP 5.3 zhodí Apache!
        if(self::isRequestFromFlash())
            Debug::enable(Debug::PRODUCTION);

        $dir = Environment::expand(self::$uploadFileDirectory);

        // Vytvoříme složku a ověříme jestli je zapisovatelná
        if(!file_exists($dir))
            mkdir($dir,777);
        if(!is_writable($dir))
            throw new InvalidStateException($dir." is not writable!");

        // Zpracuj soubory
        if(self::isRequestFromFlash()){
            // Uploadify
            /*
             * Dostaneme soubor Filedata
             */
            if(!isSet($_POST["token"])) return;
            $token = $_POST["token"];
            $store = self::getData($token);
            foreach(Environment::getHttpRequest()->getFiles() AS $file){
                self::processSingleFile($token, $file, $store);
            }
            self::saveData($token, $store);

        }else{
            // Standardní HTTP požadavek
            /*
             * Dojde něco ve stylu:
             *   Array
             *   (
             *       [testUpload] => Array
             *           (
             *               [files] => Array
             *                   (
             *                       [0] => HttpUploadedFile Object
             *                           (
             *                               [name:private] => anchor.png
             *                               [type:private] =>
             *                               [size:private] => 523
             *                               [tmpName:private] => C:\Program Files\xampp\tmp\phpBBF2.tmp
             *                               [error:private] => 0
             *                           )
             *
             *                       [1] => HttpUploadedFile Object
             *                           (
             *                               [name:private] => application_edit.png
             *                               [type:private] =>
             *                               [size:private] => 703
             *                               [tmpName:private] => C:\Program Files\xampp\tmp\phpBC03.tmp
             *                               [error:private] => 0
             *                           )
             *                   )
             *
             *           )
             *
             *   )
             */
            foreach(Environment::getHttpRequest()->getFiles() AS $name => $controlValue){
                if(is_array($controlValue) and isSet($controlValue["files"]) and isSet($_POST[$name]["token"])){
                    $token = $_POST[$name]["token"];
                    $store = self::getData($token);
                    foreach($controlValue["files"] AS $file){
                        self::processSingleFile($token,$file, $store);
                    }
                    self::saveData($token,$store);
                }//else zpracuje si to už formulář sám (nejspíš tam bude už HTTPUploadedFile, ale odeslán z klasického FileUpload políčka)
            }
        }

        // Pokud všechno proběhlo ok a soubor byl odeslán z flashe
        if(self::isRequestFromFlash()) {
            echo "1";
            throw new AbortException();
        }

        self::$filesProccessed = true;
    }

    /**
     * Cleans cache
     * @return bool
     */
    static function cleanCache(){
        $cache  = self::getCache();

        if(isSet($cache["lastCleanup"]) and $cache["lastCleanup"] > (time()-self::$cleanInterval))
            return;
            
        if(isSet($cache["cleaning"])) return;
        $cache["cleaning"]=true;

<commit_msg>Bug fix - Abort Exception outside the Application -> now die() is called<commit_after><?php

/**
 * Copyright (c) 2009, <NAME>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms,
 * with or without modification, are permitted provided
 * that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 *       copyright notice, this list of conditions and the following
 *       disclaimer in the documentation and/or other materials provided
 *       with the distribution.
 *     * Neither the name of the Mujserver.net nor the names of its
 *       contributors may be used to endorse or promote products derived
 *       from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * @author     <NAME>
 * @copyright  Copyright (c) 2009 <NAME> (http://mujserver.net)
 * @license    New BSD License
 * @link       http://nettephp.com/cs/extras/multiplefileupload
 */

class MultipleFileUpload extends FileUpload {

    // TODO: dodělat JavaScriptovou validaci - hidden field kde se budou cpát hodnoty pro Nettí validátor
    // TODO: Thread-safe cache pro seznamy souborů ve frontě. Tip: http://forum.nettephp.com/cs/viewtopic.php?pid=16547#p16547
    //  Už to mám! :) Vytvořit další soubor v cache s funkcí lock-unlock.
    // TODO: Vytvořit nějaký obecný Storage na data, který je thread-safe a bude nahrozovat časté nesprávné použití cache.
    // TODO: Nejdříve vygenerovat nějaký jednorázový token, kterým se uživatel následně ověří, že je to opravdu on.

    static function register(){
        $application = Environment::getApplication();
        $application->onStartup[]  = "MultipleFileUpload::handleUploads";
        $application->onShutdown[] = "MultipleFileUpload::cleanCache";
    }

    /* ##########  HANDLING UPLOADS  ########### */


    /**
     * Directory for temporary uploads
     * @var string
     */
    public static $uploadFileDirectory = "%tempDir%/MultipleFileUpload-uploads";

    /**
     * Cache object
     * @var Cache
     */
    private static $cache;

    /**
     * Is files proccessed?
     * @var bool
     */
    private static $filesProccessed = false;

    /**
     * Check if handleUploads was called
     * @var bool
     */
    public static $handleUploadsCheck = false;

    /**
     * Lifetime of files in queue
     * When clean up is running, it is watching if there is any added file in their lifetime.
     *
     * @var int Time in seconds
     */
    public static $lifeTime = 3600; // 1 hour

    /**
     * Cleaning up interval
     * @var int In seconds
     */
    public static $cleanInterval = 18000; // 5 hours

    /**
     * Handles uploading files
     */
    static function handleUploads() {

        // Checks
        self::$handleUploadsCheck = true;
        if(self::$filesProccessed === true) return;

        $req = Environment::getHttpRequest();
        if(!$req->getMethod() === "POST" OR !stristr($req->getHeader("Content-type"),"multipart/form-data"))
            return;

        // V PHP 5.3 zhodí Apache!
        if(self::isRequestFromFlash())
            Debug::enable(Debug::PRODUCTION);

        $dir = Environment::expand(self::$uploadFileDirectory);

        // Vytvoříme složku a ověříme jestli je zapisovatelná
        if(!file_exists($dir))
            mkdir($dir,777);
        if(!is_writable($dir))
            throw new InvalidStateException($dir." is not writable!");

        // Zpracuj soubory
        if(self::isRequestFromFlash()){
            // Uploadify
            /*
             * Dostaneme soubor Filedata
             */
            if(!isSet($_POST["token"])) return;
            $token = $_POST["token"];
            $store = self::getData($token);
            foreach(Environment::getHttpRequest()->getFiles() AS $file){
                self::processSingleFile($token, $file, $store);
            }
            self::saveData($token, $store);

        }else{
            // Standardní HTTP požadavek
            /*
             * Dojde něco ve stylu:
             *   Array
             *   (
             *       [testUpload] => Array
             *           (
             *               [files] => Array
             *                   (
             *                       [0] => HttpUploadedFile Object
             *                           (
             *                               [name:private] => anchor.png
             *                               [type:private] =>
             *                               [size:private] => 523
             *                               [tmpName:private] => C:\Program Files\xampp\tmp\phpBBF2.tmp
             *                               [error:private] => 0
             *                           )
             *
             *                       [1] => HttpUploadedFile Object
             *                           (
             *                               [name:private] => application_edit.png
             *                               [type:private] =>
             *                               [size:private] => 703
             *                               [tmpName:private] => C:\Program Files\xampp\tmp\phpBC03.tmp
             *                               [error:private] => 0
             *                           )
             *                   )
             *
             *           )
             *
             *   )
             */
            foreach(Environment::getHttpRequest()->getFiles() AS $name => $controlValue){
                if(is_array($controlValue) and isSet($controlValue["files"]) and isSet($_POST[$name]["token"])){
                    $token = $_POST[$name]["token"];
                    $store = self::getData($token);
                    foreach($controlValue["files"] AS $file){
                        self::processSingleFile($token,$file, $store);
                    }
                    self::saveData($token,$store);
                }//else zpracuje si to už formulář sám (nejspíš tam bude už HTTPUploadedFile, ale odeslán z klasického FileUpload políčka)
            }
        }

        // Pokud všechno proběhlo ok a soubor byl odeslán z flashe
        if(self::isRequestFromFlash()) {
            echo "1";
            
            // Voláno ještě před spustěním $application-run() -> abort exception by způsobilo akorát nezachycenou výjimku
            die();
        }

        self::$filesProccessed = true;
    }

    /**
     * Cleans cache
     * @return bool
     */
    static function cleanCache(){
        $cache  = self::getCache();

        if(isSet($cache["lastCleanup"]) and $cache["lastCleanup"] > (time()-self::$cleanInterval))
            return;
            
        if(isSet($cache["cleaning"])) return;
        $cache["cleaning"]=true;


{'fraction_non_alphanumeric': 0.10307863259036538, 'fraction_numerical': 0.0062749199294071505, 'mean_word_length': 1.7175843694493784, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 55, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 56, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2137648', 'n_tokens_mistral': 4211, 'n_tokens_neox': 4001, 'n_words': 1172}