Ejemplo n.º 1
0
function checkDirectory(&$dir)
{
    if (substr($dir, -1) !== '/') {
        //append slash
        $dir .= '/';
    }
    $dirHandle = opendir($dir);
    if ($dirHandle !== false) {
        while (($file = readdir($dirHandle)) !== false) {
            if ($file !== '..' && $file !== '.') {
                $fullfilename = $dir . $file;
                if (is_dir($fullfilename) === false) {
                    //check file for BOM
                    echo $fullfilename;
                    if (isUTF8BOM($fullfilename) !== false) {
                        echo ' contains BOM';
                    } else {
                        echo ' does not contain BOM';
                    }
                    echo PHP_EOL;
                } else {
                    //check next directory
                    checkDirectory($fullfilename);
                }
            }
        }
        closedir($dirHandle);
    }
}
Ejemplo n.º 2
0
/**
 * Checks for the location of the incoming directory
 * If it does not exist, then it creates it.
 */
function checkIncomingPath()
{
    global $cfg;
    switch ($cfg["enable_home_dirs"]) {
        case 1:
        default:
            // is there a user dir?
            checkDirectory($cfg["path"] . $cfg["user"], 0777);
            break;
        case 0:
            // is there a incoming dir?
            checkDirectory($cfg["path"] . $cfg["path_incoming"], 0777);
            break;
    }
}
/**
 * backup of flux-installation
 *
 * @param $talk: boolean if function should talk
 * @param $compression: 0 = none | 1 = gzip | 2 = bzip2
 * @return string with name of backup-archive, string with "" in error-case.
 */
function backupCreate($talk = false, $compression = 0)
{
    global $cfg, $error;
    // backup-dir
    $dirBackup = $cfg["path"] . _DIR_BACKUP;
    if (!checkDirectory($dirBackup)) {
        $error = "Errors when checking/creating backup-dir: " . tfb_htmlencodekeepspaces($dirBackup);
        return "";
    }
    // files and more strings
    $backupName = "backup_" . _VERSION . "_" . date("YmdHis");
    $fileArchiveName = $backupName . ".tar";
    $tarSwitch = "-cf";
    switch ($compression) {
        case 1:
            $fileArchiveName .= ".gz";
            $tarSwitch = "-zcf";
            break;
        case 2:
            $fileArchiveName .= ".bz2";
            $tarSwitch = "-jcf";
            break;
    }
    // files
    $files = array();
    $files['archive'] = $dirBackup . '/' . $fileArchiveName;
    $files['db'] = $dirBackup . '/database.sql';
    $files['docroot'] = $dirBackup . '/docroot.tar';
    $files['transfers'] = $dirBackup . '/transfers.tar';
    $files['fluxd'] = $dirBackup . '/fluxd.tar';
    $files['mrtg'] = $dirBackup . '/mrtg.tar';
    // exec
    $exec = array();
    $exec['transfers'] = @is_dir($cfg["transfer_file_path"]) === true;
    $exec['fluxd'] = @is_dir($cfg["path"] . '.fluxd') === true;
    $exec['mrtg'] = @is_dir($cfg["path"] . '.mrtg') === true;
    // commands
    $commands = array();
    $commands['archive'] = "cd " . tfb_shellencode($dirBackup) . "; tar " . $tarSwitch . " " . $fileArchiveName . " ";
    $commands['db'] = "";
    switch ($cfg["db_type"]) {
        case "mysql":
            $commands['db'] = "mysqldump -h " . tfb_shellencode($cfg["db_host"]) . " -u " . tfb_shellencode($cfg["db_user"]) . " --password="******"db_pass"]) . " --all -f " . tfb_shellencode($cfg["db_name"]) . " > " . tfb_shellencode($files['db']);
            $commands['archive'] .= 'database.sql ';
            break;
        case "sqlite":
            $commands['db'] = "sqlite " . tfb_shellencode($cfg["db_host"]) . " .dump > " . tfb_shellencode($files['db']);
            $commands['archive'] .= 'database.sql ';
            break;
        case "postgres":
            $commands['db'] = "pg_dump -h " . tfb_shellencode($cfg["db_host"]) . " -D " . tfb_shellencode($cfg["db_name"]) . " -U " . tfb_shellencode($cfg["db_user"]) . " -f " . tfb_shellencode($files['db']);
            $commands['archive'] .= 'database.sql ';
            break;
    }
    $commands['archive'] .= 'docroot.tar';
    if ($exec['transfers'] === true) {
        $commands['archive'] .= ' transfers.tar';
    }
    if ($exec['fluxd'] === true) {
        $commands['archive'] .= ' fluxd.tar';
    }
    if ($exec['mrtg'] === true) {
        $commands['archive'] .= ' mrtg.tar';
    }
    //$commands['docroot'] = "cd ".tfb_shellencode($dirBackup)."; tar -cf docroot.tar ".tfb_shellencode($cfg["docroot"]); // with path of docroot
    $commands['docroot'] = "cd " . tfb_shellencode($cfg["docroot"]) . "; tar -cf " . tfb_shellencode($files['docroot']) . " .";
    // only content of docroot
    $commands['transfers'] = "cd " . tfb_shellencode($cfg["transfer_file_path"]) . "; tar -cf " . tfb_shellencode($files['transfers']) . " .";
    $commands['fluxd'] = "cd " . tfb_shellencode($cfg["path"] . '.fluxd') . "; tar -cf " . tfb_shellencode($files['fluxd']) . " .";
    $commands['mrtg'] = "cd " . tfb_shellencode($cfg["path"] . '.mrtg') . "; tar -cf " . tfb_shellencode($files['mrtg']) . " .";
    // action
    if ($talk) {
        sendLine('<br>');
    }
    // database-command
    if ($commands['db'] != "") {
        if ($talk) {
            sendLine('Backup of Database <em>' . tfb_htmlencodekeepspaces($cfg["db_name"]) . '</em> ...');
        }
        shell_exec($commands['db']);
    }
    if ($talk) {
        sendLine(' <font color="green">Ok</font><br>');
    }
    // docroot-command
    if ($talk) {
        sendLine('Backup of Docroot <em>' . tfb_htmlencodekeepspaces($cfg["docroot"]) . '</em> ...');
    }
    shell_exec($commands['docroot']);
    if ($talk) {
        sendLine(' <font color="green">Ok</font><br>');
    }
    // transfers-command
    if ($exec['transfers'] === true) {
        if ($talk) {
            sendLine('Backup of transfers <em>' . tfb_htmlencodekeepspaces($cfg["transfer_file_path"]) . '</em> ...');
        }
        shell_exec($commands['transfers']);
        if ($talk) {
            sendLine(' <font color="green">Ok</font><br>');
        }
    }
    // fluxd-command
    if ($exec['fluxd'] === true) {
        if ($talk) {
            sendLine('Backup of fluxd <em>' . tfb_htmlencodekeepspaces($cfg["path"] . '.fluxd') . '</em> ...');
        }
        shell_exec($commands['fluxd']);
        if ($talk) {
            sendLine(' <font color="green">Ok</font><br>');
        }
    }
    // mrtg-command
    if ($exec['mrtg'] === true) {
        if ($talk) {
            sendLine('Backup of mrtg <em>' . tfb_htmlencodekeepspaces($cfg["path"] . '.mrtg') . '</em> ...');
        }
        shell_exec($commands['mrtg']);
        if ($talk) {
            sendLine(' <font color="green">Ok</font><br>');
        }
    }
    // create the archive
    if ($talk) {
        sendLine('Creating Archive <em>' . $fileArchiveName . '</em> ...');
    }
    shell_exec($commands['archive']);
    if ($talk) {
        sendLine(' <font color="green">Ok</font><br>');
    }
    // delete temp-file(s)
    if ($talk) {
        sendLine('Deleting temp-files ...');
    }
    if ($commands['db'] != "") {
        @unlink($files['db']);
    }
    @unlink($files['docroot']);
    @unlink($files['transfers']);
    @unlink($files['fluxd']);
    @unlink($files['mrtg']);
    if ($talk) {
        sendLine(' <font color="green">Ok</font><br>');
    }
    // log
    if ($talk) {
        sendLine('<font color="green">Backup Complete.</font><br>');
    }
    AuditAction($cfg["constants"]["admin"], "Backup Created: " . $fileArchiveName);
    return $fileArchiveName;
}
Ejemplo n.º 4
0
/**
 * backup of flux-installation
 *
 * @param $talk : boolean if function should talk
 * @param $compression : 0 = none | 1 = gzip | 2 = bzip2
 * @return string with name of backup-archive, string with "" in error-case.
 */
function backupCreate($talk = false, $compression = 0)
{
    global $cfg, $error;
    // backup-dir
    $dirBackup = $cfg["path"] . _DIR_BACKUP;
    if (!checkDirectory($dirBackup)) {
        $error = "Errors when checking/creating backup-dir : " . $dirBackup;
        return "";
    }
    // files and more strings
    $backupName = "backup_" . _VERSION_THIS . "_" . date("YmdHis");
    $fileArchiveName = $backupName . ".tar";
    $tarSwitch = "-cf";
    switch ($compression) {
        case 1:
            $fileArchiveName .= ".gz";
            $tarSwitch = "-zcf";
            break;
        case 2:
            $fileArchiveName .= ".bz2";
            $tarSwitch = "-jcf";
            break;
    }
    $fileArchive = $dirBackup . '/' . $fileArchiveName;
    $fileDatabase = $dirBackup . '/database.sql';
    $fileDocroot = $dirBackup . '/docroot.tar';
    // command-strings
    $commandArchive = "cd " . $dirBackup . "; tar " . $tarSwitch . " " . $fileArchiveName . " ";
    $commandDatabase = "";
    switch ($cfg["db_type"]) {
        case "mysql":
            $commandDatabase = "mysqldump -h " . $cfg["db_host"] . " -u " . $cfg["db_user"] . " --password="******"db_pass"] . " --all -f " . $cfg["db_name"] . " > " . $fileDatabase;
            $commandArchive .= 'database.sql ';
            break;
        case "sqlite":
            $commandDatabase = "sqlite " . $cfg["db_host"] . " .dump > " . $fileDatabase;
            $commandArchive .= 'database.sql ';
            break;
        case "postgres":
            $commandDatabase = "pg_dump -h " . $cfg["db_host"] . " -D " . $cfg["db_name"] . " -U " . $cfg["db_user"] . " -f " . $fileDatabase;
            $commandArchive .= 'database.sql ';
            break;
    }
    $commandArchive .= 'docroot.tar';
    $docroot = dirname(__FILE__);
    //$commandDocroot = "cd ".$dirBackup."; tar -cf docroot.tar ".$docroot; // with path of docroot
    $commandDocroot = "cd " . escapeshellarg($docroot) . "; tar -cf " . $fileDocroot . " .";
    // only content of docroot
    // database-command
    if ($commandDatabase != "") {
        if ($talk) {
            sendLine('Backup of Database <em>' . $cfg["db_name"] . '</em> ...');
        }
        shell_exec($commandDatabase);
    }
    if ($talk) {
        sendLine(' <font color="green">Ok</font><br>');
    }
    // docroot-command
    if ($talk) {
        sendLine('Backup of Docroot <em>' . $docroot . '</em> ...');
    }
    shell_exec($commandDocroot);
    if ($talk) {
        sendLine(' <font color="green">Ok</font><br>');
    }
    // create the archive
    if ($talk) {
        sendLine('Creating Archive <em>' . $fileArchiveName . '</em> ...');
    }
    shell_exec($commandArchive);
    if ($talk) {
        sendLine(' <font color="green">Ok</font><br>');
    }
    // delete temp-file(s)
    if ($talk) {
        sendLine('Deleting temp-files ...');
    }
    if ($commandDatabase != "") {
        @unlink($fileDatabase);
    }
    @unlink($fileDocroot);
    if ($talk) {
        sendLine(' <font color="green">Ok</font><br>');
    }
    // log
    if ($talk) {
        sendLine('<font color="green">Backup Complete.</font><br>');
    }
    AuditAction($cfg["constants"]["admin"], "FluxBackup Created : " . $fileArchiveName);
    return $fileArchiveName;
}
Ejemplo n.º 5
0
 /**
  * process a feed
  *
  * @param $sdir
  * @param $filter
  * @param $hist
  * @param $url
  * @return boolean
  */
 function instance_processFeed($sdir, $filter, $hist, $url)
 {
     // (re)set state
     $this->state = RSSD_STATE_NULL;
     // validate
     if (!checkDirectory($sdir, 0777)) {
         $this->state = RSSD_STATE_ERROR;
         $msg = "Save-Dir " . $sdir . " not valid.";
         array_push($this->messages, $msg);
         $this->_outputError($msg . "\n");
         return false;
     }
     if (!is_file($filter)) {
         $this->state = RSSD_STATE_ERROR;
         $msg = "Filter-File " . $filter . " not valid.";
         array_push($this->messages, $msg);
         $this->_outputError($msg . "\n");
         return false;
     }
     // output
     $this->_outputMessage("Processing feed " . $url . " ...\n");
     // set vars
     $this->_dirSave = checkDirPathString($sdir);
     $this->_fileFilters = $filter;
     $this->_fileHistory = $hist;
     $this->_urlRSS = $url;
     $this->_filters = array();
     $this->_history = array();
     $this->_historyNew = array();
     $this->_data = array();
     $this->_filesSaved = array();
     // load _filters
     if (!$this->_loadFilters()) {
         return false;
     }
     // load history
     if (!$this->_loadHistory()) {
         return false;
     }
     // load data
     if (!$this->_loadData()) {
         return false;
     }
     // something to do ?
     if ($this->_data['items_count'] <= 0) {
         // no
         // state
         $this->state = RSSD_STATE_OK;
         return true;
     }
     // process data
     if (!$this->_processData()) {
         return false;
     }
     // update history
     if (!$this->_updateHistory()) {
         return false;
     }
     // state
     $this->state = RSSD_STATE_OK;
     // output
     $this->_outputMessage("feed processed. downloaded and saved " . count($this->_filesSaved) . " torrents.\n");
     // return
     return true;
 }
Ejemplo n.º 6
0
 /**
  * prepares start of a bittorrent-client.
  * prepares vars and other generic stuff
  * @param $torrent name of the torrent
  * @param $interactive (1|0) : is this a interactive startup with dialog ?
  */
 function prepareStartTorrentClient($torrent, $interactive)
 {
     if ($this->state < 1) {
         $this->state = -1;
         $this->messages .= "Error. ClientHandler in wrong state on prepare-request.";
         return;
     }
     $this->skip_hash_check = "";
     if ($interactive == 1) {
         // interactive, get vars from request vars
         $this->rate = getRequestVar('rate');
         if (empty($this->rate)) {
             if ($this->rate != "0") {
                 $this->rate = $this->cfg["max_upload_rate"];
             }
         }
         $this->drate = getRequestVar('drate');
         if (empty($this->drate)) {
             if ($this->drate != "0") {
                 $this->drate = $this->cfg["max_download_rate"];
             }
         }
         $this->superseeder = getRequestVar('superseeder');
         if (empty($this->superseeder)) {
             $this->superseeder = "0";
         }
         // should be 0 in most cases
         $this->runtime = getRequestVar('runtime');
         if (empty($this->runtime)) {
             $this->runtime = $this->cfg["torrent_dies_when_done"];
         }
         $this->maxuploads = getRequestVar('maxuploads');
         if (empty($this->maxuploads)) {
             if ($this->maxuploads != "0") {
                 $this->maxuploads = $this->cfg["max_uploads"];
             }
         }
         $this->minport = getRequestVar('minport');
         if (empty($this->minport)) {
             $this->minport = $this->cfg["minport"];
         }
         $this->maxport = getRequestVar('maxport');
         if (empty($this->maxport)) {
             $this->maxport = $this->cfg["maxport"];
         }
         $this->maxcons = getRequestVar('maxcons');
         if (empty($this->maxcons)) {
             $this->maxcons = $this->cfg["maxcons"];
         }
         $this->rerequest = getRequestVar("rerequest");
         if (empty($this->rerequest)) {
             $this->rerequest = $this->cfg["rerequest_interval"];
         }
         $this->sharekill = getRequestVar('sharekill');
         if ($this->runtime == "True") {
             $this->sharekill = "-1";
         }
         if (empty($this->sharekill)) {
             if ($this->sharekill != "0") {
                 $this->sharekill = $this->cfg["sharekill"];
             }
         }
         $this->savepath = getRequestVar('savepath');
         $this->skip_hash_check = getRequestVar('skiphashcheck');
     } else {
         // non-interactive, load settings from db and set vars
         $this->rerequest = $this->cfg["rerequest_interval"];
         $this->skip_hash_check = $this->cfg["skiphashcheck"];
         $this->superseeder = 0;
         // load settings
         $settingsAry = loadTorrentSettings(urldecode($torrent));
         $this->rate = $settingsAry["max_upload_rate"];
         $this->drate = $settingsAry["max_download_rate"];
         $this->runtime = $settingsAry["torrent_dies_when_done"];
         $this->maxuploads = $settingsAry["max_uploads"];
         $this->minport = $settingsAry["minport"];
         $this->maxport = $settingsAry["maxport"];
         $this->maxcons = $settingsAry["maxcons"];
         $this->sharekill = $settingsAry["sharekill"];
         $this->savepath = $settingsAry["savepath"];
         // fallback-values if fresh-torrent is started non-interactive or
         // something else strange happened
         if ($this->rate == '') {
             $this->rate = $this->cfg["max_upload_rate"];
         }
         if ($this->drate == '') {
             $this->drate = $this->cfg["max_download_rate"];
         }
         if ($this->runtime == '') {
             $this->runtime = $this->cfg["torrent_dies_when_done"];
         }
         if ($this->maxuploads == '') {
             $this->maxuploads = $this->cfg["max_uploads"];
         }
         if ($this->minport == '') {
             $this->minport = $this->cfg["minport"];
         }
         if ($this->maxport == '') {
             $this->maxport = $this->cfg["maxport"];
         }
         if ($this->maxcons == '') {
             $this->maxcons = $this->cfg["maxcons"];
         }
         if ($this->sharekill == '') {
             $this->sharekill = $this->cfg["sharekill"];
         }
     }
     // queue
     if ($this->cfg["AllowQueing"]) {
         if (IsAdmin()) {
             $this->queue = getRequestVar('queue');
             if ($this->queue == 'on') {
                 $this->queue = "1";
             } else {
                 $this->queue = "0";
             }
         } else {
             $this->queue = "1";
         }
     } else {
         $this->queue = "0";
     }
     //
     $this->torrent = urldecode($torrent);
     $this->alias = getAliasName($this->torrent);
     $this->owner = getOwner($this->torrent);
     if (empty($this->savepath)) {
         $this->savepath = $this->cfg['path'] . $this->owner . "/";
     }
     // ensure path has trailing slash
     $this->savepath = checkDirPathString($this->savepath);
     // check target-directory, create if not present
     if (!checkDirectory($this->savepath, 0777)) {
         AuditAction($this->cfg["constants"]["error"], "Error checking " . $this->savepath . ".");
         $this->state = -1;
         $this->messages .= "Error. TorrentFlux settings are not correct (path-setting).";
         global $argv;
         if (isset($argv)) {
             die($this->messages);
         } else {
             if (IsAdmin()) {
                 @header("location: admin.php?op=configSettings");
                 exit;
             } else {
                 $this->messages .= " please contact an admin.";
                 showErrorPage($this->messages);
             }
         }
     }
     // create AliasFile object and write out the stat file
     include_once "AliasFile.php";
     $this->af = AliasFile::getAliasFileInstance($this->cfg["torrent_file_path"] . $this->alias . ".stat", $this->owner, $this->cfg, $this->handlerName);
     // set param for sharekill
     $this->sharekill = intval($this->sharekill);
     if ($this->sharekill == 0) {
         // nice, we seed forever
         $this->sharekill_param = 0;
     } elseif ($this->sharekill > 0) {
         // recalc sharekill
         // sanity-check. catch "data-size = 0".
         $transferSize = intval($this->af->size);
         if ($transferSize > 0) {
             $totalAry = getTorrentTotals($this->torrent);
             $upTotal = $totalAry["uptotal"] + 0;
             $downTotal = $totalAry["downtotal"] + 0;
             $upWanted = $this->sharekill / 100 * $transferSize;
             $sharePercentage = $upTotal / $transferSize * 100;
             if ($upTotal >= $upWanted && $downTotal >= $transferSize) {
                 // we already have seeded at least wanted percentage.
                 // skip start of client
                 // set state
                 $this->state = 1;
                 // message
                 $this->messages = "skipping start of transfer " . $this->torrent . " due to share-ratio (has: " . @number_format($sharePercentage, 2) . " ; set:" . $this->sharekill . ")";
                 // DEBUG : log the messages
                 AuditAction($this->cfg["constants"]["debug"], $this->messages);
                 // return
                 return;
             } else {
                 // not done seeding wanted percentage
                 $this->sharekill_param = intval(ceil($this->sharekill - $sharePercentage));
                 // sanity-check.
                 if ($this->sharekill_param < 1) {
                     $this->sharekill_param = 1;
                 }
             }
         } else {
             $this->messages = "data-size is 0 when recalcing share-kill for " . $this->torrent . ". setting sharekill absolute to " . $this->sharekill;
             AuditAction($this->cfg["constants"]["error"], $this->messages);
             $this->sharekill_param = $this->sharekill;
         }
     } else {
         $this->sharekill_param = $this->sharekill;
     }
     // set port if start (not queue)
     if (!($this->cfg["AllowQueing"] && $this->queue == "1")) {
         if ($this->setClientPort() === false) {
             return;
         }
     }
     //XFER: before a torrent start/restart save upload/download xfer to SQL
     $torrentTotals = getTorrentTotalsCurrent($this->torrent);
     saveXfer($this->owner, $torrentTotals["downtotal"] + 0, $torrentTotals["uptotal"] + 0);
     // update totals for this torrent
     updateTorrentTotals($this->torrent);
     // write stat-file
     if ($this->cfg["AllowQueing"] && $this->queue == "1") {
         $this->af->QueueTorrentFile();
     } else {
         $this->af->StartTorrentFile();
     }
     // set state
     $this->state = 2;
 }
Ejemplo n.º 7
0
 /**
  * ctor
  */
 function FluAzu()
 {
     global $cfg;
     // paths
     $this->_pathDataDir = $cfg["path"] . '.fluazu/';
     $this->_pathPidFile = $this->_pathDataDir . 'fluazu.pid';
     $this->_pathCommandFile = $this->_pathDataDir . 'fluazu.cmd';
     $this->_pathLogFile = $this->_pathDataDir . 'fluazu.log';
     $this->_pathStatFile = $this->_pathDataDir . 'fluazu.stat';
     $this->_pathTransfers = $this->_pathDataDir . 'cur/';
     $this->_pathTransfersRun = $this->_pathDataDir . 'run/';
     $this->_pathTransfersDel = $this->_pathDataDir . 'del/';
     // check path
     if (!checkDirectory($this->_pathDataDir)) {
         @error("fluazu-Main-Path does not exist and cannot be created or is not writable", "admin.php?op=serverSettings", "Server-Settings", array("path : " . $this->_pathDataDir));
     }
     // check if fluazu running
     if ($this->instance_isRunning()) {
         $this->state = FLUAZU_STATE_RUNNING;
     }
 }
/**
 * checks main-directories.
 *
 * @return boolean
 */
function checkMainDirectories()
{
    global $cfg;
    // main-path
    if (!checkDirectory($cfg["path"])) {
        @error("Main-Path does not exist and cannot be created or is not writable", "admin.php?op=serverSettings", "Server-Settings", array("path : " . $cfg["path"]));
    }
    // transfer-path
    if (!checkDirectory($cfg["transfer_file_path"])) {
        @error("Transfer-File-Path does not exist and cannot be created or is not writable", "admin.php?op=serverSettings", "Server-Settings", array("transfer_file_path : " . $cfg["transfer_file_path"]));
    }
}
Ejemplo n.º 9
0
if (!defined("ENT_COMPAT")) {
    define("ENT_COMPAT", 2);
}
if (!defined("ENT_NOQUOTES")) {
    define("ENT_NOQUOTES", 0);
}
if (!defined("ENT_QUOTES")) {
    define("ENT_QUOTES", 3);
}
// Get RSS feeds from Database
$arURL = GetRSSLinks();
// create lastRSS object
$rss = new lastRSS();
// setup transparent cache
$cacheDir = $cfg['path'] . ".rsscache";
if (!checkDirectory($cacheDir, 0777)) {
    @error("Error with rss-cache-dir", "index.php?iid=index", "", array($cacheDir));
}
$rss->cache_dir = $cacheDir;
$rss->cache_time = $cfg["rss_cache_min"] * 60;
// 1200 = 20 min.  3600 = 1 hour
$rss->strip_html = false;
// don't remove HTML from the description
// init template-instance
tmplInitializeInstance($cfg["theme"], "page.readrss.tmpl");
// set vars
// Loop through each RSS feed
$rss_list = array();
foreach ($arURL as $rid => $url) {
    if (isset($_REQUEST["debug"])) {
        $rss->cache_time = 0;
Ejemplo n.º 10
0
/*** check table field expand by preload ***/
if (!checkTable()) {
    $messages[] = 'You must put extras/extra_preload/upgrade22.class.php in ' . XOOPS_ROOT_PATH . '/preload';
}
/*** check latest language file ***/
$lang = XCube_Root::getSingleton()->mLanguageManager->mLanguageName;
if (!checkLanguage($lang)) {
    $messages[] = 'You must move the latest language files from extras/extra_languages/' . $lang . '. DON\'T MOVE /install directory !';
}
/*** check file existing ***/
$files = checkFile();
foreach ($files as $file) {
    $messages[] = $file;
}
/*** check directory existing ***/
$directories = checkDirectory();
foreach ($directories as $dir) {
    $messages[] = $dir;
}
/*** check directory permission to write ***/
$permissions = checkPermission();
foreach ($permissions as $perm) {
    $messages[] = $perm;
}
/*** check module version, if updated by module admin ***/
$modules = checkVersion();
foreach ($modules as $mod) {
    $messages[] = 'You must upgrade module "' . $mod . '" in module administration page.';
}
if (count($messages) === 0) {
    $messages[] = 'Congraturation! You are ready for upgrade XCL2.2.<br />Remove ' . XOOPS_ROOT_PATH . '/legacy22_check.php file.';
Ejemplo n.º 11
0
/**
 * checks a dir. recursive process to emulate "mkdir -p" if dir not present
 *
 * @param $dir the name of the dir
 * @param $mode the mode of the dir if created. default is 0755
 * @return boolean if dir exists/could be created
 */
function checkDirectory($dir, $mode = 0755)
{
    if (is_dir($dir) && is_writable($dir) || @mkdir($dir, $mode)) {
        return true;
    }
    if (!checkDirectory(dirname($dir), $mode)) {
        return false;
    }
    return @mkdir($dir, $mode);
}
Ejemplo n.º 12
0
// set vars
// path
$tmpl->setvar('path', $cfg["path"]);
if (is_dir($cfg["path"])) {
    $tmpl->setvar('is_path', 1);
    $tmpl->setvar('is_writable', is_writable($cfg["path"]) ? 1 : 0);
} else {
    $tmpl->setvar('is_path', 0);
}
// docroot
$tmpl->setvar('docroot', $cfg["docroot"]);
$tmpl->setvar('is_docroot', is_file($cfg["docroot"] . "version.php") ? 1 : 0);
// homedirs + incoming
$tmpl->setvar('enable_home_dirs', $cfg["enable_home_dirs"]);
$tmpl->setvar('path_incoming', $cfg["path_incoming"]);
$tmpl->setvar('path_incoming_ok', checkDirectory($cfg["path"] . $cfg["path_incoming"], 0777) ? 1 : 0);
// bins
$tmpl->setvar('btclient_transmission_bin', $cfg["btclient_transmission_bin"]);
$tmpl->setvar('validate_transmission_bin', validateTransmissionCli($cfg["btclient_transmission_bin"]));
$tmpl->setvar('perlCmd', $cfg["perlCmd"]);
$tmpl->setvar('validate_perl', validateBinary($cfg["perlCmd"]));
$tmpl->setvar('bin_grep', $cfg["bin_grep"]);
$tmpl->setvar('validate_grep', validateBinary($cfg["bin_grep"]));
$tmpl->setvar('bin_php', $cfg["bin_php"]);
$tmpl->setvar('validate_php', validatePhpCli($cfg["bin_php"]));
$tmpl->setvar('pythonCmd', $cfg["pythonCmd"]);
$tmpl->setvar('validate_python', validateBinary($cfg["pythonCmd"]));
$tmpl->setvar('bin_awk', $cfg["bin_awk"]);
$tmpl->setvar('validate_awk', validateBinary($cfg["bin_awk"]));
$tmpl->setvar('bin_du', $cfg["bin_du"]);
$tmpl->setvar('validate_du', validateBinary($cfg["bin_du"]));
Ejemplo n.º 13
0
function checkDirectory($path)
{
    global $fsPath, $aIgnore;
    $fullpath = sprintf('%s/%s', $fsPath, $path);
    if (!is_dir($fullpath)) {
        print "Not a directory: {$fullpath}\n";
    }
    if ($path === '/Deleted') {
        // Deleted files handled separately.
        return;
    }
    if (!empty($path)) {
        $fod = KTBrowseUtil::folderOrDocument($path);
        if ($fod === false) {
            $GLOBALS['aFoldersToRemove'][] = $path;
            return;
        }
    }
    $dh = @opendir($fullpath);
    if ($dh === false) {
        print "Could not open directory: {$fullpath}\n";
    }
    while (($filename = readdir($dh)) !== false) {
        if (in_array($filename, $aIgnore)) {
            continue;
        }
        $subrelpath = sprintf('%s/%s', $path, $filename);
        $subfullpath = sprintf('%s/%s', $fsPath, $subrelpath);
        if (is_dir($subfullpath)) {
            checkDirectory($subrelpath);
        }
        if (is_file($subfullpath)) {
            checkFile($subrelpath);
        }
    }
}
Ejemplo n.º 14
0
 if ($targetDir == "" && isset($_POST['selector'])) {
     $targetDir = trim(urldecode($_POST['selector']));
 }
 $dirValid = true;
 if (strlen($targetDir) <= 0) {
     $dirValid = false;
 } else {
     // we need absolute paths or stuff will end up in docroot
     // inform user .. dont move it into a fallback-dir which may be a hastle
     if ($targetDir[0] != '/') {
         echo "Target-dirs must be specified with absolute and not relative paths. <br>";
         $dirValid = false;
     }
 }
 // check dir
 if ($dirValid && checkDirectory($targetDir, 0777)) {
     $targetDir = checkDirPathString($targetDir);
     // move
     $cmd = "mv \"" . $cfg["path"] . $_POST['file'] . "\" " . $targetDir . "";
     $cmd .= ' 2>&1';
     $handle = popen($cmd, 'r');
     // get the output and print it.
     $gotError = -1;
     while (!feof($handle)) {
         $buff = fgets($handle, 30);
         echo nl2br($buff);
         @ob_flush();
         @flush();
         $gotError = $gotError + 1;
     }
     pclose($handle);
 /**
  * updates a single job
  *
  * @param $jobNumber
  * @param $savedir
  * @param $url
  * @param $filtername
  * @return boolean
  */
 function instance_jobUpdate($jobNumber, $savedir, $url, $filtername, $checkdir = false)
 {
     if ($jobNumber > 0 && strlen($savedir) > 0 && strlen($url) > 0 && strlen($filtername) > 0) {
         $jobs = $this->instance_jobsGetList();
         if ($jobs !== false && count($jobs) > 0) {
             $result = array();
             $idx = 1;
             while (count($jobs) > 0) {
                 $job = array_shift($jobs);
                 if ($idx != $jobNumber) {
                     array_push($result, $job);
                 } else {
                     array_push($result, array('savedir' => trim(checkDirPathString($savedir)), 'url' => $url, 'filtername' => $filtername));
                 }
                 $idx++;
             }
             $jobsString = "";
             $resultCount = count($result);
             for ($i = 0; $i < $resultCount; $i++) {
                 $jobsString .= $result[$i]["savedir"] . $this->_delimJob;
                 $jobsString .= $result[$i]["url"] . $this->_delimJob;
                 $jobsString .= $result[$i]["filtername"];
                 if ($i < $resultCount - 1) {
                     $jobsString .= $this->_delimJobs;
                 }
             }
             // check dir
             if ($checkdir) {
                 $check = checkDirectory($savedir);
                 if (!$check) {
                     array_push($this->messages, "dir " . $savedir . " does not exist and could not be created.");
                 }
             } else {
                 $check = true;
             }
             // update setting
             return $check && $this->_jobsUpdate($jobsString);
         }
         return false;
     } else {
         return false;
     }
 }
/**
 * checks a dir. recursive process to emulate "mkdir -p" if dir not present
 *
 * @param $dir the name of the dir
 * @param $mode the mode of the dir if created. default is 0755
 * @return boolean if dir exists/could be created
 */
function checkDirectory($dir, $mode = 0755, $depth = 0)
{
    if ($depth > 32) {
        return false;
    }
    if (@is_dir($dir) && @is_writable($dir) || @mkdir($dir, $mode)) {
        return true;
    }
    if ($dir == '/') {
        return false;
    }
    if (!@checkDirectory(dirname($dir), $mode, ++$depth)) {
        return false;
    }
    return @mkdir($dir, $mode);
}
 /**
  * init start of a client.
  *
  * @param $interactive
  * @param $enqueue
  * @param $setPort
  * @param $recalcSharekill
  */
 function _init($interactive, $enqueue = false, $setPort = false, $recalcSharekill = false)
 {
     global $cfg;
     // request-vars / defaults / database
     if ($interactive) {
         // interactive, get vars from request vars
         $this->settingsInit();
     } else {
         // non-interactive, load settings from db
         $this->skip_hash_check = $cfg["skiphashcheck"];
         // load settings, default if settings could not be loaded (fresh transfer)
         if ($this->settingsLoad() !== true) {
             $this->settingsDefault();
         }
     }
     // queue
     if ($enqueue) {
         $this->queue = $cfg['isAdmin'] ? $enqueue : true;
     } else {
         $this->queue = false;
     }
     // savepath-check
     if (empty($this->savepath)) {
         $this->savepath = $cfg["enable_home_dirs"] != 0 ? $cfg['path'] . $this->owner . "/" : $cfg['path'] . $cfg["path_incoming"] . "/";
     } else {
         $this->savepath = checkDirPathString($this->savepath);
     }
     // check target-directory, create if not present
     if (!checkDirectory($this->savepath, 0777)) {
         $this->state = CLIENTHANDLER_STATE_ERROR;
         $msg = "Error checking savepath " . $this->savepath;
         array_push($this->messages, $msg);
         AuditAction($cfg["constants"]["error"], $msg);
         $this->logMessage($msg . "\n", true);
         // write error to stat
         $sf = new StatFile($this->transfer, $this->owner);
         $sf->time_left = 'Error';
         $sf->write();
         return false;
     }
     // umask
     $this->umask = $cfg["enable_umask"] != 0 ? " umask 0000;" : "";
     // nice
     $this->nice = $cfg["nice_adjust"] != 0 ? "nice -n " . $cfg["nice_adjust"] . " " : "";
     // set param for sharekill
     $this->sharekill = intval($this->sharekill);
     // recalc sharekill
     if ($recalcSharekill) {
         if ($this->_recalcSharekill() === false) {
             return false;
         }
     } else {
         $this->sharekill_param = $this->sharekill;
         $this->logMessage("setting sharekill-param to " . $this->sharekill_param . "\n", true);
     }
     // set port if start (only if not queue)
     if ($setPort && !$this->queue) {
         if ($this->_setClientPort() === false) {
             return false;
         }
     }
     // get current transfer
     $transferTotals = $this->getTransferCurrent($this->transfer);
     //XFER: before a transfer start/restart save upload/download xfer to SQL
     if ($cfg['enable_xfer'] == 1) {
         Xfer::save($this->owner, $transferTotals["downtotal"], $transferTotals["uptotal"]);
     }
     // update totals for this transfer
     $this->_updateTotals();
     // set state
     $this->state = CLIENTHANDLER_STATE_READY;
 }
 /**
  * update a job
  *
  * @param $jobnumber
  * @param $watchdir
  * @param $user
  * @param $profile
  * @param $checkdir
  * @return boolean
  */
 function instance_jobUpdate($jobnumber, $watchdir, $user, $profile, $checkdir = false)
 {
     $jobInt = intval($jobnumber);
     if ($jobInt > 0 && strlen($watchdir) > 0 && strlen($user) > 0) {
         $watchdir = checkDirPathString($watchdir);
         // Get current jobs and make sure modified one is not a duplicate.
         $jobs = $this->instance_jobsGetList();
         if ($jobs !== false && count($jobs) >= $jobInt) {
             $jobs[$jobInt - 1] = array();
             foreach ($jobs as $job) {
                 if (isset($job['D']) && $job['D'] == $watchdir) {
                     array_push($this->messages, "dir " . $watchdir . " is already begin watched.");
                     return false;
                 }
             }
             // Check/create dir if needed.
             if ($checkdir && !checkDirectory($watchdir)) {
                 array_push($this->messages, "dir " . $watchdir . " does not exist and could not be created.");
                 return false;
             }
             // Create new job.
             $job = array('U' => $user, 'D' => $watchdir);
             if (isset($profile)) {
                 $job['P'] = $profile;
             }
             $jobs[$jobInt - 1] = $job;
             // Update settings.
             return $this->_jobsUpdateSetting($jobs);
         }
     }
     return false;
 }
 if (!empty($list_changes)) {
     $tmpl->setloop('list_changes', $list_changes);
 }
 if (empty($list_send)) {
     $doSend = false;
 } else {
     $tmpl->setloop('list_send', $list_send);
 }
 if (!empty($list_restart)) {
     $tmpl->setloop('list_restart', $list_restart);
 }
 // save settings
 if ($cfg["showdirtree"] == 1) {
     $newSavepath = checkDirPathString($settingsNew['savepath']);
     if ($newSavepath != $settingsCurrent['savepath']) {
         if (@checkDirectory($newSavepath, 0777) !== true) {
             $tmpl->setvar('error', "savepath " . $newSavepath . " not valid and change not saved.");
         } else {
             $ch->savepath = $newSavepath;
         }
     }
 }
 $ch->rate = $settingsNew['max_upload_rate'];
 $ch->drate = $settingsNew['max_download_rate'];
 $ch->maxuploads = $settingsNew['max_uploads'];
 $ch->superseeder = $settingsNew['superseeder'];
 $ch->runtime = $settingsNew['die_when_done'];
 $ch->sharekill = $settingsNew['sharekill'];
 $ch->minport = $settingsNew['minport'];
 $ch->maxport = $settingsNew['maxport'];
 $ch->maxcons = $settingsNew['maxcons'];
Ejemplo n.º 20
0
/**
 * checks a dir. recursive process to emulate "mkdir -p" if dir not present
 *
 * @param $dir the name of the dir
 * @param $mode the mode of the dir if created. default is 0755
 * @return boolean if dir exists/could be created
 */
function checkDirectory($dir, $mode = 0755)
{
    global $CHECKDIR_RECURSION;
    if (isset($CHECKDIR_RECURSION)) {
        $CHECKDIR_RECURSION++;
    } else {
        $CHECKDIR_RECURSION = 0;
    }
    if ($CHECKDIR_RECURSION > 10) {
        return false;
    }
    if (@is_dir($dir) && @is_writable($dir) || @mkdir($dir, $mode)) {
        return true;
    }
    if (!@checkDirectory(dirname($dir), $mode)) {
        return false;
    }
    return @mkdir($dir, $mode);
}
Ejemplo n.º 21
0
/**
 * Add task for a work
 * *******************
 *
 * @param  (string) (url) Url for task
 * @param  (string) (saveAs) Save to this file name
 * @return (array)
 */
function addWgetTask($url, $saveAs)
{
    function checkPermissions($path)
    {
        return file_exists($path) && is_dir($path) && is_writable($path) ? true : false;
    }
    function checkDirectory($dir)
    {
        if (!checkPermissions($dir)) {
            mkdir($dir, 0777, true);
            chmod($dir, 0777);
            return checkPermissions($dir) ? true : false;
        }
        return true;
    }
    log::debug('(call) addWgetTask() called, $url=' . var_export($url, true) . ', $saveAs=' . var_export($saveAs, true));
    define('OriginalTaskUrl', $url);
    // Save in constant original task url
    if (empty($url)) {
        return array('result' => false, 'msg' => 'No URL');
    }
    if (defined('WGET_ONE_TIME_LIMIT') && count(getWgetTasks()) + 1 > WGET_ONE_TIME_LIMIT) {
        log::notice('Task not added, because one time tasks limit is reached');
        return array('result' => false, 'msg' => 'One time tasks limit is reached');
    }
    if (!defined('DOWNLOAD_PATH')) {
        log::error('"DOWNLOAD_PATH" not defined');
        return array('result' => false, 'msg' => '"DOWNLOAD_PATH" not defined');
    }
    if (!checkDirectory(DOWNLOAD_PATH)) {
        log::error('Directory ' . var_export(DOWNLOAD_PATH, true) . ' cannot be created');
        return array('result' => false, 'msg' => 'Cannot create directory for downloads');
    }
    // DOWNLOAD YOUTUBE VIDEO
    // Detect - if url is link to youtube video
    if (stripos($url, 'youtube.com/') !== false || stripos($url, 'youtu.be/') !== false) {
        $youtubeVideos = array();
        // http://stackoverflow.com/a/10315969/2252921
        preg_match('/^(?:https?:\\/\\/)?(?:www\\.)?(?:youtu\\.be\\/|youtube\\.com\\/(?:embed\\/|v\\/|watch\\?v=|watch\\?.+&v=))((\\w|-){11})(?:\\S+)?$/i', $url, $founded);
        define('YoutubeVideoID', @$founded[1]);
        // Set as constant YouTube video ID
        if (strlen(YoutubeVideoID) == 11) {
            $rawVideoInfo = file_get_contents('http://youtube.com/get_video_info?video_id=' . YoutubeVideoID . '&ps=default&eurl=&gl=US&hl=en');
            if ($rawVideoInfo !== false) {
                parse_str($rawVideoInfo, $videoInfo);
                //var_dump($videoInfo);
                if (isset($videoInfo['url_encoded_fmt_stream_map'])) {
                    $my_formats_array = explode(',', $videoInfo['url_encoded_fmt_stream_map']);
                    foreach ($my_formats_array as $videoItem) {
                        parse_str($videoItem, $videoItemData);
                        if (isset($videoItemData['url'])) {
                            //var_dump($videoItemData);
                            switch (@$videoItemData['quality']) {
                                case 'small':
                                    $videoItemData['quality'] = '240p';
                                    break;
                                case 'medium':
                                    $videoItemData['quality'] = '360p';
                                    break;
                                case 'large':
                                    $videoItemData['quality'] = '480p';
                                    break;
                                case 'hd720':
                                    $videoItemData['quality'] = '720p';
                                    break;
                                case 'hd1080':
                                    $videoItemData['quality'] = '1080p';
                                    break;
                            }
                            array_push($youtubeVideos, array('title' => trim(@$videoInfo['title']), 'thumbnail' => @$videoInfo['thumbnail_url'], 'url' => urldecode($videoItemData['url']), 'type' => @$videoItemData['type'], 'quality' => @$videoItemData['quality']));
                        } else {
                            log::error('Link to youtube source video file not exists ' . var_export($videoItemData, true));
                            return array('result' => false, 'msg' => 'Link to youtube source video file not exists');
                        }
                    }
                } else {
                    $errorDescription = 'Youtube answer not contains data about video files';
                    if (isset($videoInfo['reason']) && !empty($videoInfo['reason'])) {
                        $errorDescription = trim(strip_tags($videoInfo['reason'], '<a><br/>'));
                    }
                    log::error($errorDescription . ', raw=' . var_export($rawVideoInfo, true));
                    return array('result' => false, 'msg' => $errorDescription);
                }
            } else {
                log::error('Cannot call "file_get_contents()" for $url=' . var_export($url, true));
                return array('result' => false, 'msg' => 'Cannot get remote content');
            }
        }
        //var_dump($youtubeVideos);
        // If we found video links
        if (count($youtubeVideos) > 0) {
            // Get first 'mp4' video
            foreach ($youtubeVideos as $video) {
                if (isset($video['type']) && !empty($video['type'])) {
                    preg_match('~\\/(.*?)\\;~', $video['type'], $videoType);
                    if (@$videoType[1] == 'mp4') {
                        $videoToDownload = $video;
                        break;
                    }
                }
            }
            // Or take first video (by default - with highest quality)
            if (!isset($videoToDownload)) {
                $videoToDownload = $youtubeVideos[0];
            }
            preg_match('~\\/(.*?)\\;~', $videoToDownload['type'], $extension);
            switch (@$extension[1]) {
                case 'mp4':
                    $fileExtension = 'mp4';
                    break;
                case 'webm':
                    $fileExtension = 'webm';
                    break;
                case 'x-flv':
                    $fileExtension = 'flv';
                    break;
                case '3gpp':
                    $fileExtension = '3gp';
                    break;
                default:
                    $fileExtension = 'video';
            }
            $clearTitle = makeStringSafe(@$videoToDownload['title']);
            // Tadaaam :)
            $url = $videoToDownload['url'];
            if (empty($saveAs)) {
                if (empty($clearTitle)) {
                    $saveAs = 'youtube_video_id' . YoutubeVideoID . ' (' . $videoToDownload['quality'] . ').' . $fileExtension;
                } else {
                    $saveAs = $videoToDownload['title'] . ' (' . $videoToDownload['quality'] . ').' . $fileExtension;
                }
            }
        }
    }
    // DOWNLOAD VK.COM VIDEO
    // Detect - if url is link to vk.com video
    if (stripos($url, 'vk.com/video_ext.php') !== false) {
        // For test code/decode url - http://meyerweb.com/eric/tools/dencoder/
        // Get url query and parse it to $q
        $urlParts = parse_url(urldecode($url));
        parse_str($urlParts['query'], $q);
        define('VkVideoID', @$q['id']);
        // Set as constant VK video ID
        if (isset($q['oid']) && !empty($q['oid']) && is_numeric($q['oid']) && is_numeric(VkVideoID) && isset($q['hash']) && !empty($q['hash'])) {
            // Build request url
            $queryUrl = 'https://vk.com/video_ext.php?oid=' . $q['oid'] . '&id=' . $q['id'] . '&hash=' . $q['hash'];
            // Get page content
            $rawVideoInfo = file_get_contents($queryUrl);
            if ($rawVideoInfo !== false) {
                if (preg_match('/.*\\<div.*id\\=\\"video_player\\".*/im', $rawVideoInfo) !== 0) {
                    $videoData = array();
                    preg_match('/\\&amp\\;url240\\=(.*?)\\&amp\\;/i', $rawVideoInfo, $f);
                    $videoData['240'] = urldecode(@$f[1]);
                    preg_match('/\\&amp\\;url360\\=(.*?)\\&amp\\;/i', $rawVideoInfo, $f);
                    $videoData['360'] = urldecode(@$f[1]);
                    preg_match('/\\&amp\\;url480\\=(.*?)\\&amp\\;/i', $rawVideoInfo, $f);
                    $videoData['480'] = urldecode(@$f[1]);
                    preg_match('/\\&amp\\;url720\\=(.*?)\\&amp\\;/i', $rawVideoInfo, $f);
                    $videoData['720'] = urldecode(@$f[1]);
                    preg_match('/\\&amp\\;thumb\\=(.*?)\\&amp\\;/i', $rawVideoInfo, $f);
                    $videoData['thumbnail'] = trim(urldecode(@$f[1]));
                    preg_match('/\\&amp\\;md_title\\=(.*?)\\&amp\\;/i', $rawVideoInfo, $f);
                    $videoData['title'] = trim(urldecode(@$f[1]));
                    // video in low quality always must exists, if parse complete without errors
                    if (isset($videoData['240']) && !empty($videoData['240'])) {
                        $videoQualityStr = '';
                        if (isset($videoData['240']) && !empty($videoData['240'])) {
                            $url = $videoData['240'];
                            $videoQualityStr = '240p';
                        }
                        if (isset($videoData['360']) && !empty($videoData['360'])) {
                            $url = $videoData['360'];
                            $videoQualityStr = '360p';
                        }
                        if (isset($videoData['480']) && !empty($videoData['480'])) {
                            $url = $videoData['480'];
                            $videoQualityStr = '480p';
                        }
                        if (isset($videoData['720']) && !empty($videoData['720'])) {
                            $url = $videoData['720'];
                            $videoQualityStr = '720p';
                        }
                        $clearTitle = makeStringSafe(@$videoData['title']);
                        if (empty($saveAs)) {
                            if (empty($clearTitle)) {
                                $saveAs = 'vk_video_id' . VkVideoID . ' (' . $videoQualityStr . ').mp4';
                            } else {
                                $saveAs = $clearTitle . ' (' . $videoQualityStr . ').mp4';
                            }
                        }
                    } else {
                        log::error('Link to video file not found');
                        return array('result' => false, 'msg' => 'Link to video file not found');
                    }
                } else {
                    log::error('Video container not found $queryUrl=' . var_export($queryUrl, true));
                    return array('result' => false, 'msg' => 'Video container not found');
                }
            } else {
                log::error('Cannot call "file_get_contents()" for $url=' . var_export($url, true));
                return array('result' => false, 'msg' => 'Cannot get remote content');
            }
        } else {
            log::error('Request error - some important query part not exists, $url=' . var_export($url, true));
            return array('result' => false, 'msg' => 'Request error - some important query part(s) not exists');
        }
    }
    // DROPBOX 'Content-Disposition' bug fix
    // Issue - <https://github.com/tarampampam/wget-gui-light/issues/17>
    if (stripos($url, 'dropboxusercontent.com/') !== false) {
        $file_name = basename($url);
        if (!empty($file_name)) {
            $saveAs = $file_name;
        }
    }
    //var_dump($videoToDownload);
    $historyAction = '';
    $saveAs = makeStringSafe($saveAs);
    if (defined('LOG_HISTORY')) {
        if (checkDirectory(dirname(LOG_HISTORY))) {
            $savedAsCmdString = !empty($saveAs) ? ' ## SavedAs: \\"' . $saveAs . '\\"' : '';
            // If string passed in '$url' and saved 'OriginalTaskUrl' not equal each other,
            //   we understand - URL was PARSED and changed. And now, for a history
            //   (tadatadaaaam =)) we must write ORIGINAL url (not parsed)
            $urlForHistory = $url !== OriginalTaskUrl ? OriginalTaskUrl : $url;
            $urlForHistoryCmd = $url !== OriginalTaskUrl ? ' && URL="' . $urlForHistory . '"' : '';
            $historyAction = ' && HISTORY="' . LOG_HISTORY . '"' . $urlForHistoryCmd . ' && if [ "$?" = "0" ]; then ' . 'echo "Success: \\"$URL\\"' . $savedAsCmdString . '" >> "$HISTORY"; ' . 'else ' . 'echo "Failed: \\"$URL\\"" >> "$HISTORY"; ' . 'fi';
        } else {
            log::error('Directory ' . var_export(dirname(LOG_HISTORY), true) . ' cannot be created');
        }
    }
    $speedLimit = defined('WGET_DOWNLOAD_LIMIT') ? '--limit-rate=' . WGET_DOWNLOAD_LIMIT . 'k ' : ' ';
    $saveAsFile = !empty($saveAs) ? '--output-document="' . DOWNLOAD_PATH . '/' . $saveAs . '" ' : ' ';
    $tmpFileName = TMP_PATH . '/wget' . rand(1, 32768) . '.log.tmp';
    $cmd = '(URL="' . $url . '"; TMPFILE="' . $tmpFileName . '"; echo > "$TMPFILE"; ' . wget . ' ' . '--progress=bar:force --output-file="$TMPFILE" ' . '--tries=0 ' . '--no-check-certificate ' . '--no-cache ' . '--user-agent="Mozilla/5.0 (X11; Linux amd64; rv:21.0) Gecko/20100101 Firefox/21.0" ' . '--directory-prefix="' . DOWNLOAD_PATH . '" ' . '--content-disposition ' . '--restrict-file-names=nocontrol ' . $speedLimit . $saveAsFile . ' ' . WGET_SECRET_FLAG . ' ' . '"$URL"' . $historyAction . '; ' . rm . ' -f "$TMPFILE") > /dev/null 2>&1 & echo $!';
    log::debug('Command to exec: ' . var_export($cmd, true));
    $task = bash($cmd, 'string');
    if (empty($task)) {
        log::error('Exec task ' . var_export($cmd, true) . ' error');
        return array('result' => false, 'msg' => 'Exec task error');
    }
    usleep(100000);
    // 1/10 sec
    preg_match("/(\\d{2,7})/i", $task, $founded);
    $parentPid = @$founded[1];
    if (!validatePid($parentPid)) {
        log::error('Parent PID ' . var_export($parentPid, true) . ' for task ' . var_export($url, true) . ' not valid');
        return array('result' => false, 'msg' => 'Parent PID not valid');
    }
    //var_dump($cmd); var_dump($task); var_dump($parentPid);
    // Wait ~1 sec until child pipe not running, check every second
    for ($i = 1; $i <= 4; $i++) {
        // Get pipe with out wget task (search by $tmpFileName)
        $taskData = getWgetTasksList($tmpFileName);
        // Get last job with current URL
        $taskPid = @$taskData[0]['pid'];
        if (validatePid($taskPid)) {
            break;
        } else {
            usleep(250000);
        }
        // 1/4 sec
    }
    if (!file_exists($tmpFileName)) {
        log::notice('Task ' . var_export($url, true) . ' already complete (probably with error)');
        return array('result' => true, 'msg' => 'Task completed too fast (probably with error)');
    }
    if (!validatePid($taskPid)) {
        log::error('Task PID ' . var_export($taskPid, true) . ' for ' . var_export($url, true) . ' not valid');
        return array('result' => false, 'msg' => 'Task PID not valid');
    }
    log::notice('Task ' . var_export($url, true) . ' added successful (pid ' . var_export($taskPid, true) . ')');
    return array('result' => true, 'pid' => (int) $taskPid, 'msg' => 'Task added successful');
}