Find and load sieve script with/for vacation rule

@param string $script_name Optional script name

@return int Connection status: 0 on success, >0 on failure
426151
protected function load_script($script_name = null)
    {
        if ($this->script_name !== null) {
            return 0;
        }

        $list     = $this->list_scripts();
        $master   = $this->rc->config->get('managesieve_kolab_master');
        $included = array();

        $this->script_name = false;

        // first try the active script(s)...
        if (!empty($this->active)) {
            // Note: there can be more than one active script on KEP:14-enabled server
            foreach ($this->active as $script) {
                if ($this->sieve->load($script)) {
                    foreach ($this->sieve->script->as_array() as $rule) {
                        if (!empty($rule['actions'])) {
                            if ($rule['actions'][0]['type'] == 'vacation') {
                                $this->script_name = $script;
                                return 0;
                            }
                            else if (empty($master) && $rule['actions'][0]['type'] == 'include') {
                                $included[] = $rule['actions'][0]['target'];
                            }
                        }
                    }
                }
            }

            // ...else try scripts included in active script (not for KEP:14)
            foreach ($included as $script) {
                if ($this->sieve->load($script)) {
                    foreach ($this->sieve->script->as_array() as $rule) {
                        if (!empty($rule['actions']) && $rule['actions'][0]['type'] == 'vacation') {
                            $this->script_name = $script;
                            return 0;
                        }
                    }
                }
            }
        }

        // try all other scripts
        if (!empty($list)) {
            // else try included scripts
            foreach (array_diff($list, $included, $this->active) as $script) {
                if ($this->sieve->load($script)) {
                    foreach ($this->sieve->script->as_array() as $rule) {
                        if (!empty($rule['actions']) && $rule['actions'][0]['type'] == 'vacation') {
                            $this->script_name = $script;
                            return 0;
                        }
                    }
                }
            }

            // none of the scripts contains existing vacation rule
            // use any (first) active or just existing script (in that order)
            if (!empty($this->active)) {
                $this->sieve->load($this->script_name = $this->active[0]);
            }
            else {
                $this->sieve->load($this->script_name = $list[0]);
            }
        }

        return $this->sieve->error();
    }
1310562
public static function getTable($table_name)
        {
            if (!isset(self::$tables[$table_name])) {
                self::loadNewTable(new $table_name());
            }
            if (!isset(self::$tables[$table_name])) {
                throw new Exception('Table ' . $table_name . ' is not loaded');
            }
            return self::$tables[$table_name];
        }
48483
public function get_script($name)
    {
        if (!$this->sieve)
            return $this->_set_error(self::ERROR_INTERNAL);

        $content = $this->sieve->getScript($name);

        if (is_a($content, 'PEAR_Error')) {
            return $this->_set_error(self::ERROR_OTHER);
        }

        return $content;
    }
179071
public function remove($name = null)
    {
        if (!$this->sieve) {
            return $this->_set_error(self::ERROR_INTERNAL);
        }

        if (!$name) {
            $name = $this->current;
        }

        // script must be deactivated first
        if ($name == $this->sieve->getActive()) {
            $result = $this->sieve->setActive('');

            if (is_a($result, 'PEAR_Error')) {
                return $this->_set_error(self::ERROR_DELETE);
            }

            $this->active = null;
        }

        $result = $this->sieve->removeScript($name);

        if (is_a($result, 'PEAR_Error')) {
            return $this->_set_error(self::ERROR_DELETE);
        }

        if ($name == $this->current) {
            $this->current = null;
        }

        $this->list = null;

        return true;
    }
256285
public function getCleanedFieldAsInt(string $field_name): int
    {
        if (empty($this->initial_data[$field_name])) {
            return 0;
        }

        if (!is_scalar($this->initial_data[$field_name])) {
            return 0;
        }

        return (int)$this->initial_data[$field_name];
    }
1237648
def get_script(name=None):  # noqa: E501
    

    if(not hasAccess()):
        return redirectUnauthorized()

    driver = LoadedDrivers.getDefaultBaseDriver()
    return Response(status=200, body=driver.readScript(name))
25384
protected function initialization($controller_name, $method_name)
    {
        if ($this->isRPC && !empty($this->rpc_request_id)) {
            //全链路监控保证调用的request_id唯一
            $this->context['request_id'] = $this->rpc_request_id;
        } else {
            $this->context['request_id'] = time() . crc32($controller_name . $method_name . getTickTime() . rand(1, 10000000));
        }
        $this->context['controller_name'] = $controller_name;
        $this->context['method_name'] = "$controller_name::$method_name";
        $this->context['ip'] = $this->getFdInfo()['remote_ip'];
        if (!empty($this->uid)) {
            $this->context['uid'] = $this->uid;
        }
        $this->db = $this->loader->mysql("mysqlPool",$this);
        $this->redis = $this->loader->redis("redisPool",$this);
        if ($this->isEnableError) {
            $this->Error = $this->loader->model(Error::class, $this);
        }
    }
859498
private function lazyLoad($query_name)
    {
        if (isset($this->query_handler_ids[$query_name])) {
            list($service, $method) = $this->query_handler_ids[$query_name];

            return $this->resolve($this->container->get($service), $method);
        }

        return null;
    }
1178541
public function loadFile($file_name, $dir_name = null)
    {
        try {
            $loader = $this->getLoader();
            $file_path = $loader->findLanguageDBFile(
                !empty($file_name) ? basename($file_name) : $file_name,
                !empty($dir_name) ? $dir_name : (
                    !empty($file_name) ? dirname($file_name) : $dir_name
                )
            );
            if ($file_path && file_exists($file_path)) {
                $loader
                    ->setOption('language_strings_db_directory', dirname($file_path))
                    ->setOption('language_strings_db_filename', basename($file_path))
                ;

                $this->_loadLanguageStrings(true, true, true);
            } else {
                throw new I18nInvalidArgumentException(
                    sprintf('Language file "%s" not found!', $file_name)
                );
            }
        } catch (I18nException $e) {
            throw $e;
        }
    }
103137
protected function waitForMySQLDatabaseByName($database_name)
    {
        return $this->retry(50, function () use ($database_name) {
            $this->databases = $this->fetchMySQLDatabases();
            $database = $this->getMysqlDatabaseByName($this->databases, $database_name);
            return $database['status'] == 'installed' ? $database : null;
        });
    }
886432
def get_executable_info
      if not (@servers.empty? )
        if (@script != nil)
          # If script is an uri/url no need to "detect it"
          # https://my.rightscale.com/acct/9202/right_scripts/205347
          if @script =~ /\A#{URI::regexp}\z/
            if not @use_chimpd || !@prompt
              puts "=================================================="
              puts "WARNING! You will be running this script on all "
              puts "server matches! (Press enter to continue)"
              puts "=================================================="
              gets
            end

            script_number = File.basename(@script)

            s = Executable.new
            s.delay = @delay

            s.params['right_script']['href']="right_script_href=/api/right_scripts/"+script_number
            #Make an 1.5 call to extract name, by loading resource.
            Log.debug "[#{Chimp.get_job_uuid}] Making API 1.5 call : client.resource(#{s.params['right_script']['href'].scan(/=(.*)/).last.last})"
            begin
              tries ||= 3
              the_name = Connection.client.resource(s.params['right_script']['href'].scan(/=(.*)/).last.last).name
            rescue
              Log.error "[#{Chimp.get_job_uuid}] Failed to make 1.5 call for rightscript href (retrying)"
              sleep 30
              retry unless (tries -= 1).zero?
              Log.error "[#{Chimp.get_job_uuid}] Failed to make 1.5 call for rightscript href (giving up)"
            end
            s.params['right_script']['name'] = the_name
            @executable = s
          else
            # If its not an url, go ahead try to locate it in the ST"
            @executable = detect_right_script(@server_template, @script)
          end
        else
          # @script could be nil because we want to run ssh
          if @action == :action_ssh
            puts "Using SSH command: \"#{@ssh}\"" if @action == :action_ssh
          end
        end
      end
    end
1333204
public static function getCommandRunningCount($name)
    {
        exec(sprintf("ps auxwww|grep '%s'|grep -v grep", $name), $output);

        if (false === is_array($output)) {
            return 1;
        }

        /*
         * Remove Crontab sh calls
         */
        foreach ($output as $lineIndex => $line) {
            if (false !== strpos($line, '/bin/sh -c')) {
                unset($output[$lineIndex]);
            }
        }

        return count($output);
    }
1098402
public static function create($name, $script)
    {
        $object = get_class(self::$driver);
        //
        return $object::create($name, $script);
    }
327534
private function findScript(string $scriptFilename): string
    {
        // @todo Make this a setting in config instead. This module shouldn't make assumptions on where it's installed
        $conductorRoot = realpath(__DIR__ . '/../../../../..');
        $configRoot = "$conductorRoot/config/app";
        $environment = $this->applicationConfig->getCurrentEnvironment();

        $environmentPath = "$configRoot/environments/$environment/files";
        if (file_exists("$environmentPath/$scriptFilename")) {
            return "$environmentPath/$scriptFilename";
        }

        $globalPath = "$configRoot/files";
        if (file_exists("$globalPath/$scriptFilename")) {
            return "$globalPath/$scriptFilename";
        }

        throw new Exception\RuntimeException(
            "Script \"$scriptFilename\" not found in \"$environmentPath\" or \"$globalPath\"."
        );
    }
974469
public function get_scripts()
    {
        if (!$this->list) {

            if (!$this->sieve)
                return $this->_set_error(self::ERROR_INTERNAL);

            $list = $this->sieve->listScripts($active);

            if (is_a($list, 'PEAR_Error')) {
                return $this->_set_error(self::ERROR_OTHER);
            }

            $this->list   = $list;
            $this->active = $active;
        }

        return $this->list;
    }
437476
public function fetchByName($str_key_name)
    {
        $arr_results = $this->fetchByNames([$str_key_name]);
        if(count($arr_results) > 0) {
            return $arr_results[0];
        }
        return null;
    }
518008
public Script getScriptSig() throws ScriptException {
        // Transactions that generate new coins don't actually have a script. Instead this
        // parameter is overloaded to be something totally different.
        Script script = scriptSig == null ? null : scriptSig.get();
        if (script == null) {
            script = new Script(scriptBytes);
            scriptSig = new WeakReference<>(script);
        }
        return script;
    }