Return the contents of the user's crontab

    CLI Example:

    .. code-block:: bash

        salt '*' cron.raw_cron root
351357
def raw_cron(user):
    '''
    
    '''
    if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
        cmd = 'crontab -l'
        # Preserve line endings
        lines = salt.utils.data.decode(
            __salt__['cmd.run_stdout'](cmd,
                                       runas=user,
                                       ignore_retcode=True,
                                       rstrip=False,
                                       python_shell=False)
        ).splitlines(True)
    else:
        cmd = 'crontab -u {0} -l'.format(user)
        # Preserve line endings
        lines = salt.utils.data.decode(
            __salt__['cmd.run_stdout'](cmd,
                                       ignore_retcode=True,
                                       rstrip=False,
                                       python_shell=False)
        ).splitlines(True)

    if lines and lines[0].startswith('# DO NOT EDIT THIS FILE - edit the master and reinstall.'):
        del lines[0:3]
    return ''.join(lines)
1109664
def cron(schedule, timezone: nil)
            ms = Scheduler.parse_cron(schedule, timezone: timezone)
            event = Repeat.new(self, ms)
            event.progress &Proc.new if block_given?
            schedule(event)
            event
        end
28537
private static CronDefinition unixCrontab() {
        return CronDefinitionBuilder.defineCron()
                .withMinutes().and()
                .withHours().and()
                .withDayOfMonth().and()
                .withMonth().and()
                .withDayOfWeek().withValidRange(0, 7).withMondayDoWValue(1).withIntMapping(7, 0).and()
                .enforceStrictRanges()
                .instance();
    }
1080181
public function cron() {
        global $CFG;

        // Get configs.
        $imsfilelocation = $this->get_config('imsfilelocation');
        $logtolocation = $this->get_config('logtolocation');
        $mailadmins = $this->get_config('mailadmins');
        $prevtime = $this->get_config('prev_time');
        $prevmd5 = $this->get_config('prev_md5');
        $prevpath = $this->get_config('prev_path');

        if (empty($imsfilelocation)) {
            $filename = "$CFG->dataroot/1/imsenterprise-enrol.xml";  // Default location.
        } else {
            $filename = $imsfilelocation;
        }

        $this->logfp = false;
        if (!empty($logtolocation)) {
            $this->logfp = fopen($logtolocation, 'a');
        }

        $this->defaultcategoryid = null;

        $fileisnew = false;
        if ( file_exists($filename) ) {
            core_php_time_limit::raise();
            $starttime = time();

            $this->log_line('----------------------------------------------------------------------');
            $this->log_line("IMS Enterprise enrol cron process launched at " . userdate(time()));
            $this->log_line('Found file '.$filename);
            $this->xmlcache = '';

            $categoryseparator = trim($this->get_config('categoryseparator'));
            $categoryidnumber = $this->get_config('categoryidnumber');

            // Make sure we understand how to map the IMS-E roles to Moodle roles.
            $this->load_role_mappings();
            // Make sure we understand how to map the IMS-E course names to Moodle course names.
            $this->load_course_mappings();

            $md5 = md5_file($filename); // NB We'll write this value back to the database at the end of the cron.
            $filemtime = filemtime($filename);

            // Decide if we want to process the file (based on filepath, modification time, and MD5 hash)
            // This is so we avoid wasting the server's efforts processing a file unnecessarily.
            if ($categoryidnumber && empty($categoryseparator)) {
                $this->log_line('Category idnumber is enabled but category separator is not defined - skipping processing.');
            } else if (empty($prevpath)  || ($filename != $prevpath)) {
                $fileisnew = true;
            } else if (isset($prevtime) && ($filemtime <= $prevtime)) {
                $this->log_line('File modification time is not more recent than last update - skipping processing.');
            } else if (isset($prevmd5) && ($md5 == $prevmd5)) {
                $this->log_line('File MD5 hash is same as on last update - skipping processing.');
            } else {
                $fileisnew = true; // Let's process it!
            }

            if ($fileisnew) {

                // The <properties> tag is allowed to halt processing if we're demanding a matching target.
                $this->continueprocessing = true;

                // Run through the file and process the group/person entries.
                if (($fh = fopen($filename, "r")) != false) {

                    $line = 0;
                    while ((!feof($fh)) && $this->continueprocessing) {

                        $line++;
                        $curline = fgets($fh);
                        $this->xmlcache .= $curline; // Add a line onto the XML cache.

                        while (true) {
                            // If we've got a full tag (i.e. the most recent line has closed the tag) then process-it-and-forget-it.
                            // Must always make sure to remove tags from cache so they don't clog up our memory.
                            if ($tagcontents = $this->full_tag_found_in_cache('group', $curline)) {
                                $this->process_group_tag($tagcontents);
                                $this->remove_tag_from_cache('group');
                            } else if ($tagcontents = $this->full_tag_found_in_cache('person', $curline)) {
                                $this->process_person_tag($tagcontents);
                                $this->remove_tag_from_cache('person');
                            } else if ($tagcontents = $this->full_tag_found_in_cache('membership', $curline)) {
                                $this->process_membership_tag($tagcontents);
                                $this->remove_tag_from_cache('membership');
                            } else if ($tagcontents = $this->full_tag_found_in_cache('comments', $curline)) {
                                $this->remove_tag_from_cache('comments');
                            } else if ($tagcontents = $this->full_tag_found_in_cache('properties', $curline)) {
                                $this->process_properties_tag($tagcontents);
                                $this->remove_tag_from_cache('properties');
                            } else {
                                break;
                            }
                        }
                    }
                    fclose($fh);
                    fix_course_sortorder();
                }

                $timeelapsed = time() - $starttime;
                $this->log_line('Process has completed. Time taken: '.$timeelapsed.' seconds.');

            }

            // These variables are stored so we can compare them against the IMS file, next time round.
            $this->set_config('prev_time', $filemtime);
            $this->set_config('prev_md5',  $md5);
            $this->set_config('prev_path', $filename);

        } else {
            $this->log_line('File not found: '.$filename);
        }

        if (!empty($mailadmins) && $fileisnew) {
            $timeelapsed = isset($timeelapsed) ? $timeelapsed : 0;
            $msg = "An IMS enrolment has been carried out within Moodle.\nTime taken: $timeelapsed seconds.\n\n";
            if (!empty($logtolocation)) {
                if ($this->logfp) {
                    $msg .= "Log data has been written to:\n";
                    $msg .= "$logtolocation\n";
                    $msg .= "(Log file size: ".ceil(filesize($logtolocation) / 1024)."Kb)\n\n";
                } else {
                    $msg .= "The log file appears not to have been successfully written.\n";
                    $msg .= "Check that the file is writeable by the server:\n";
                    $msg .= "$logtolocation\n\n";
                }
            } else {
                $msg .= "Logging is currently not active.";
            }

            $eventdata = new \core\message\message();
            $eventdata->courseid          = SITEID;
            $eventdata->modulename        = 'moodle';
            $eventdata->component         = 'enrol_imsenterprise';
            $eventdata->name              = 'imsenterprise_enrolment';
            $eventdata->userfrom          = get_admin();
            $eventdata->userto            = get_admin();
            $eventdata->subject           = "Moodle IMS Enterprise enrolment notification";
            $eventdata->fullmessage       = $msg;
            $eventdata->fullmessageformat = FORMAT_PLAIN;
            $eventdata->fullmessagehtml   = '';
            $eventdata->smallmessage      = '';
            message_send($eventdata);

            $this->log_line('Notification email sent to administrator.');

        }

        if ($this->logfp) {
            fclose($this->logfp);
        }

    }
420197
private function writeCronFile()
    {
        if (empty($this->cronFile)) {
            return false;
        }

        if (!is_file($this->cronFile)) {
            return false;
        }

        if (!is_writable($this->cronFile)) {
            return false;
        }

        return file_put_contents($this->cronFile, $this->generateCron());
    }
877241
function () {
        const crons = _.get(Shared, 'runtimeArgs.cron') || _.get(Shared, 'runtimeArgs.crons');
        if (crons) {
            const cronTasks = crons.replace(/\s/g, '').split(',');
            return cronTasks.length > 0 ? cronTasks : undefined;
        }
        return undefined;
    }
1144687
def fetch(**kwargs):
    '''
    
    '''
    # fetch continues when no controlling terminal is present
    pre = ''
    post = ''
    run_args = {}
    if float(__grains__['osrelease']) >= 10.2:
        post += '--not-running-from-cron'
    else:
        pre += ' env PAGER=cat'
        run_args['python_shell'] = True
    return _wrapper('fetch', pre=pre, post=post, run_args=run_args, **kwargs)
819781
def _check_cron(user,
                cmd,
                minute=None,
                hour=None,
                daymonth=None,
                month=None,
                dayweek=None,
                comment=None,
                commented=None,
                identifier=None,
                special=None):
    '''
    
    '''
    if minute is not None:
        minute = six.text_type(minute).lower()
    if hour is not None:
        hour = six.text_type(hour).lower()
    if daymonth is not None:
        daymonth = six.text_type(daymonth).lower()
    if month is not None:
        month = six.text_type(month).lower()
    if dayweek is not None:
        dayweek = six.text_type(dayweek).lower()
    if identifier is not None:
        identifier = six.text_type(identifier)
    if commented is not None:
        commented = commented is True
    if cmd is not None:
        cmd = six.text_type(cmd)
    lst = __salt__['cron.list_tab'](user)
    if special is None:
        for cron in lst['crons']:
            if _cron_matched(cron, cmd, identifier):
                if any([_needs_change(x, y) for x, y in
                        ((cron['minute'], minute), (cron['hour'], hour),
                         (cron['daymonth'], daymonth), (cron['month'], month),
                         (cron['dayweek'], dayweek), (cron['identifier'], identifier),
                         (cron['cmd'], cmd), (cron['comment'], comment),
                         (cron['commented'], commented))]):
                    return 'update'
                return 'present'
    else:
        for cron in lst['special']:
            if _cron_matched(cron, cmd, identifier):
                if any([_needs_change(x, y) for x, y in
                        ((cron['spec'], special),
                         (cron['identifier'], identifier),
                         (cron['cmd'], cmd),
                         (cron['comment'], comment),
                         (cron['commented'], commented))]):
                    return 'update'
                return 'present'
    return 'absent'
1117002
def rm_env(user, name):
    '''
    
    '''
    lst = list_tab(user)
    ret = 'absent'
    rm_ = None
    for ind in range(len(lst['env'])):
        if name == lst['env'][ind]['name']:
            rm_ = ind
    if rm_ is not None:
        lst['env'].pop(rm_)
        ret = 'removed'
    comdat = _write_cron_lines(user, _render_tab(lst))
    if comdat['retcode']:
        # Failed to commit, return the error
        return comdat['stderr']
    return ret
621437
public function index()
    {
        //  Command line only
        $oInput = Factory::service('Input');
        if (Environment::is(Environment::ENV_PROD) && !$oInput::isCli()) {
            header($oInput->server('SERVER_PROTOCOL') . ' 401 Unauthorized');
            echo '<h1>' . lang('unauthorised') . '</h1>';
            exit(401);
        }

        // --------------------------------------------------------------------------

        /**
         * Look for a controller, app version first then the module's cron controllers directory
         */
        $aControllerPaths = [
            NAILS_APP_PATH . 'application/modules/cron/controllers/',
        ];

        $nailsModules = Components::modules();

        foreach ($nailsModules as $oModule) {

            if ($oModule->moduleName === $this->sModuleName) {
                $aControllerPaths[] = $oModule->path . 'cron/controllers/';
                break;
            }
        }

        //  Look for a valid controller
        $sControllerName    = ucfirst($this->sClassName) . '.php';
        $bDidfindController = false;

        foreach ($aControllerPaths as $sPath) {

            $sControllerPath = $sPath . $sControllerName;

            if (is_file($sControllerPath)) {
                $bDidfindController = true;
                break;
            }
        }

        if (!empty($bDidfindController)) {

            //  Load the file and try and execute the method
            require_once $sControllerPath;

            $this->sModuleName = 'Nails\\Cron\\' . ucfirst($this->sModuleName) . '\\' . ucfirst($this->sClassName);

            if (class_exists($this->sModuleName)) {

                //  New instance of the controller
                $oInstance = new $this->sModuleName($this);

                if (is_callable([$oInstance, $this->sMethod])) {

                    //  Begin timing
                    $this->writeLog('Starting job');

                    if (!empty($this->aParams)) {

                        $this->writeLog('Passed parameters');
                        $this->writeLog(print_r($this->aParams, true));
                    }

                    $iStart = microtime(true) * 10000;

                    call_user_func_array([$oInstance, $this->sMethod], $this->aParams);

                    $iEnd      = microtime(true) * 10000;
                    $iDuration = ($iEnd - $iStart) / 10000;
                    $this->writeLog('Finished job');
                    $this->writeLog('Job took ' . number_format($iDuration, 5) . ' seconds');

                } else {

                    $this->writeLog('Cannot call method "' . $this->sMethod . '"');
                }

            } else {

                $this->writeLog(
                    '"' . $this->sModuleName . '" is incorrectly configured; could not find class ' . $this->sModuleName . '  at path ' . $sControllerPath
                );
            }

        } else {

            $this->writeLog(
                '"' . $this->sModuleName . '/' . $this->sClassName . '/' . $this->sMethod . '" is not a valid route.'
            );
        }
    }
862952
def setup(cls, cron_cfg="cron"):
        
        random.seed()
        logging_cfg = cls.LOGGING_CFG
        if "%s" in logging_cfg:
            logging_cfg = logging_cfg % (cron_cfg if "--cron" in sys.argv[1:] else "scripts",)
        logging_cfg = os.path.expanduser(logging_cfg)

        if os.path.exists(logging_cfg):
            logging.HERE = os.path.dirname(logging_cfg)
            logging.config.fileConfig(logging_cfg)
        else:
            logging.basicConfig(level=logging.INFO)

        logging.getLogger().debug("Logging config read from '%s'" % logging_cfg)
321904
def _make_matchers(self, crontab):
        '''
        
        '''
        crontab = _aliases.get(crontab, crontab)
        ct = crontab.split()
        if len(ct) == 5:
            ct.insert(0, '0')
            ct.append('*')
        elif len(ct) == 6:
            ct.insert(0, '0')
        _assert(len(ct) == 7,
            "improper number of cron entries specified; got %i need 5 to 7"%(len(ct,)))

        matchers = [_Matcher(which, entry) for which, entry in enumerate(ct)]

        return Matcher(*matchers)
555467
def activate_crontab(self):
        
        self._crontab = []
        if hasattr(self, 'CRONTAB'):
            for crontab_spec in self.CRONTAB:
                args = cronjob.parse_crontab(crontab_spec)
                job = cronjob.CronJob()
                if args['_timer'] == 'datetime':
                    job.set_triggers(args['trigger_format'], args['trigger_time'])
                if args['_timer'] == 'crontab':
                    job.set_crontab(args['crontab'])
                if args['action'].startswith('.'):
                    action_name = args['action'][1:]
                    action_ = getattr(self.__class__, action_name)
                else:
                    action_ = args['action']
                job.set_action(action_, *args['args'])
                self._crontab.append(job)
        self.start_poller(30, self.poll_crontab)
943876
def _login(server, creds_file=None, api_key=None, silent=False):
    
    # fetch_api_key and check_version expect server to end in /
    if server[-1] != "/":
        server = server + "/"

    # creds file path setup
    if creds_file is None:
        creds_file = os.path.expanduser("~/.onecodex")

    # check if the creds file exists and is readable
    if not os.path.exists(creds_file):
        if silent:
            return None

        creds = {}
    elif not os.access(creds_file, os.R_OK):
        click.echo("Please check the permissions on {}".format(collapse_user(creds_file)), err=True)
        sys.exit(1)
    else:
        # it is, so let's read it!
        with open(creds_file, "r") as fp:
            try:
                creds = json.load(fp)
            except ValueError:
                click.echo(
                    "Your ~/.onecodex credentials file appears to be corrupted. "  # noqa
                    "Please delete it and re-authorize.",
                    err=True,
                )
                sys.exit(1)

        # check for updates if logged in more than one day ago
        last_update = creds.get("updated_at") or creds.get("saved_at")
        last_update = last_update if last_update else datetime.datetime.now().strftime(DATE_FORMAT)
        diff = datetime.datetime.now() - datetime.datetime.strptime(last_update, DATE_FORMAT)

        if diff.days >= 1:
            # if creds_file is old, check for updates
            upgrade_required, msg = check_version(__version__, server)
            creds["updated_at"] = datetime.datetime.now().strftime(DATE_FORMAT)

            try:
                json.dump(creds, open(creds_file, "w"))
            except Exception as e:
                if e.errno == errno.EACCES:
                    click.echo(
                        "Please check the permissions on {}".format(collapse_user(creds_file)),
                        err=True,
                    )
                    sys.exit(1)
                else:
                    raise

            if upgrade_required:
                click.echo("\nWARNING: {}\n".format(msg), err=True)

        # finally, give the user back what they want (whether silent or not)
        if silent:
            return creds.get("api_key", None)

        click.echo(
            "Credentials file already exists ({}). Logout first.".format(collapse_user(creds_file)),
            err=True,
        )
        return creds.get("email", None)

    # creds_file was not found and we're not silent, so prompt user to login
    email, api_key = login_uname_pwd(server, api_key=api_key)

    if api_key is None:
        click.echo(
            "We could not verify your credentials. Either you mistyped your email "
            "or password, or your account does not currently have API access. "
            "Please contact help@onecodex.com if you continue to experience problems."
        )
        sys.exit(1)

    creds.update(
        {
            "api_key": api_key,
            "saved_at": datetime.datetime.now().strftime(DATE_FORMAT),
            "updated_at": None,
            "email": email,
        }
    )

    try:
        json.dump(creds, open(creds_file, "w"))
    except Exception as e:
        if e.errno == errno.EACCES:
            click.echo("Please check the permissions on {}".format(creds_file), err=True)
            sys.exit(1)
        else:
            raise

    click.echo("Your ~/.onecodex credentials file was successfully created.", err=True)

    return email
847467
public function reload_if_dirty() {
        global $ACCESSLIB_PRIVATE, $USER;

        // Load dirty contexts list if needed
        if (CLI_SCRIPT) {
            if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
                // we do not load dirty flags in CLI and cron
                $ACCESSLIB_PRIVATE->dirtycontexts = array();
            }
        } else {
            if (!isset($USER->access['time'])) {
                // Nothing has been loaded yet, so we do not need to check dirty flags now.
                return;
            }

            // From skodak: No idea why -2 is there, server cluster time difference maybe...
            $changedsince = $USER->access['time'] - 2;

            if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
                $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $changedsince);
            }

            if (!isset($ACCESSLIB_PRIVATE->dirtyusers[$USER->id])) {
                $ACCESSLIB_PRIVATE->dirtyusers[$USER->id] = get_cache_flag('accesslib/dirtyusers', $USER->id, $changedsince);
            }
        }

        $dirty = false;

        if (!empty($ACCESSLIB_PRIVATE->dirtyusers[$USER->id])) {
            $dirty = true;
        } else if (!empty($ACCESSLIB_PRIVATE->dirtycontexts)) {
            $paths = $this->get_parent_context_paths(true);

            foreach ($paths as $path) {
                if (isset($ACCESSLIB_PRIVATE->dirtycontexts[$path])) {
                    $dirty = true;
                    break;
                }
            }
        }

        if ($dirty) {
            // Reload all capabilities of USER and others - preserving loginas, roleswitches, etc.
            // Then cleanup any marks of dirtyness... at least from our short term memory!
            reload_all_capabilities();
        }
    }
243325
def ReadCronJobRun(self, job_id, run_id, cursor=None):
    """"""
    query = ("SELECT run, UNIX_TIMESTAMP(write_time) FROM cron_job_runs "
             "WHERE job_id = %s AND run_id = %s")
    num_runs = cursor.execute(
        query, [job_id, db_utils.CronJobRunIDToInt(run_id)])
    if num_runs == 0:
      raise db.UnknownCronJobRunError(
          "Run with job id %s and run id %s not found." % (job_id, run_id))

    return self._CronJobRunFromRow(cursor.fetchall()[0])
320167
def determine_check_cron_time(check)
      cron_parser = CronParser.new(check[:cron])
      current_time = Time.now
      next_cron_time = cron_parser.next(current_time)
      next_cron_time - current_time
    end