Passed
Push — master ( f66003...c58f8d )
by Joas
14:36 queued 13s
created
apps/files_sharing/lib/ExpireSharesJob.php 1 patch
Indentation   +55 added lines, -55 removed lines patch added patch discarded remove patch
@@ -37,71 +37,71 @@
 block discarded – undo
37 37
  */
38 38
 class ExpireSharesJob extends TimedJob {
39 39
 
40
-	/** @var IManager */
41
-	private $shareManager;
40
+    /** @var IManager */
41
+    private $shareManager;
42 42
 
43
-	/** @var IDBConnection */
44
-	private $db;
43
+    /** @var IDBConnection */
44
+    private $db;
45 45
 
46
-	public function __construct(ITimeFactory $time, IManager $shareManager, IDBConnection $db) {
47
-		$this->shareManager = $shareManager;
48
-		$this->db = $db;
46
+    public function __construct(ITimeFactory $time, IManager $shareManager, IDBConnection $db) {
47
+        $this->shareManager = $shareManager;
48
+        $this->db = $db;
49 49
 
50
-		parent::__construct($time);
50
+        parent::__construct($time);
51 51
 
52
-		// Run once a day
53
-		$this->setInterval(24 * 60 * 60);
54
-		$this->setTimeSensitivity(IJob::TIME_INSENSITIVE);
55
-	}
52
+        // Run once a day
53
+        $this->setInterval(24 * 60 * 60);
54
+        $this->setTimeSensitivity(IJob::TIME_INSENSITIVE);
55
+    }
56 56
 
57 57
 
58
-	/**
59
-	 * Makes the background job do its work
60
-	 *
61
-	 * @param array $argument unused argument
62
-	 */
63
-	public function run($argument) {
64
-		//Current time
65
-		$now = new \DateTime();
66
-		$now = $now->format('Y-m-d H:i:s');
58
+    /**
59
+     * Makes the background job do its work
60
+     *
61
+     * @param array $argument unused argument
62
+     */
63
+    public function run($argument) {
64
+        //Current time
65
+        $now = new \DateTime();
66
+        $now = $now->format('Y-m-d H:i:s');
67 67
 
68
-		/*
68
+        /*
69 69
 		 * Expire file link shares only (for now)
70 70
 		 */
71
-		$qb = $this->db->getQueryBuilder();
72
-		$qb->select('id', 'share_type')
73
-			->from('share')
74
-			->where(
75
-				$qb->expr()->andX(
76
-					$qb->expr()->orX(
77
-						$qb->expr()->eq('share_type', $qb->expr()->literal(IShare::TYPE_LINK)),
78
-						$qb->expr()->eq('share_type', $qb->expr()->literal(IShare::TYPE_EMAIL))
79
-					),
80
-					$qb->expr()->lte('expiration', $qb->expr()->literal($now)),
81
-					$qb->expr()->orX(
82
-						$qb->expr()->eq('item_type', $qb->expr()->literal('file')),
83
-						$qb->expr()->eq('item_type', $qb->expr()->literal('folder'))
84
-					)
85
-				)
86
-			);
71
+        $qb = $this->db->getQueryBuilder();
72
+        $qb->select('id', 'share_type')
73
+            ->from('share')
74
+            ->where(
75
+                $qb->expr()->andX(
76
+                    $qb->expr()->orX(
77
+                        $qb->expr()->eq('share_type', $qb->expr()->literal(IShare::TYPE_LINK)),
78
+                        $qb->expr()->eq('share_type', $qb->expr()->literal(IShare::TYPE_EMAIL))
79
+                    ),
80
+                    $qb->expr()->lte('expiration', $qb->expr()->literal($now)),
81
+                    $qb->expr()->orX(
82
+                        $qb->expr()->eq('item_type', $qb->expr()->literal('file')),
83
+                        $qb->expr()->eq('item_type', $qb->expr()->literal('folder'))
84
+                    )
85
+                )
86
+            );
87 87
 
88
-		$shares = $qb->execute();
89
-		while ($share = $shares->fetch()) {
90
-			if ((int)$share['share_type'] === IShare::TYPE_LINK) {
91
-				$id = 'ocinternal';
92
-			} elseif ((int)$share['share_type'] === IShare::TYPE_EMAIL) {
93
-				$id = 'ocMailShare';
94
-			}
88
+        $shares = $qb->execute();
89
+        while ($share = $shares->fetch()) {
90
+            if ((int)$share['share_type'] === IShare::TYPE_LINK) {
91
+                $id = 'ocinternal';
92
+            } elseif ((int)$share['share_type'] === IShare::TYPE_EMAIL) {
93
+                $id = 'ocMailShare';
94
+            }
95 95
 
96
-			$id .= ':' . $share['id'];
96
+            $id .= ':' . $share['id'];
97 97
 
98
-			try {
99
-				$share = $this->shareManager->getShareById($id);
100
-				$this->shareManager->deleteShare($share);
101
-			} catch (ShareNotFound $e) {
102
-				// Normally the share gets automatically expired on fetching it
103
-			}
104
-		}
105
-		$shares->closeCursor();
106
-	}
98
+            try {
99
+                $share = $this->shareManager->getShareById($id);
100
+                $this->shareManager->deleteShare($share);
101
+            } catch (ShareNotFound $e) {
102
+                // Normally the share gets automatically expired on fetching it
103
+            }
104
+        }
105
+        $shares->closeCursor();
106
+    }
107 107
 }
Please login to merge, or discard this patch.
apps/dav/lib/BackgroundJob/UploadCleanup.php 1 patch
Indentation   +39 added lines, -39 removed lines patch added patch discarded remove patch
@@ -39,53 +39,53 @@
 block discarded – undo
39 39
 
40 40
 class UploadCleanup extends TimedJob {
41 41
 
42
-	/** @var IRootFolder */
43
-	private $rootFolder;
42
+    /** @var IRootFolder */
43
+    private $rootFolder;
44 44
 
45
-	/** @var IJobList */
46
-	private $jobList;
45
+    /** @var IJobList */
46
+    private $jobList;
47 47
 
48
-	public function __construct(ITimeFactory $time, IRootFolder $rootFolder, IJobList $jobList) {
49
-		parent::__construct($time);
50
-		$this->rootFolder = $rootFolder;
51
-		$this->jobList = $jobList;
48
+    public function __construct(ITimeFactory $time, IRootFolder $rootFolder, IJobList $jobList) {
49
+        parent::__construct($time);
50
+        $this->rootFolder = $rootFolder;
51
+        $this->jobList = $jobList;
52 52
 
53
-		// Run once a day
54
-		$this->setInterval(60 * 60 * 24);
55
-		$this->setTimeSensitivity(IJob::TIME_INSENSITIVE);
56
-	}
53
+        // Run once a day
54
+        $this->setInterval(60 * 60 * 24);
55
+        $this->setTimeSensitivity(IJob::TIME_INSENSITIVE);
56
+    }
57 57
 
58
-	protected function run($argument) {
59
-		$uid = $argument['uid'];
60
-		$folder = $argument['folder'];
58
+    protected function run($argument) {
59
+        $uid = $argument['uid'];
60
+        $folder = $argument['folder'];
61 61
 
62
-		try {
63
-			$userFolder = $this->rootFolder->getUserFolder($uid);
64
-			$userRoot = $userFolder->getParent();
65
-			/** @var Folder $uploads */
66
-			$uploads = $userRoot->get('uploads');
67
-			/** @var Folder $uploadFolder */
68
-			$uploadFolder = $uploads->get($folder);
69
-		} catch (NotFoundException | NoUserException $e) {
70
-			$this->jobList->remove(self::class, $argument);
71
-			return;
72
-		}
62
+        try {
63
+            $userFolder = $this->rootFolder->getUserFolder($uid);
64
+            $userRoot = $userFolder->getParent();
65
+            /** @var Folder $uploads */
66
+            $uploads = $userRoot->get('uploads');
67
+            /** @var Folder $uploadFolder */
68
+            $uploadFolder = $uploads->get($folder);
69
+        } catch (NotFoundException | NoUserException $e) {
70
+            $this->jobList->remove(self::class, $argument);
71
+            return;
72
+        }
73 73
 
74
-		$files = $uploadFolder->getDirectoryListing();
74
+        $files = $uploadFolder->getDirectoryListing();
75 75
 
76
-		// Remove if all files have an mtime of more than a day
77
-		$time = $this->time->getTime() - 60 * 60 * 24;
76
+        // Remove if all files have an mtime of more than a day
77
+        $time = $this->time->getTime() - 60 * 60 * 24;
78 78
 
79
-		// The folder has to be more than a day old
80
-		$initial = $uploadFolder->getMTime() < $time;
79
+        // The folder has to be more than a day old
80
+        $initial = $uploadFolder->getMTime() < $time;
81 81
 
82
-		$expire = array_reduce($files, function (bool $carry, File $file) use ($time) {
83
-			return $carry && $file->getMTime() < $time;
84
-		}, $initial);
82
+        $expire = array_reduce($files, function (bool $carry, File $file) use ($time) {
83
+            return $carry && $file->getMTime() < $time;
84
+        }, $initial);
85 85
 
86
-		if ($expire) {
87
-			$uploadFolder->delete();
88
-			$this->jobList->remove(self::class, $argument);
89
-		}
90
-	}
86
+        if ($expire) {
87
+            $uploadFolder->delete();
88
+            $this->jobList->remove(self::class, $argument);
89
+        }
90
+    }
91 91
 }
Please login to merge, or discard this patch.
apps/files_external/lib/BackgroundJob/CredentialsCleanup.php 1 patch
Indentation   +28 added lines, -28 removed lines patch added patch discarded remove patch
@@ -36,38 +36,38 @@
 block discarded – undo
36 36
 use OCP\IUserManager;
37 37
 
38 38
 class CredentialsCleanup extends TimedJob {
39
-	private $credentialsManager;
40
-	private $userGlobalStoragesService;
41
-	private $userManager;
39
+    private $credentialsManager;
40
+    private $userGlobalStoragesService;
41
+    private $userManager;
42 42
 
43
-	public function __construct(
44
-		ITimeFactory $time,
45
-		ICredentialsManager $credentialsManager,
46
-		UserGlobalStoragesService $userGlobalStoragesService,
47
-		IUserManager $userManager
48
-	) {
49
-		parent::__construct($time);
43
+    public function __construct(
44
+        ITimeFactory $time,
45
+        ICredentialsManager $credentialsManager,
46
+        UserGlobalStoragesService $userGlobalStoragesService,
47
+        IUserManager $userManager
48
+    ) {
49
+        parent::__construct($time);
50 50
 
51
-		$this->credentialsManager = $credentialsManager;
52
-		$this->userGlobalStoragesService = $userGlobalStoragesService;
53
-		$this->userManager = $userManager;
51
+        $this->credentialsManager = $credentialsManager;
52
+        $this->userGlobalStoragesService = $userGlobalStoragesService;
53
+        $this->userManager = $userManager;
54 54
 
55
-		// run every day
56
-		$this->setInterval(24 * 60 * 60);
57
-		$this->setTimeSensitivity(IJob::TIME_INSENSITIVE);
58
-	}
55
+        // run every day
56
+        $this->setInterval(24 * 60 * 60);
57
+        $this->setTimeSensitivity(IJob::TIME_INSENSITIVE);
58
+    }
59 59
 
60
-	protected function run($argument) {
61
-		$this->userManager->callForSeenUsers(function (IUser $user) {
62
-			$storages = $this->userGlobalStoragesService->getAllStoragesForUser($user);
60
+    protected function run($argument) {
61
+        $this->userManager->callForSeenUsers(function (IUser $user) {
62
+            $storages = $this->userGlobalStoragesService->getAllStoragesForUser($user);
63 63
 
64
-			$usesLoginCredentials = array_reduce($storages, function (bool $uses, StorageConfig $storage) {
65
-				return $uses || $storage->getAuthMechanism() instanceof LoginCredentials;
66
-			}, false);
64
+            $usesLoginCredentials = array_reduce($storages, function (bool $uses, StorageConfig $storage) {
65
+                return $uses || $storage->getAuthMechanism() instanceof LoginCredentials;
66
+            }, false);
67 67
 
68
-			if (!$usesLoginCredentials) {
69
-				$this->credentialsManager->delete($user->getUID(), LoginCredentials::CREDENTIALS_IDENTIFIER);
70
-			}
71
-		});
72
-	}
68
+            if (!$usesLoginCredentials) {
69
+                $this->credentialsManager->delete($user->getUID(), LoginCredentials::CREDENTIALS_IDENTIFIER);
70
+            }
71
+        });
72
+    }
73 73
 }
Please login to merge, or discard this patch.
apps/twofactor_backupcodes/lib/BackgroundJob/RememberBackupCodesJob.php 1 patch
Indentation   +60 added lines, -60 removed lines patch added patch discarded remove patch
@@ -36,67 +36,67 @@
 block discarded – undo
36 36
 
37 37
 class RememberBackupCodesJob extends TimedJob {
38 38
 
39
-	/** @var IRegistry */
40
-	private $registry;
41
-
42
-	/** @var IUserManager */
43
-	private $userManager;
44
-
45
-	/** @var IManager */
46
-	private $notificationManager;
47
-
48
-	/** @var IJobList */
49
-	private $jobList;
50
-
51
-	public function __construct(IRegistry $registry,
52
-								IUserManager $userManager,
53
-								ITimeFactory $timeFactory,
54
-								IManager $notificationManager,
55
-								IJobList $jobList) {
56
-		parent::__construct($timeFactory);
57
-		$this->registry = $registry;
58
-		$this->userManager = $userManager;
59
-		$this->time = $timeFactory;
60
-		$this->notificationManager = $notificationManager;
61
-		$this->jobList = $jobList;
62
-
63
-		$this->setInterval(60 * 60 * 24 * 14);
64
-		$this->setTimeSensitivity(IJob::TIME_INSENSITIVE);
65
-	}
66
-
67
-	protected function run($argument) {
68
-		$uid = $argument['uid'];
69
-		$user = $this->userManager->get($uid);
70
-
71
-		if ($user === null) {
72
-			// We can't run with an invalid user
73
-			return;
74
-		}
75
-
76
-		$providers = $this->registry->getProviderStates($user);
77
-		$state2fa = array_reduce($providers, function (bool $carry, bool $state) {
78
-			return $carry || $state;
79
-		}, false);
80
-
81
-		/*
39
+    /** @var IRegistry */
40
+    private $registry;
41
+
42
+    /** @var IUserManager */
43
+    private $userManager;
44
+
45
+    /** @var IManager */
46
+    private $notificationManager;
47
+
48
+    /** @var IJobList */
49
+    private $jobList;
50
+
51
+    public function __construct(IRegistry $registry,
52
+                                IUserManager $userManager,
53
+                                ITimeFactory $timeFactory,
54
+                                IManager $notificationManager,
55
+                                IJobList $jobList) {
56
+        parent::__construct($timeFactory);
57
+        $this->registry = $registry;
58
+        $this->userManager = $userManager;
59
+        $this->time = $timeFactory;
60
+        $this->notificationManager = $notificationManager;
61
+        $this->jobList = $jobList;
62
+
63
+        $this->setInterval(60 * 60 * 24 * 14);
64
+        $this->setTimeSensitivity(IJob::TIME_INSENSITIVE);
65
+    }
66
+
67
+    protected function run($argument) {
68
+        $uid = $argument['uid'];
69
+        $user = $this->userManager->get($uid);
70
+
71
+        if ($user === null) {
72
+            // We can't run with an invalid user
73
+            return;
74
+        }
75
+
76
+        $providers = $this->registry->getProviderStates($user);
77
+        $state2fa = array_reduce($providers, function (bool $carry, bool $state) {
78
+            return $carry || $state;
79
+        }, false);
80
+
81
+        /*
82 82
 		 * If no provider is active or if the backup codes are already generate
83 83
 		 * we can remove the job
84 84
 		 */
85
-		if ($state2fa === false || (isset($providers['backup_codes']) && $providers['backup_codes'] === true)) {
86
-			// Backup codes already generated lets remove this job
87
-			$this->jobList->remove(self::class, $argument);
88
-			return;
89
-		}
90
-
91
-		$date = new \DateTime();
92
-		$date->setTimestamp($this->time->getTime());
93
-
94
-		$notification = $this->notificationManager->createNotification();
95
-		$notification->setApp('twofactor_backupcodes')
96
-			->setUser($user->getUID())
97
-			->setDateTime($date)
98
-			->setObject('create', 'codes')
99
-			->setSubject('create_backupcodes');
100
-		$this->notificationManager->notify($notification);
101
-	}
85
+        if ($state2fa === false || (isset($providers['backup_codes']) && $providers['backup_codes'] === true)) {
86
+            // Backup codes already generated lets remove this job
87
+            $this->jobList->remove(self::class, $argument);
88
+            return;
89
+        }
90
+
91
+        $date = new \DateTime();
92
+        $date->setTimestamp($this->time->getTime());
93
+
94
+        $notification = $this->notificationManager->createNotification();
95
+        $notification->setApp('twofactor_backupcodes')
96
+            ->setUser($user->getUID())
97
+            ->setDateTime($date)
98
+            ->setObject('create', 'codes')
99
+            ->setSubject('create_backupcodes');
100
+        $this->notificationManager->notify($notification);
101
+    }
102 102
 }
Please login to merge, or discard this patch.
apps/contactsinteraction/lib/BackgroundJob/CleanupJob.php 1 patch
Indentation   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -32,22 +32,22 @@
 block discarded – undo
32 32
 
33 33
 class CleanupJob extends TimedJob {
34 34
 
35
-	/** @var RecentContactMapper */
36
-	private $mapper;
35
+    /** @var RecentContactMapper */
36
+    private $mapper;
37 37
 
38
-	public function __construct(ITimeFactory $time,
39
-								RecentContactMapper $mapper) {
40
-		parent::__construct($time);
38
+    public function __construct(ITimeFactory $time,
39
+                                RecentContactMapper $mapper) {
40
+        parent::__construct($time);
41 41
 
42
-		$this->setInterval(24 * 60 * 60);
43
-		$this->setTimeSensitivity(IJob::TIME_INSENSITIVE);
42
+        $this->setInterval(24 * 60 * 60);
43
+        $this->setTimeSensitivity(IJob::TIME_INSENSITIVE);
44 44
 
45
-		$this->mapper = $mapper;
46
-	}
45
+        $this->mapper = $mapper;
46
+    }
47 47
 
48
-	protected function run($argument) {
49
-		$time = $this->time->getDateTime();
50
-		$time->modify('-7days');
51
-		$this->mapper->cleanUp($time->getTimestamp());
52
-	}
48
+    protected function run($argument) {
49
+        $time = $this->time->getDateTime();
50
+        $time->modify('-7days');
51
+        $this->mapper->cleanUp($time->getTimestamp());
52
+    }
53 53
 }
Please login to merge, or discard this patch.
cron.php 1 patch
Indentation   +145 added lines, -145 removed lines patch added patch discarded remove patch
@@ -40,151 +40,151 @@
 block discarded – undo
40 40
 require_once __DIR__ . '/lib/versioncheck.php';
41 41
 
42 42
 try {
43
-	require_once __DIR__ . '/lib/base.php';
44
-
45
-	if (\OCP\Util::needUpgrade()) {
46
-		\OC::$server->getLogger()->debug('Update required, skipping cron', ['app' => 'cron']);
47
-		exit;
48
-	}
49
-	if ((bool) \OC::$server->getSystemConfig()->getValue('maintenance', false)) {
50
-		\OC::$server->getLogger()->debug('We are in maintenance mode, skipping cron', ['app' => 'cron']);
51
-		exit;
52
-	}
53
-
54
-	// load all apps to get all api routes properly setup
55
-	OC_App::loadApps();
56
-
57
-	\OC::$server->getSession()->close();
58
-
59
-	// initialize a dummy memory session
60
-	$session = new \OC\Session\Memory('');
61
-	$cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
62
-	$session = $cryptoWrapper->wrapSession($session);
63
-	\OC::$server->setSession($session);
64
-
65
-	$logger = \OC::$server->getLogger();
66
-	$config = \OC::$server->getConfig();
67
-
68
-	// Don't do anything if Nextcloud has not been installed
69
-	if (!$config->getSystemValue('installed', false)) {
70
-		exit(0);
71
-	}
72
-
73
-	\OC::$server->getTempManager()->cleanOld();
74
-
75
-	// Exit if background jobs are disabled!
76
-	$appMode = $config->getAppValue('core', 'backgroundjobs_mode', 'ajax');
77
-	if ($appMode === 'none') {
78
-		if (OC::$CLI) {
79
-			echo 'Background Jobs are disabled!' . PHP_EOL;
80
-		} else {
81
-			OC_JSON::error(['data' => ['message' => 'Background jobs disabled!']]);
82
-		}
83
-		exit(1);
84
-	}
85
-
86
-	if (OC::$CLI) {
87
-		// set to run indefinitely if needed
88
-		if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
89
-			@set_time_limit(0);
90
-		}
91
-
92
-		// the cron job must be executed with the right user
93
-		if (!function_exists('posix_getuid')) {
94
-			echo "The posix extensions are required - see https://www.php.net/manual/en/book.posix.php" . PHP_EOL;
95
-			exit(1);
96
-		}
97
-
98
-		$user = posix_getuid();
99
-		$configUser = fileowner(OC::$configDir . 'config.php');
100
-		if ($user !== $configUser) {
101
-			echo "Console has to be executed with the user that owns the file config/config.php" . PHP_EOL;
102
-			echo "Current user id: " . $user . PHP_EOL;
103
-			echo "Owner id of config.php: " . $configUser . PHP_EOL;
104
-			exit(1);
105
-		}
106
-
107
-
108
-		// We call Nextcloud from the CLI (aka cron)
109
-		if ($appMode !== 'cron') {
110
-			$config->setAppValue('core', 'backgroundjobs_mode', 'cron');
111
-		}
112
-
113
-		// Low-load hours
114
-		$onlyTimeSensitive = false;
115
-		$startHour = $config->getSystemValueInt('maintenance_window_start', 100);
116
-		if ($startHour <= 23) {
117
-			$date = new \DateTime('now', new \DateTimeZone('UTC'));
118
-			$currentHour = (int) $date->format('G');
119
-			$endHour = $startHour + 4;
120
-
121
-			if ($startHour <= 20) {
122
-				// Start time: 01:00
123
-				// End time: 05:00
124
-				// Only run sensitive tasks when it's before the start or after the end
125
-				$onlyTimeSensitive = $currentHour < $startHour || $currentHour > $endHour;
126
-			} else {
127
-				// Start time: 23:00
128
-				// End time: 03:00
129
-				$endHour -= 24; // Correct the end time from 27:00 to 03:00
130
-				// Only run sensitive tasks when it's after the end and before the start
131
-				$onlyTimeSensitive = $currentHour > $endHour && $currentHour < $startHour;
132
-			}
133
-		}
134
-
135
-		// Work
136
-		$jobList = \OC::$server->getJobList();
137
-
138
-		// We only ask for jobs for 14 minutes, because after 5 minutes the next
139
-		// system cron task should spawn and we want to have at most three
140
-		// cron jobs running in parallel.
141
-		$endTime = time() + 14 * 60;
142
-
143
-		$executedJobs = [];
144
-		while ($job = $jobList->getNext($onlyTimeSensitive)) {
145
-			if (isset($executedJobs[$job->getId()])) {
146
-				$jobList->unlockJob($job);
147
-				break;
148
-			}
149
-
150
-			$job->execute($jobList, $logger);
151
-			// clean up after unclean jobs
152
-			\OC_Util::tearDownFS();
153
-
154
-			$jobList->setLastJob($job);
155
-			$executedJobs[$job->getId()] = true;
156
-			unset($job);
157
-
158
-			if (time() > $endTime) {
159
-				break;
160
-			}
161
-		}
162
-	} else {
163
-		// We call cron.php from some website
164
-		if ($appMode === 'cron') {
165
-			// Cron is cron :-P
166
-			OC_JSON::error(['data' => ['message' => 'Backgroundjobs are using system cron!']]);
167
-		} else {
168
-			// Work and success :-)
169
-			$jobList = \OC::$server->getJobList();
170
-			$job = $jobList->getNext();
171
-			if ($job != null) {
172
-				$job->execute($jobList, $logger);
173
-				$jobList->setLastJob($job);
174
-			}
175
-			OC_JSON::success();
176
-		}
177
-	}
178
-
179
-	// Log the successful cron execution
180
-	$config->setAppValue('core', 'lastcron', time());
181
-	exit();
43
+    require_once __DIR__ . '/lib/base.php';
44
+
45
+    if (\OCP\Util::needUpgrade()) {
46
+        \OC::$server->getLogger()->debug('Update required, skipping cron', ['app' => 'cron']);
47
+        exit;
48
+    }
49
+    if ((bool) \OC::$server->getSystemConfig()->getValue('maintenance', false)) {
50
+        \OC::$server->getLogger()->debug('We are in maintenance mode, skipping cron', ['app' => 'cron']);
51
+        exit;
52
+    }
53
+
54
+    // load all apps to get all api routes properly setup
55
+    OC_App::loadApps();
56
+
57
+    \OC::$server->getSession()->close();
58
+
59
+    // initialize a dummy memory session
60
+    $session = new \OC\Session\Memory('');
61
+    $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
62
+    $session = $cryptoWrapper->wrapSession($session);
63
+    \OC::$server->setSession($session);
64
+
65
+    $logger = \OC::$server->getLogger();
66
+    $config = \OC::$server->getConfig();
67
+
68
+    // Don't do anything if Nextcloud has not been installed
69
+    if (!$config->getSystemValue('installed', false)) {
70
+        exit(0);
71
+    }
72
+
73
+    \OC::$server->getTempManager()->cleanOld();
74
+
75
+    // Exit if background jobs are disabled!
76
+    $appMode = $config->getAppValue('core', 'backgroundjobs_mode', 'ajax');
77
+    if ($appMode === 'none') {
78
+        if (OC::$CLI) {
79
+            echo 'Background Jobs are disabled!' . PHP_EOL;
80
+        } else {
81
+            OC_JSON::error(['data' => ['message' => 'Background jobs disabled!']]);
82
+        }
83
+        exit(1);
84
+    }
85
+
86
+    if (OC::$CLI) {
87
+        // set to run indefinitely if needed
88
+        if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
89
+            @set_time_limit(0);
90
+        }
91
+
92
+        // the cron job must be executed with the right user
93
+        if (!function_exists('posix_getuid')) {
94
+            echo "The posix extensions are required - see https://www.php.net/manual/en/book.posix.php" . PHP_EOL;
95
+            exit(1);
96
+        }
97
+
98
+        $user = posix_getuid();
99
+        $configUser = fileowner(OC::$configDir . 'config.php');
100
+        if ($user !== $configUser) {
101
+            echo "Console has to be executed with the user that owns the file config/config.php" . PHP_EOL;
102
+            echo "Current user id: " . $user . PHP_EOL;
103
+            echo "Owner id of config.php: " . $configUser . PHP_EOL;
104
+            exit(1);
105
+        }
106
+
107
+
108
+        // We call Nextcloud from the CLI (aka cron)
109
+        if ($appMode !== 'cron') {
110
+            $config->setAppValue('core', 'backgroundjobs_mode', 'cron');
111
+        }
112
+
113
+        // Low-load hours
114
+        $onlyTimeSensitive = false;
115
+        $startHour = $config->getSystemValueInt('maintenance_window_start', 100);
116
+        if ($startHour <= 23) {
117
+            $date = new \DateTime('now', new \DateTimeZone('UTC'));
118
+            $currentHour = (int) $date->format('G');
119
+            $endHour = $startHour + 4;
120
+
121
+            if ($startHour <= 20) {
122
+                // Start time: 01:00
123
+                // End time: 05:00
124
+                // Only run sensitive tasks when it's before the start or after the end
125
+                $onlyTimeSensitive = $currentHour < $startHour || $currentHour > $endHour;
126
+            } else {
127
+                // Start time: 23:00
128
+                // End time: 03:00
129
+                $endHour -= 24; // Correct the end time from 27:00 to 03:00
130
+                // Only run sensitive tasks when it's after the end and before the start
131
+                $onlyTimeSensitive = $currentHour > $endHour && $currentHour < $startHour;
132
+            }
133
+        }
134
+
135
+        // Work
136
+        $jobList = \OC::$server->getJobList();
137
+
138
+        // We only ask for jobs for 14 minutes, because after 5 minutes the next
139
+        // system cron task should spawn and we want to have at most three
140
+        // cron jobs running in parallel.
141
+        $endTime = time() + 14 * 60;
142
+
143
+        $executedJobs = [];
144
+        while ($job = $jobList->getNext($onlyTimeSensitive)) {
145
+            if (isset($executedJobs[$job->getId()])) {
146
+                $jobList->unlockJob($job);
147
+                break;
148
+            }
149
+
150
+            $job->execute($jobList, $logger);
151
+            // clean up after unclean jobs
152
+            \OC_Util::tearDownFS();
153
+
154
+            $jobList->setLastJob($job);
155
+            $executedJobs[$job->getId()] = true;
156
+            unset($job);
157
+
158
+            if (time() > $endTime) {
159
+                break;
160
+            }
161
+        }
162
+    } else {
163
+        // We call cron.php from some website
164
+        if ($appMode === 'cron') {
165
+            // Cron is cron :-P
166
+            OC_JSON::error(['data' => ['message' => 'Backgroundjobs are using system cron!']]);
167
+        } else {
168
+            // Work and success :-)
169
+            $jobList = \OC::$server->getJobList();
170
+            $job = $jobList->getNext();
171
+            if ($job != null) {
172
+                $job->execute($jobList, $logger);
173
+                $jobList->setLastJob($job);
174
+            }
175
+            OC_JSON::success();
176
+        }
177
+    }
178
+
179
+    // Log the successful cron execution
180
+    $config->setAppValue('core', 'lastcron', time());
181
+    exit();
182 182
 } catch (Exception $ex) {
183
-	\OC::$server->getLogger()->logException($ex, ['app' => 'cron']);
184
-	echo $ex . PHP_EOL;
185
-	exit(1);
183
+    \OC::$server->getLogger()->logException($ex, ['app' => 'cron']);
184
+    echo $ex . PHP_EOL;
185
+    exit(1);
186 186
 } catch (Error $ex) {
187
-	\OC::$server->getLogger()->logException($ex, ['app' => 'cron']);
188
-	echo $ex . PHP_EOL;
189
-	exit(1);
187
+    \OC::$server->getLogger()->logException($ex, ['app' => 'cron']);
188
+    echo $ex . PHP_EOL;
189
+    exit(1);
190 190
 }
Please login to merge, or discard this patch.
lib/private/Security/Bruteforce/CleanupJob.php 1 patch
Indentation   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -33,25 +33,25 @@
 block discarded – undo
33 33
 
34 34
 class CleanupJob extends TimedJob {
35 35
 
36
-	/** @var IDBConnection */
37
-	private $connection;
38
-
39
-	public function __construct(ITimeFactory $time, IDBConnection $connection) {
40
-		parent::__construct($time);
41
-		$this->connection = $connection;
42
-
43
-		// Run once a day
44
-		$this->setInterval(3600 * 24);
45
-		$this->setTimeSensitivity(IJob::TIME_INSENSITIVE);
46
-	}
47
-
48
-	protected function run($argument) {
49
-		// Delete all entries more than 48 hours old
50
-		$time = $this->time->getTime() - (48 * 3600);
51
-
52
-		$qb = $this->connection->getQueryBuilder();
53
-		$qb->delete('bruteforce_attempts')
54
-			->where($qb->expr()->lt('occurred', $qb->createNamedParameter($time), IQueryBuilder::PARAM_INT));
55
-		$qb->execute();
56
-	}
36
+    /** @var IDBConnection */
37
+    private $connection;
38
+
39
+    public function __construct(ITimeFactory $time, IDBConnection $connection) {
40
+        parent::__construct($time);
41
+        $this->connection = $connection;
42
+
43
+        // Run once a day
44
+        $this->setInterval(3600 * 24);
45
+        $this->setTimeSensitivity(IJob::TIME_INSENSITIVE);
46
+    }
47
+
48
+    protected function run($argument) {
49
+        // Delete all entries more than 48 hours old
50
+        $time = $this->time->getTime() - (48 * 3600);
51
+
52
+        $qb = $this->connection->getQueryBuilder();
53
+        $qb->delete('bruteforce_attempts')
54
+            ->where($qb->expr()->lt('occurred', $qb->createNamedParameter($time), IQueryBuilder::PARAM_INT));
55
+        $qb->execute();
56
+    }
57 57
 }
Please login to merge, or discard this patch.
lib/private/BackgroundJob/JobList.php 1 patch
Indentation   +333 added lines, -333 removed lines patch added patch discarded remove patch
@@ -40,337 +40,337 @@
 block discarded – undo
40 40
 
41 41
 class JobList implements IJobList {
42 42
 
43
-	/** @var IDBConnection */
44
-	protected $connection;
45
-
46
-	/**@var IConfig */
47
-	protected $config;
48
-
49
-	/**@var ITimeFactory */
50
-	protected $timeFactory;
51
-
52
-	/**
53
-	 * @param IDBConnection $connection
54
-	 * @param IConfig $config
55
-	 * @param ITimeFactory $timeFactory
56
-	 */
57
-	public function __construct(IDBConnection $connection, IConfig $config, ITimeFactory $timeFactory) {
58
-		$this->connection = $connection;
59
-		$this->config = $config;
60
-		$this->timeFactory = $timeFactory;
61
-	}
62
-
63
-	/**
64
-	 * @param IJob|string $job
65
-	 * @param mixed $argument
66
-	 */
67
-	public function add($job, $argument = null) {
68
-		if ($job instanceof IJob) {
69
-			$class = get_class($job);
70
-		} else {
71
-			$class = $job;
72
-		}
73
-
74
-		$argumentJson = json_encode($argument);
75
-		if (strlen($argumentJson) > 4000) {
76
-			throw new \InvalidArgumentException('Background job arguments can\'t exceed 4000 characters (json encoded)');
77
-		}
78
-
79
-		$query = $this->connection->getQueryBuilder();
80
-		if (!$this->has($job, $argument)) {
81
-			$query->insert('jobs')
82
-				->values([
83
-					'class' => $query->createNamedParameter($class),
84
-					'argument' => $query->createNamedParameter($argumentJson),
85
-					'argument_hash' => $query->createNamedParameter(md5($argumentJson)),
86
-					'last_run' => $query->createNamedParameter(0, IQueryBuilder::PARAM_INT),
87
-					'last_checked' => $query->createNamedParameter($this->timeFactory->getTime(), IQueryBuilder::PARAM_INT),
88
-				]);
89
-		} else {
90
-			$query->update('jobs')
91
-				->set('reserved_at', $query->expr()->literal(0, IQueryBuilder::PARAM_INT))
92
-				->set('last_checked', $query->createNamedParameter($this->timeFactory->getTime(), IQueryBuilder::PARAM_INT))
93
-				->where($query->expr()->eq('class', $query->createNamedParameter($class)))
94
-				->andWhere($query->expr()->eq('argument_hash', $query->createNamedParameter(md5($argumentJson))));
95
-		}
96
-		$query->executeStatement();
97
-	}
98
-
99
-	/**
100
-	 * @param IJob|string $job
101
-	 * @param mixed $argument
102
-	 */
103
-	public function remove($job, $argument = null) {
104
-		if ($job instanceof IJob) {
105
-			$class = get_class($job);
106
-		} else {
107
-			$class = $job;
108
-		}
109
-
110
-		$query = $this->connection->getQueryBuilder();
111
-		$query->delete('jobs')
112
-			->where($query->expr()->eq('class', $query->createNamedParameter($class)));
113
-		if (!is_null($argument)) {
114
-			$argument = json_encode($argument);
115
-			$query->andWhere($query->expr()->eq('argument', $query->createNamedParameter($argument)));
116
-		}
117
-		$query->execute();
118
-	}
119
-
120
-	/**
121
-	 * @param int $id
122
-	 */
123
-	protected function removeById($id) {
124
-		$query = $this->connection->getQueryBuilder();
125
-		$query->delete('jobs')
126
-			->where($query->expr()->eq('id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
127
-		$query->execute();
128
-	}
129
-
130
-	/**
131
-	 * check if a job is in the list
132
-	 *
133
-	 * @param IJob|string $job
134
-	 * @param mixed $argument
135
-	 * @return bool
136
-	 */
137
-	public function has($job, $argument) {
138
-		if ($job instanceof IJob) {
139
-			$class = get_class($job);
140
-		} else {
141
-			$class = $job;
142
-		}
143
-		$argument = json_encode($argument);
144
-
145
-		$query = $this->connection->getQueryBuilder();
146
-		$query->select('id')
147
-			->from('jobs')
148
-			->where($query->expr()->eq('class', $query->createNamedParameter($class)))
149
-			->andWhere($query->expr()->eq('argument_hash', $query->createNamedParameter(md5($argument))))
150
-			->setMaxResults(1);
151
-
152
-		$result = $query->execute();
153
-		$row = $result->fetch();
154
-		$result->closeCursor();
155
-
156
-		return (bool) $row;
157
-	}
158
-
159
-	/**
160
-	 * get all jobs in the list
161
-	 *
162
-	 * @return IJob[]
163
-	 * @deprecated 9.0.0 - This method is dangerous since it can cause load and
164
-	 * memory problems when creating too many instances.
165
-	 */
166
-	public function getAll() {
167
-		$query = $this->connection->getQueryBuilder();
168
-		$query->select('*')
169
-			->from('jobs');
170
-		$result = $query->execute();
171
-
172
-		$jobs = [];
173
-		while ($row = $result->fetch()) {
174
-			$job = $this->buildJob($row);
175
-			if ($job) {
176
-				$jobs[] = $job;
177
-			}
178
-		}
179
-		$result->closeCursor();
180
-
181
-		return $jobs;
182
-	}
183
-
184
-	/**
185
-	 * get the next job in the list
186
-	 *
187
-	 * @param bool $onlyTimeSensitive
188
-	 * @return IJob|null
189
-	 */
190
-	public function getNext(bool $onlyTimeSensitive = true): ?IJob {
191
-		$query = $this->connection->getQueryBuilder();
192
-		$query->select('*')
193
-			->from('jobs')
194
-			->where($query->expr()->lte('reserved_at', $query->createNamedParameter($this->timeFactory->getTime() - 12 * 3600, IQueryBuilder::PARAM_INT)))
195
-			->andWhere($query->expr()->lte('last_checked', $query->createNamedParameter($this->timeFactory->getTime(), IQueryBuilder::PARAM_INT)))
196
-			->orderBy('last_checked', 'ASC')
197
-			->setMaxResults(1);
198
-
199
-		if ($onlyTimeSensitive) {
200
-			$query->andWhere($query->expr()->eq('time_sensitive', $query->createNamedParameter(IJob::TIME_SENSITIVE, IQueryBuilder::PARAM_INT)));
201
-		}
202
-
203
-		$update = $this->connection->getQueryBuilder();
204
-		$update->update('jobs')
205
-			->set('reserved_at', $update->createNamedParameter($this->timeFactory->getTime()))
206
-			->set('last_checked', $update->createNamedParameter($this->timeFactory->getTime()))
207
-			->where($update->expr()->eq('id', $update->createParameter('jobid')))
208
-			->andWhere($update->expr()->eq('reserved_at', $update->createParameter('reserved_at')))
209
-			->andWhere($update->expr()->eq('last_checked', $update->createParameter('last_checked')));
210
-
211
-		$result = $query->execute();
212
-		$row = $result->fetch();
213
-		$result->closeCursor();
214
-
215
-		if ($row) {
216
-			$update->setParameter('jobid', $row['id']);
217
-			$update->setParameter('reserved_at', $row['reserved_at']);
218
-			$update->setParameter('last_checked', $row['last_checked']);
219
-			$count = $update->execute();
220
-
221
-			if ($count === 0) {
222
-				// Background job already executed elsewhere, try again.
223
-				return $this->getNext($onlyTimeSensitive);
224
-			}
225
-			$job = $this->buildJob($row);
226
-
227
-			if ($job === null) {
228
-				// set the last_checked to 12h in the future to not check failing jobs all over again
229
-				$reset = $this->connection->getQueryBuilder();
230
-				$reset->update('jobs')
231
-					->set('reserved_at', $reset->expr()->literal(0, IQueryBuilder::PARAM_INT))
232
-					->set('last_checked', $reset->createNamedParameter($this->timeFactory->getTime() + 12 * 3600, IQueryBuilder::PARAM_INT))
233
-					->where($reset->expr()->eq('id', $reset->createNamedParameter($row['id'], IQueryBuilder::PARAM_INT)));
234
-				$reset->execute();
235
-
236
-				// Background job from disabled app, try again.
237
-				return $this->getNext($onlyTimeSensitive);
238
-			}
239
-
240
-			return $job;
241
-		} else {
242
-			return null;
243
-		}
244
-	}
245
-
246
-	/**
247
-	 * @param int $id
248
-	 * @return IJob|null
249
-	 */
250
-	public function getById($id) {
251
-		$row = $this->getDetailsById($id);
252
-
253
-		if ($row) {
254
-			return $this->buildJob($row);
255
-		}
256
-
257
-		return null;
258
-	}
259
-
260
-	public function getDetailsById(int $id): ?array {
261
-		$query = $this->connection->getQueryBuilder();
262
-		$query->select('*')
263
-			->from('jobs')
264
-			->where($query->expr()->eq('id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
265
-		$result = $query->executeQuery();
266
-		$row = $result->fetch();
267
-		$result->closeCursor();
268
-
269
-		if ($row) {
270
-			return $row;
271
-		}
272
-
273
-		return null;
274
-	}
275
-
276
-	/**
277
-	 * get the job object from a row in the db
278
-	 *
279
-	 * @param array $row
280
-	 * @return IJob|null
281
-	 */
282
-	private function buildJob($row) {
283
-		try {
284
-			try {
285
-				// Try to load the job as a service
286
-				/** @var IJob $job */
287
-				$job = \OC::$server->query($row['class']);
288
-			} catch (QueryException $e) {
289
-				if (class_exists($row['class'])) {
290
-					$class = $row['class'];
291
-					$job = new $class();
292
-				} else {
293
-					// job from disabled app or old version of an app, no need to do anything
294
-					return null;
295
-				}
296
-			}
297
-
298
-			$job->setId((int) $row['id']);
299
-			$job->setLastRun((int) $row['last_run']);
300
-			$job->setArgument(json_decode($row['argument'], true));
301
-			return $job;
302
-		} catch (AutoloadNotAllowedException $e) {
303
-			// job is from a disabled app, ignore
304
-			return null;
305
-		}
306
-	}
307
-
308
-	/**
309
-	 * set the job that was last ran
310
-	 *
311
-	 * @param IJob $job
312
-	 */
313
-	public function setLastJob(IJob $job) {
314
-		$this->unlockJob($job);
315
-		$this->config->setAppValue('backgroundjob', 'lastjob', $job->getId());
316
-	}
317
-
318
-	/**
319
-	 * Remove the reservation for a job
320
-	 *
321
-	 * @param IJob $job
322
-	 */
323
-	public function unlockJob(IJob $job) {
324
-		$query = $this->connection->getQueryBuilder();
325
-		$query->update('jobs')
326
-			->set('reserved_at', $query->expr()->literal(0, IQueryBuilder::PARAM_INT))
327
-			->where($query->expr()->eq('id', $query->createNamedParameter($job->getId(), IQueryBuilder::PARAM_INT)));
328
-		$query->execute();
329
-	}
330
-
331
-	/**
332
-	 * set the lastRun of $job to now
333
-	 *
334
-	 * @param IJob $job
335
-	 */
336
-	public function setLastRun(IJob $job) {
337
-		$query = $this->connection->getQueryBuilder();
338
-		$query->update('jobs')
339
-			->set('last_run', $query->createNamedParameter(time(), IQueryBuilder::PARAM_INT))
340
-			->where($query->expr()->eq('id', $query->createNamedParameter($job->getId(), IQueryBuilder::PARAM_INT)));
341
-
342
-		if ($job instanceof \OCP\BackgroundJob\TimedJob
343
-			&& !$job->isTimeSensitive()) {
344
-			$query->set('time_sensitive', $query->createNamedParameter(IJob::TIME_INSENSITIVE));
345
-		}
346
-
347
-		$query->execute();
348
-	}
349
-
350
-	/**
351
-	 * @param IJob $job
352
-	 * @param $timeTaken
353
-	 */
354
-	public function setExecutionTime(IJob $job, $timeTaken) {
355
-		$query = $this->connection->getQueryBuilder();
356
-		$query->update('jobs')
357
-			->set('execution_duration', $query->createNamedParameter($timeTaken, IQueryBuilder::PARAM_INT))
358
-			->where($query->expr()->eq('id', $query->createNamedParameter($job->getId(), IQueryBuilder::PARAM_INT)));
359
-		$query->execute();
360
-	}
361
-
362
-	/**
363
-	 * Reset the $job so it executes on the next trigger
364
-	 *
365
-	 * @param IJob $job
366
-	 * @since 23.0.0
367
-	 */
368
-	public function resetBackgroundJob(IJob $job): void {
369
-		$query = $this->connection->getQueryBuilder();
370
-		$query->update('jobs')
371
-			->set('last_run', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT))
372
-			->set('reserved_at', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT))
373
-			->where($query->expr()->eq('id', $query->createNamedParameter($job->getId()), IQueryBuilder::PARAM_INT));
374
-		$query->executeStatement();
375
-	}
43
+    /** @var IDBConnection */
44
+    protected $connection;
45
+
46
+    /**@var IConfig */
47
+    protected $config;
48
+
49
+    /**@var ITimeFactory */
50
+    protected $timeFactory;
51
+
52
+    /**
53
+     * @param IDBConnection $connection
54
+     * @param IConfig $config
55
+     * @param ITimeFactory $timeFactory
56
+     */
57
+    public function __construct(IDBConnection $connection, IConfig $config, ITimeFactory $timeFactory) {
58
+        $this->connection = $connection;
59
+        $this->config = $config;
60
+        $this->timeFactory = $timeFactory;
61
+    }
62
+
63
+    /**
64
+     * @param IJob|string $job
65
+     * @param mixed $argument
66
+     */
67
+    public function add($job, $argument = null) {
68
+        if ($job instanceof IJob) {
69
+            $class = get_class($job);
70
+        } else {
71
+            $class = $job;
72
+        }
73
+
74
+        $argumentJson = json_encode($argument);
75
+        if (strlen($argumentJson) > 4000) {
76
+            throw new \InvalidArgumentException('Background job arguments can\'t exceed 4000 characters (json encoded)');
77
+        }
78
+
79
+        $query = $this->connection->getQueryBuilder();
80
+        if (!$this->has($job, $argument)) {
81
+            $query->insert('jobs')
82
+                ->values([
83
+                    'class' => $query->createNamedParameter($class),
84
+                    'argument' => $query->createNamedParameter($argumentJson),
85
+                    'argument_hash' => $query->createNamedParameter(md5($argumentJson)),
86
+                    'last_run' => $query->createNamedParameter(0, IQueryBuilder::PARAM_INT),
87
+                    'last_checked' => $query->createNamedParameter($this->timeFactory->getTime(), IQueryBuilder::PARAM_INT),
88
+                ]);
89
+        } else {
90
+            $query->update('jobs')
91
+                ->set('reserved_at', $query->expr()->literal(0, IQueryBuilder::PARAM_INT))
92
+                ->set('last_checked', $query->createNamedParameter($this->timeFactory->getTime(), IQueryBuilder::PARAM_INT))
93
+                ->where($query->expr()->eq('class', $query->createNamedParameter($class)))
94
+                ->andWhere($query->expr()->eq('argument_hash', $query->createNamedParameter(md5($argumentJson))));
95
+        }
96
+        $query->executeStatement();
97
+    }
98
+
99
+    /**
100
+     * @param IJob|string $job
101
+     * @param mixed $argument
102
+     */
103
+    public function remove($job, $argument = null) {
104
+        if ($job instanceof IJob) {
105
+            $class = get_class($job);
106
+        } else {
107
+            $class = $job;
108
+        }
109
+
110
+        $query = $this->connection->getQueryBuilder();
111
+        $query->delete('jobs')
112
+            ->where($query->expr()->eq('class', $query->createNamedParameter($class)));
113
+        if (!is_null($argument)) {
114
+            $argument = json_encode($argument);
115
+            $query->andWhere($query->expr()->eq('argument', $query->createNamedParameter($argument)));
116
+        }
117
+        $query->execute();
118
+    }
119
+
120
+    /**
121
+     * @param int $id
122
+     */
123
+    protected function removeById($id) {
124
+        $query = $this->connection->getQueryBuilder();
125
+        $query->delete('jobs')
126
+            ->where($query->expr()->eq('id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
127
+        $query->execute();
128
+    }
129
+
130
+    /**
131
+     * check if a job is in the list
132
+     *
133
+     * @param IJob|string $job
134
+     * @param mixed $argument
135
+     * @return bool
136
+     */
137
+    public function has($job, $argument) {
138
+        if ($job instanceof IJob) {
139
+            $class = get_class($job);
140
+        } else {
141
+            $class = $job;
142
+        }
143
+        $argument = json_encode($argument);
144
+
145
+        $query = $this->connection->getQueryBuilder();
146
+        $query->select('id')
147
+            ->from('jobs')
148
+            ->where($query->expr()->eq('class', $query->createNamedParameter($class)))
149
+            ->andWhere($query->expr()->eq('argument_hash', $query->createNamedParameter(md5($argument))))
150
+            ->setMaxResults(1);
151
+
152
+        $result = $query->execute();
153
+        $row = $result->fetch();
154
+        $result->closeCursor();
155
+
156
+        return (bool) $row;
157
+    }
158
+
159
+    /**
160
+     * get all jobs in the list
161
+     *
162
+     * @return IJob[]
163
+     * @deprecated 9.0.0 - This method is dangerous since it can cause load and
164
+     * memory problems when creating too many instances.
165
+     */
166
+    public function getAll() {
167
+        $query = $this->connection->getQueryBuilder();
168
+        $query->select('*')
169
+            ->from('jobs');
170
+        $result = $query->execute();
171
+
172
+        $jobs = [];
173
+        while ($row = $result->fetch()) {
174
+            $job = $this->buildJob($row);
175
+            if ($job) {
176
+                $jobs[] = $job;
177
+            }
178
+        }
179
+        $result->closeCursor();
180
+
181
+        return $jobs;
182
+    }
183
+
184
+    /**
185
+     * get the next job in the list
186
+     *
187
+     * @param bool $onlyTimeSensitive
188
+     * @return IJob|null
189
+     */
190
+    public function getNext(bool $onlyTimeSensitive = true): ?IJob {
191
+        $query = $this->connection->getQueryBuilder();
192
+        $query->select('*')
193
+            ->from('jobs')
194
+            ->where($query->expr()->lte('reserved_at', $query->createNamedParameter($this->timeFactory->getTime() - 12 * 3600, IQueryBuilder::PARAM_INT)))
195
+            ->andWhere($query->expr()->lte('last_checked', $query->createNamedParameter($this->timeFactory->getTime(), IQueryBuilder::PARAM_INT)))
196
+            ->orderBy('last_checked', 'ASC')
197
+            ->setMaxResults(1);
198
+
199
+        if ($onlyTimeSensitive) {
200
+            $query->andWhere($query->expr()->eq('time_sensitive', $query->createNamedParameter(IJob::TIME_SENSITIVE, IQueryBuilder::PARAM_INT)));
201
+        }
202
+
203
+        $update = $this->connection->getQueryBuilder();
204
+        $update->update('jobs')
205
+            ->set('reserved_at', $update->createNamedParameter($this->timeFactory->getTime()))
206
+            ->set('last_checked', $update->createNamedParameter($this->timeFactory->getTime()))
207
+            ->where($update->expr()->eq('id', $update->createParameter('jobid')))
208
+            ->andWhere($update->expr()->eq('reserved_at', $update->createParameter('reserved_at')))
209
+            ->andWhere($update->expr()->eq('last_checked', $update->createParameter('last_checked')));
210
+
211
+        $result = $query->execute();
212
+        $row = $result->fetch();
213
+        $result->closeCursor();
214
+
215
+        if ($row) {
216
+            $update->setParameter('jobid', $row['id']);
217
+            $update->setParameter('reserved_at', $row['reserved_at']);
218
+            $update->setParameter('last_checked', $row['last_checked']);
219
+            $count = $update->execute();
220
+
221
+            if ($count === 0) {
222
+                // Background job already executed elsewhere, try again.
223
+                return $this->getNext($onlyTimeSensitive);
224
+            }
225
+            $job = $this->buildJob($row);
226
+
227
+            if ($job === null) {
228
+                // set the last_checked to 12h in the future to not check failing jobs all over again
229
+                $reset = $this->connection->getQueryBuilder();
230
+                $reset->update('jobs')
231
+                    ->set('reserved_at', $reset->expr()->literal(0, IQueryBuilder::PARAM_INT))
232
+                    ->set('last_checked', $reset->createNamedParameter($this->timeFactory->getTime() + 12 * 3600, IQueryBuilder::PARAM_INT))
233
+                    ->where($reset->expr()->eq('id', $reset->createNamedParameter($row['id'], IQueryBuilder::PARAM_INT)));
234
+                $reset->execute();
235
+
236
+                // Background job from disabled app, try again.
237
+                return $this->getNext($onlyTimeSensitive);
238
+            }
239
+
240
+            return $job;
241
+        } else {
242
+            return null;
243
+        }
244
+    }
245
+
246
+    /**
247
+     * @param int $id
248
+     * @return IJob|null
249
+     */
250
+    public function getById($id) {
251
+        $row = $this->getDetailsById($id);
252
+
253
+        if ($row) {
254
+            return $this->buildJob($row);
255
+        }
256
+
257
+        return null;
258
+    }
259
+
260
+    public function getDetailsById(int $id): ?array {
261
+        $query = $this->connection->getQueryBuilder();
262
+        $query->select('*')
263
+            ->from('jobs')
264
+            ->where($query->expr()->eq('id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
265
+        $result = $query->executeQuery();
266
+        $row = $result->fetch();
267
+        $result->closeCursor();
268
+
269
+        if ($row) {
270
+            return $row;
271
+        }
272
+
273
+        return null;
274
+    }
275
+
276
+    /**
277
+     * get the job object from a row in the db
278
+     *
279
+     * @param array $row
280
+     * @return IJob|null
281
+     */
282
+    private function buildJob($row) {
283
+        try {
284
+            try {
285
+                // Try to load the job as a service
286
+                /** @var IJob $job */
287
+                $job = \OC::$server->query($row['class']);
288
+            } catch (QueryException $e) {
289
+                if (class_exists($row['class'])) {
290
+                    $class = $row['class'];
291
+                    $job = new $class();
292
+                } else {
293
+                    // job from disabled app or old version of an app, no need to do anything
294
+                    return null;
295
+                }
296
+            }
297
+
298
+            $job->setId((int) $row['id']);
299
+            $job->setLastRun((int) $row['last_run']);
300
+            $job->setArgument(json_decode($row['argument'], true));
301
+            return $job;
302
+        } catch (AutoloadNotAllowedException $e) {
303
+            // job is from a disabled app, ignore
304
+            return null;
305
+        }
306
+    }
307
+
308
+    /**
309
+     * set the job that was last ran
310
+     *
311
+     * @param IJob $job
312
+     */
313
+    public function setLastJob(IJob $job) {
314
+        $this->unlockJob($job);
315
+        $this->config->setAppValue('backgroundjob', 'lastjob', $job->getId());
316
+    }
317
+
318
+    /**
319
+     * Remove the reservation for a job
320
+     *
321
+     * @param IJob $job
322
+     */
323
+    public function unlockJob(IJob $job) {
324
+        $query = $this->connection->getQueryBuilder();
325
+        $query->update('jobs')
326
+            ->set('reserved_at', $query->expr()->literal(0, IQueryBuilder::PARAM_INT))
327
+            ->where($query->expr()->eq('id', $query->createNamedParameter($job->getId(), IQueryBuilder::PARAM_INT)));
328
+        $query->execute();
329
+    }
330
+
331
+    /**
332
+     * set the lastRun of $job to now
333
+     *
334
+     * @param IJob $job
335
+     */
336
+    public function setLastRun(IJob $job) {
337
+        $query = $this->connection->getQueryBuilder();
338
+        $query->update('jobs')
339
+            ->set('last_run', $query->createNamedParameter(time(), IQueryBuilder::PARAM_INT))
340
+            ->where($query->expr()->eq('id', $query->createNamedParameter($job->getId(), IQueryBuilder::PARAM_INT)));
341
+
342
+        if ($job instanceof \OCP\BackgroundJob\TimedJob
343
+            && !$job->isTimeSensitive()) {
344
+            $query->set('time_sensitive', $query->createNamedParameter(IJob::TIME_INSENSITIVE));
345
+        }
346
+
347
+        $query->execute();
348
+    }
349
+
350
+    /**
351
+     * @param IJob $job
352
+     * @param $timeTaken
353
+     */
354
+    public function setExecutionTime(IJob $job, $timeTaken) {
355
+        $query = $this->connection->getQueryBuilder();
356
+        $query->update('jobs')
357
+            ->set('execution_duration', $query->createNamedParameter($timeTaken, IQueryBuilder::PARAM_INT))
358
+            ->where($query->expr()->eq('id', $query->createNamedParameter($job->getId(), IQueryBuilder::PARAM_INT)));
359
+        $query->execute();
360
+    }
361
+
362
+    /**
363
+     * Reset the $job so it executes on the next trigger
364
+     *
365
+     * @param IJob $job
366
+     * @since 23.0.0
367
+     */
368
+    public function resetBackgroundJob(IJob $job): void {
369
+        $query = $this->connection->getQueryBuilder();
370
+        $query->update('jobs')
371
+            ->set('last_run', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT))
372
+            ->set('reserved_at', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT))
373
+            ->where($query->expr()->eq('id', $query->createNamedParameter($job->getId()), IQueryBuilder::PARAM_INT));
374
+        $query->executeStatement();
375
+    }
376 376
 }
Please login to merge, or discard this patch.
lib/public/BackgroundJob/IJob.php 1 patch
Indentation   +52 added lines, -52 removed lines patch added patch discarded remove patch
@@ -34,63 +34,63 @@
 block discarded – undo
34 34
  * @since 7.0.0
35 35
  */
36 36
 interface IJob {
37
-	/**
38
-	 * @since 24.0.0
39
-	 */
40
-	public const TIME_INSENSITIVE = 0;
41
-	/**
42
-	 * @since 24.0.0
43
-	 */
44
-	public const TIME_SENSITIVE = 1;
37
+    /**
38
+     * @since 24.0.0
39
+     */
40
+    public const TIME_INSENSITIVE = 0;
41
+    /**
42
+     * @since 24.0.0
43
+     */
44
+    public const TIME_SENSITIVE = 1;
45 45
 
46
-	/**
47
-	 * Run the background job with the registered argument
48
-	 *
49
-	 * @param IJobList $jobList The job list that manages the state of this job
50
-	 * @param ILogger|null $logger
51
-	 * @since 7.0.0
52
-	 */
53
-	public function execute(IJobList $jobList, ILogger $logger = null);
46
+    /**
47
+     * Run the background job with the registered argument
48
+     *
49
+     * @param IJobList $jobList The job list that manages the state of this job
50
+     * @param ILogger|null $logger
51
+     * @since 7.0.0
52
+     */
53
+    public function execute(IJobList $jobList, ILogger $logger = null);
54 54
 
55
-	/**
56
-	 * @since 7.0.0
57
-	 */
58
-	public function setId(int $id);
55
+    /**
56
+     * @since 7.0.0
57
+     */
58
+    public function setId(int $id);
59 59
 
60
-	/**
61
-	 * @since 7.0.0
62
-	 */
63
-	public function setLastRun(int $lastRun);
60
+    /**
61
+     * @since 7.0.0
62
+     */
63
+    public function setLastRun(int $lastRun);
64 64
 
65
-	/**
66
-	 * @param mixed $argument
67
-	 * @since 7.0.0
68
-	 */
69
-	public function setArgument($argument);
65
+    /**
66
+     * @param mixed $argument
67
+     * @since 7.0.0
68
+     */
69
+    public function setArgument($argument);
70 70
 
71
-	/**
72
-	 * Get the id of the background job
73
-	 * This id is determined by the job list when a job is added to the list
74
-	 *
75
-	 * @return int
76
-	 * @since 7.0.0
77
-	 */
78
-	public function getId();
71
+    /**
72
+     * Get the id of the background job
73
+     * This id is determined by the job list when a job is added to the list
74
+     *
75
+     * @return int
76
+     * @since 7.0.0
77
+     */
78
+    public function getId();
79 79
 
80
-	/**
81
-	 * Get the last time this job was run as unix timestamp
82
-	 *
83
-	 * @return int
84
-	 * @since 7.0.0
85
-	 */
86
-	public function getLastRun();
80
+    /**
81
+     * Get the last time this job was run as unix timestamp
82
+     *
83
+     * @return int
84
+     * @since 7.0.0
85
+     */
86
+    public function getLastRun();
87 87
 
88
-	/**
89
-	 * Get the argument associated with the background job
90
-	 * This is the argument that will be passed to the background job
91
-	 *
92
-	 * @return mixed
93
-	 * @since 7.0.0
94
-	 */
95
-	public function getArgument();
88
+    /**
89
+     * Get the argument associated with the background job
90
+     * This is the argument that will be passed to the background job
91
+     *
92
+     * @return mixed
93
+     * @since 7.0.0
94
+     */
95
+    public function getArgument();
96 96
 }
Please login to merge, or discard this patch.