Пример #1
0
 public function on_run($pars)
 {
     $bundle_id = $this->stripFileName($pars['bundle']);
     $scriptname = $this->stripFileName($pars['script']);
     $script_path = $this->configuration['support-path'] . '/bundles/' . $bundle_id . '/scripts/' . $scriptname . '.php';
     @(include_once $script_path);
     if (function_exists('run_script')) {
         run_script($this, $pars);
         self::raiseError('Script returned no result.');
     } else {
         self::raiseError('Script not found.');
     }
 }
Пример #2
0
function apply_fixes($version)
{
    $queries = array();
    if ($version == 'sfee3.3') {
        $res = db_query("SELECT COUNT(*) AS applied FROM database_changes WHERE filename='sfee3.3fixes'");
        if ($res && db_result($res, 0, 'applied') == '0') {
            show("Converting SFEE3.3 to SFEE3.0\n");
            run_script(array('filename' => 'sfee3.3-3.0-1.sql', 'ext' => 'sql'));
            run_script(array('filename' => 'sfee3.3-3.0-2.php', 'ext' => 'php'));
            run_script(array('filename' => 'sfee3.3-3.0-3.sql', 'ext' => 'sql'));
            show("Converting SFEE3.0 to SF2.6\n");
            //sfee3.0-sf26-1.sql
            run_script(array('filename' => 'sfee3.0-sf26-1.sql', 'ext' => 'sql'));
            run_script(array('filename' => 'sfee3.0-sf26-2.php', 'ext' => 'php'));
            $queries[] = "INSERT INTO database_changes (filename) VALUES ('sfee3.3fixes')";
        }
    } else {
        if ($version == 'sfee3.0') {
            $res = db_query("SELECT COUNT(*) AS applied FROM database_changes WHERE filename='sfee3.0fixes'");
            if ($res && db_result($res, 0, 'applied') == '0') {
                run_script(array('filename' => 'sfee3.0-sf26-1.sql', 'ext' => 'sql'));
                run_script(array('filename' => 'sfee3.0-sf26-2.php', 'ext' => 'php'));
                $queries[] = "INSERT INTO database_changes (filename) VALUES ('sfee3.0fixes')";
            }
        } else {
            if ($version == '2.5') {
                $res = db_query("SELECT COUNT(*) AS applied FROM database_changes WHERE filename='2.5fixes'");
                if ($res && db_result($res, 0, 'applied') == '0') {
                    show("Applying fixes for version 2.5\n");
                    $queries[] = "ALTER TABLE project_task ADD CONSTRAINT project_task_group_project_id_f CHECK (1 = 1)";
                    $queries[] = "INSERT INTO database_changes (filename) VALUES ('2.5fixes')";
                }
            } else {
                if ($version == '2.6') {
                    $res = db_query("SELECT COUNT(*) AS applied FROM database_changes WHERE filename='2.6fixes'");
                    if ($res && db_result($res, 0, 'applied') == '0') {
                        show("Applying fixes for version 2.6\n");
                        $queries[] = "ALTER TABLE project_task ADD CONSTRAINT project_task_group_project_id_f CHECK (1 = 1)";
                        $queries[] = "INSERT INTO database_changes (filename) VALUES ('2.6fixes')";
                    }
                } else {
                    if ($version == '3.0pre5') {
                        $res = db_query("SELECT COUNT(*) AS applied FROM database_changes WHERE filename='3.0pre5fixes'");
                        if ($res && db_result($res, 0, 'applied') == '0') {
                            show("Applying fixes for version 3.0pre5\n");
                            if (!run_sql_script('fix-gforge3.0pre5.sql')) {
                                show("Error applying fixes for version 3.0pre5\n");
                                //exit();
                            }
                            $queries[] = "INSERT INTO database_changes (filename) VALUES ('3.0pre5fixes')";
                        }
                    } else {
                        if ($version == '3.0pre6') {
                            $res = db_query("SELECT COUNT(*) AS applied FROM database_changes WHERE filename='3.0pre6fixes'");
                            if ($res && db_result($res, 0, 'applied') == '0') {
                                show("Applying fixes for version 3.0pre6\n");
                                $queries[] = "ALTER TABLE project_task ADD CONSTRAINT project_task_group_project_id_f CHECK (1 = 1)";
                                $queries[] = "INSERT INTO database_changes (filename) VALUES ('3.0pre6fixes')";
                            }
                        } else {
                            if ($version == '3.0pre7') {
                                $res = db_query("SELECT COUNT(*) AS applied FROM database_changes WHERE filename='3.0pre7fixes'");
                                if ($res && db_result($res, 0, 'applied') == '0') {
                                    show("Applying fixes for version 3.0pre7\n");
                                    $queries[] = "ALTER TABLE project_task ADD CONSTRAINT project_task_group_project_id_f CHECK (1 = 1)";
                                    $queries[] = "INSERT INTO database_changes (filename) VALUES ('3.0pre7fixes')";
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    //db_begin();
    foreach ($queries as $query) {
        $res = db_query($query);
        if (!$res) {
            show("ERROR: " . db_error() . "\n");
            //		db_rollback();
            return false;
        }
    }
    //db_commit();
    return true;
}
function do_action(&$env, $action)
{
    global $RAW_ID;
    global $ERROR;
    if (is_array($action)) {
        foreach ($action as $sub) {
            if (!do_action($env, $sub)) {
                return false;
            }
            if (@$env["HAS_FORKED"] || @$env["DO_BREAK"]) {
                return true;
            }
        }
        return true;
    }
    if (!$action) {
        return true;
    }
    //echo "ACTION: $action\n";
    $oldlevel = $env["LEVEL"];
    $env["LEVEL"]++;
    $ok = false;
    if (!$action) {
        $ok = true;
    } elseif (preg_match("/\\A(script|url)\\s+(.*)/", $action, $matches)) {
        $op = $matches[1];
        $cmd = $matches[2];
        if ($op == "url") {
            $cmd = "wget -O - '{$cmd}'";
        }
        $cmd = subst_macros($env, $cmd);
        $ok = run_script($env, $cmd);
    } else {
        if (preg_match("/\\A(insert|update|delete)\\s+(?:({$RAW_ID})\\s+)?({$RAW_ID}\\s*=.*)/", $action, $matches)) {
            $mode = $matches[1];
            $table = $env["TABLE"];
            if (@$matches[2]) {
                $table = $matches[2];
            }
            $rest = $matches[3];
            $data = array();
            //echo "MODE: $mode\n";
            if ($mode == "update" || $mode == "delete") {
                $primary = _db_primary($table);
                foreach (split(",", $primary) as $pri) {
                    if (isset($env[$pri])) {
                        $data[0][$pri] = $env[$pri];
                    }
                }
            }
            while (preg_match("/\\A\\s*({$RAW_ID})\\s*=\\s*'((?:[^\\']|\\.)*)'(.*)/", $rest, $matches)) {
                $field = $matches[1];
                $value = $matches[2];
                $rest = $matches[3];
                $data[0][$field] = subst_macros($env, $value, "'", "\\'");
            }
            echo_rule($env);
            echo "{$mode} {$table}:";
            foreach ($data[0] as $field => $value) {
                echo " {$field} = '{$value}'";
            }
            echo "\n";
            if ($mode == "delete") {
                $ok = db_delete($table, $data) && !$ERROR;
                check_answer($env, "DELETE {$ok}");
            } elseif ($mode == "update") {
                $ok = db_update($table, $data) && !$ERROR;
                check_answer($env, "UPDATE {$ok}");
            } else {
                $ok = db_insert($table, $data) && !$ERROR;
                check_answer($env, "INSERT {$ok}");
            }
            if (!$ok) {
                check_answer($env, "DB_ERROR {$mode} ({$ERROR})");
            }
        } else {
            if (preg_match("/\\Aquery\\s+({$RAW_ID})\\s+({$RAW_ID})\\s+({$RAW_ID}\\s*=.*)/", $action, $matches)) {
                $var = $matches[1];
                $table = $matches[2];
                $rest = $matches[3];
                $cond = array();
                while (preg_match("/\\A\\s*({$RAW_ID})\\s*=\\s*'((?:[^\\']|\\.)*)'(.*)/", $rest, $matches)) {
                    $field = $matches[1];
                    $value = $matches[2];
                    $rest = $matches[3];
                    $cond[$field] = subst_macros($env, $value, "'", "\\'");
                }
                $data = db_read($table, null, $cond, null, 0, 0);
                //echo "got....."; print_r($data); echo "\n";
                $env[$var] = $data;
                $ok = true;
            } else {
                if (preg_match("/\\Avar\\s+({$RAW_ID}(?:->{$RAW_ID})*)\\s*=\\s*'((?:[^\\']|\\.)*)'/", $action, $matches)) {
                    $var = $matches[1];
                    $expr = $matches[2];
                    $lvalue =& $env;
                    while (preg_match("/\\A(?:->)?({$RAW_ID})(.*)/", $var, $matches)) {
                        $field = $matches[1];
                        $var = $matches[2];
                        $lvalue =& $lvalue[$field];
                    }
                    if ($var) {
                        engine_error("cannot assign to variable '{$var}'");
                    } else {
                        $lvalue = subst_macros($env, $expr, "'", "\\'");
                        $ok = true;
                    }
                } else {
                    if (preg_match("/\\A(call|start)\\s+({$RAW_ID})(.*)/", $action, $matches)) {
                        $ok = false;
                        $mode = $matches[1];
                        $call = $matches[2];
                        $rest = $matches[3];
                        $cond = array("bp_name" => $call);
                        $data = db_read("bps", null, $cond);
                        if (!$data || $ERROR) {
                            check_answer($env, "DB_ERROR read ({$ERROR})");
                        } else {
                            $newenv = array();
                            while (preg_match("/\\A\\s*({$RAW_ID})\\s*=\\s*'((?:[^\\']|\\.)*)'(.*)/", $rest, $matches)) {
                                $field = $matches[1];
                                $value = $matches[2];
                                $rest = $matches[3];
                                $newenv[$field] = subst_macros($env, $value, "'", "\\'");
                            }
                            if ($rest) {
                                engine_error("bad call '{$call}', syntax rest '{$rest}'");
                            } else {
                                $statefield = $data[0]["bp_statefield"];
                                $newrec = array();
                                $newrec["state_id"] = null;
                                $newrec["bp_name"] = $call;
                                if ($mode == "start") {
                                    // asynchronous call: make "return" later a nop
                                    $newenv["NO_RETURN"] = true;
                                }
                                $newrec["state_env"] = db_data_to_code($newenv);
                                if (@$newenv["state_value"]) {
                                    $newrec["state_value"] = $newenv["state_value"];
                                }
                                $table = $env["TABLE"];
                                $primary = _db_primary($table);
                                $field = $env["FIELD"];
                                $newrec["state_returnfield"] = "{$table}.{$field}";
                                $id_rec = array();
                                foreach (split(",", $primary) as $pri) {
                                    $id_rec[$pri] = $env[$pri];
                                }
                                $newrec["state_returnid"] = db_data_to_code($id_rec);
                                $ok = db_insert("states", array($newrec)) && !$ERROR;
                                if ($ok) {
                                    if (true) {
                                        echo_rule($env);
                                        echo "call {$table}.{$field} to states\n";
                                    }
                                    // decide whether to finish the caller or not
                                    if ($mode == "call") {
                                        //echo "SHOULD_BREAK....\n";
                                        $env["DO_BREAK"] = true;
                                    } else {
                                    }
                                } else {
                                    check_answer($env, "DB_ERROR insert ({$ERROR})");
                                }
                            }
                        }
                    } else {
                        if (preg_match("/\\Areturn\\s+'((?:[^\\']|\\.)*)'(.*)/", $action, $matches)) {
                            $returnvalue = subst_macros($env, $matches[1], "'", "\\'");
                            $rest = $matches[2];
                            if (@$env["NO_RETURN"]) {
                                // original call was asynchronous: ignore return statement
                                check_answer($env, "NO_RETURN");
                                if (true) {
                                    $table = $env["TABLE"];
                                    $field = $env["FIELD"];
                                    echo_rule($env);
                                    echo "done asynchronous call {$table}.{$field}\n";
                                }
                                $ok = true;
                            } else {
                                // advance the caller's state
                                $split = split("\\.", $env["state_returnfield"]);
                                $tablename = $split[0];
                                $fieldname = $split[1];
                                $oldrec = eval("return " . $env["state_returnid"] . ";");
                                $data = db_read($tablename, null, $oldrec);
                                if (!$data || $ERROR) {
                                    engine_error("cannot re-read caller's data from table {$tablename}");
                                } else {
                                    if ($test = @$data[0]["state_env"]) {
                                        // original caller had an environment
                                        $oldenv = eval("return {$test};");
                                        while (preg_match("/\\A\\s*({$RAW_ID})\\s*=\\s*'((?:[^\\']|\\.)*)'(.*)/", $rest, $matches)) {
                                            $field = $matches[1];
                                            $value = $matches[2];
                                            $rest = $matches[3];
                                            $oldenv[$field] = subst_macros($env, $value, "'", "\\'");
                                        }
                                        if ($rest) {
                                            engine_warn("return statement has unparsable rest '{$rest}'");
                                        }
                                        $oldrec["state_env"] = db_data_to_code($oldenv);
                                    }
                                    $oldrec[$fieldname] = $returnvalue;
                                    if (true) {
                                        echo_rule($env);
                                        echo "return to {$tablename}.{$fieldname} = '{$returnvalue}'\n";
                                    }
                                    $ok = db_update($tablename, array($oldrec)) && !$ERROR;
                                    //echo "RETURN $tablename $fieldname='$returnvalue' ok='$ok' ERROR='$ERROR'\n";
                                    if (!$ok) {
                                        check_answer($env, "DB_ERROR update ({$ERROR})");
                                    }
                                }
                            }
                        } else {
                            engine_error("cannot parse action '{$action}'. correct your rules!");
                        }
                    }
                }
            }
        }
    }
    if ($ok) {
        $env["HIT_FLAG"] = true;
    }
    $env["LEVEL"] = $oldlevel;
    return $ok;
}
Пример #4
0
/**
* Shortcut to running a script consisting of multiple files with run_script.
*
* @param 1 ($files)
*   Path to the script files.
*
* @param 2 ($scriptVariables)
*   Array of variables and values to be created for the script (initially).
*
* @return 
*   String content of output buffer after the script has run, false on failure.
*/
function run_scripts($files = array(), $scriptVariables = array())
{
    $queue = array();
    $first = '';
    // Normalize
    $files = array_flatten(to_array($files));
    if (count($files) >= 1) {
        $first = array_shift($files);
        $queue = $files;
    }
    return run_script($first, $scriptVariables, $queue);
}
Пример #5
0
function updateFavoriteEpisode(&$fav, $title)
{
    global $config_values;
    if (!($guess = guess_match($title, TRUE))) {
        return;
    }
    if (preg_match('/^((\\d+x)?\\d+)p$/', $guess['episode'])) {
        $guess['episode'] = preg_replace('/^((?:\\d+x)?\\d+)p$/', '\\1', $guess['episode']);
        $PROPER = "p";
    } else {
        $PROPER = '';
    }
    if (preg_match('/(^)(\\d{8})$/', $guess['episode'], $regs)) {
        $curEpisode = $regs[2];
        $expectedEpisode = $regs[2] + 1;
    } else {
        if (preg_match('/^(\\d+)x(\\d+)$/i', $guess['episode'], $regs)) {
            $curEpisode = preg_replace('/(\\d+)x/i', "", $guess['episode']);
            $curSeason = preg_replace('/x(\\d+)/i', "", $guess['episode']);
            $expectedEpisode = sprintf('%02d', $fav['Episode'] + 1);
        } else {
            return;
        }
    }
    if ($fav['Episode'] && $curEpisode > $expectedEpisode) {
        $show = $guess['key'];
        $episode = $guess['episode'];
        $expected = $curSeason . "x" . $expectedEpisode;
        $oldEpisode = $fav['Episode'];
        $oldSeason = $fav['Season'];
        $newEpisode = $curEpisode + 1;
        $newSeason = $curSeason + 1;
        $msg = "Matched \"{$show} {$episode}\" but expected \"{$expected}\".\n";
        $msg .= "This usualy means that a double episode is downloaded before this one.\n";
        $msg .= "But it could mean that you missed an episode or that \"{$episode}\" is a special episode.\n";
        $msg .= "If this is the case you need to reset the \"Last Downloaded Episode\" setting to \"{$oldSeason} x {$oldEpisode}\" in the Favorites menu.\n";
        $msg .= "If you don't, the next match wil be \"Season: {$curSeason} Episode: {$newEpisode}\" or \"Season {$newSeason} Episode: 1\".\n";
        $subject = "TorrentWatch-X: got {$show} {$episode}, expected {$expected}";
        MailNotify($msg, $subject);
        $msg = escapeshellarg($msg);
        run_script('error', $title, $msg);
    }
    if (!isset($fav['Season'], $fav['Episode']) || $regs[1] > $fav['Season']) {
        $fav['Season'] = $regs[1];
        $fav['Episode'] = $regs[2] . $PROPER;
    } else {
        if ($regs[1] == $fav['Season'] && $regs[2] > $fav['Episode']) {
            $fav['Episode'] = $regs[2] . $PROPER;
        } else {
            $fav['Episode'] .= $PROPER;
        }
    }
    write_config_file();
}
Пример #6
0
function client_add_torrent($filename, $dest, $title, $feed = NULL, &$fav = NULL, $retried = false)
{
    global $config_values, $hit, $tw_version;
    if (strtolower($fav['Filter']) == "any") {
        $any = 1;
    }
    $hit = 1;
    if (preg_match("/^magnet:/", $filename)) {
        $tor = $filename;
        $magnet = 1;
    }
    if (!$magnet) {
        $filename = htmlspecialchars_decode($filename);
        // Detect and append cookies from the feed url
        $url = $filename;
        if ($feed && preg_match('/:COOKIE:/', $feed) && !preg_match('/:COOKIE:/', $url)) {
            $url .= stristr($feed, ':COOKIE:');
        }
        $get = curl_init();
        $response = check_for_cookies($url);
        if ($response) {
            $url = $response['url'];
            $cookies = $response['cookies'];
        }
        $getOptions[CURLOPT_URL] = $url;
        if (isset($cookies)) {
            $getOptions[CURLOPT_COOKIE] = $cookies;
        }
        //$getOptions[CURLOPT_USERAGENT] = 'Python-urllib/1.17';
        $getOptions[CURLOPT_USERAGENT] = "TWX/{$tw_version['0']}";
        get_curl_defaults($getOptions);
        curl_setopt_array($get, $getOptions);
        $tor = curl_exec($get);
        curl_close($get);
        if (strncasecmp($tor, 'd8:announce', 11) != 0) {
            // Check for torrent magic-entry
            //This was not a torrent-file, so it's poroperly some kind og xml / html.
            if (!$retried) {
                //Try to retrieve a .torrent link from the content.
                $link = find_torrent_link($url, $tor);
                return client_add_torrent($link, $dest, $title, $feed, $fav, $url);
            } else {
                _debug("No torrent file found on {$url}. Exitting.\n");
                if (isset($retried)) {
                    $url = $retried;
                }
                return "Error: No torrent file found on {$url}.";
            }
        }
        if (!$tor) {
            print '<pre>' . print_r($_GET, TRUE) . '</pre>';
            _debug("Couldn't open torrent: {$filename} \n", -1);
            return "Error: Couldn't open torrent: {$filename}";
        }
    }
    $tor_info = new BDecode("", $tor);
    if (!($tor_name = $tor_info->{'result'}['info']['name'])) {
        $tor_name = $title;
    }
    if (!isset($dest)) {
        $dest = $config_values['Settings']['Download Dir'];
    }
    if (isset($fav) && $fav['Save In'] != 'Default') {
        $dest = $fav['Save In'];
    }
    $dest = get_deep_dir(preg_replace('/\\/$/', '', $dest), $tor_name);
    if (!file_exists($dest) or !is_dir($dest)) {
        $old_umask = umask(0);
        if (file_exists($dest)) {
            unlink($dest);
        }
        mkdir($dest, 0777, TRUE);
        umask($old_umask);
    }
    foreach ($config_values['Feeds'] as $key => $feedLink) {
        if ($feedLink['Link'] == "{$feed}") {
            $idx = $key;
        }
    }
    if ($config_values['Feeds'][$idx]['seedRatio'] >= 0) {
        $seedRatio = $config_values['Feeds'][$idx]['seedRatio'];
    } else {
        $seedRatio = $config_values['Settings']['Default Seed Ratio'];
    }
    if (!$seedRatio) {
        $seedRatio = -1;
    }
    switch ($config_values['Settings']['Client']) {
        case 'Transmission':
            $return = transmission_add_torrent($tor, $dest, $title, _isset($fav, '$seedRatio', $seedRatio));
            break;
        case 'folder':
            if ($magnet) {
                _debug("Can not save magnet links to a folder\n");
            } else {
                $return = folder_add_torrent($tor, $dest, $tor_name);
            }
            break;
        default:
            _debug("Invalid Torrent Client: " . $config_values['Settings']['Client'] . "\n", -1);
            exit(1);
    }
    if ($return === 0) {
        add_history($tor_name);
        _debug("Started: {$tor_name} in {$dest}\n", 0);
        if (isset($fav)) {
            run_script('favstart', $title);
            if ($config_values['Settings']['Email Notifications'] == 1) {
                $subject = "TW-X: {$tor_name} started downloading.";
                $msg = "TorrentWatch started downloading {$tor_name}";
                MailNotify($msg, $subject);
            }
            if (!$any) {
                updateFavoriteEpisode($fav, $title);
                _debug("Updated Favorites");
            }
        } else {
            run_script('nonfavstart', $title);
        }
        if ($config_values['Settings']['Save Torrents']) {
            file_put_contents("{$dest}/{$tor_name}.torrent", $tor);
        }
        return "Success";
    } else {
        _debug("Failed Starting: {$tor_name}  Error: {$return}\n", -1);
        $msg = "TorrentWatch-X tried to start \"{$tor_name}\". But this failed with the following error:\n\n";
        $msg .= "{$return}\n";
        $subject = "TW-X: Error while trying to start {$tor_name}.";
        MailNotify($msg, $subject);
        run_script('error', $title, $msg);
        return "Error: {$return}";
    }
}