foldershare-8.x-1.2/src/ManageUsageStatistics.php
src/ManageUsageStatistics.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 | <?php namespace Drupal\foldershare; use Drupal\Core\Database\Database; use Drupal\foldershare\Entity\FolderShare; use Drupal\foldershare\Entity\FolderShareScheduledTask; /** * Manages usage statistics for FolderShare entities. * * This class provides static methods to manage collecting and retrieving * usage statistics about FolderShare entities. Supported operations include: * - Clearing usage statistics. * - Deleting usage statistics for specific users. * - Getting usage statistics. * - Updating usage statistics. * * This method also provides methods to query configuration settings for * usage statistics updates, and the total number of FolderShare entities * of various types. * * <B>Access control</B> * This class's methods do not do access control. The caller should check * access as needed by their situation. * * @ingroup foldershare * * @see \Drupal\foldershare\Entity\FolderShare */ final class ManageUsageStatistics { /*-------------------------------------------------------------------- * * Constants. * *-------------------------------------------------------------------*/ /** * The name of the per-user usage tracking database table. */ const USAGE_TABLE = 'foldershare_usage' ; /*-------------------------------------------------------------------- * * Table definition. * *-------------------------------------------------------------------*/ /** * Returns the database schema that defines the user usage table. * * The table contains one record for each user. Record fields include: * * - The user ID. * - The number of subfolders they own. * - The number of files they own. * - The total storage used by the user. * * @return array * Returns an array describing the user usage table. */ public static function getSchema() { $schema [self::USAGE_TABLE] = [ 'description' => 'Stores file and folder usage information for users.' , 'fields' => [ // The user ID for the user. 'uid' => [ 'type' => 'int' , 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0, 'description' => 'The user ID.' , ], // The number of sub-folders. 'nFolders' => [ 'type' => 'int' , 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0, 'description' => 'The number of folders owned by the user.' , ], // The number of files. 'nFiles' => [ 'type' => 'int' , 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0, 'description' => 'The number of files owned by the user.' , ], // The total storage used by the user. 'nBytes' => [ 'type' => 'int' , 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0, 'description' => 'The amount of storage (in bytes) used by the user.' , ], ], // Primary Key. 'primary key' => [ 'uid' , ], // No additional indexes are needed beyond the primary key. ]; return $schema ; } /*-------------------------------------------------------------------- * * Usage operations. * *-------------------------------------------------------------------*/ /** * Clears usage statistics for all users. * * @see ::deleteFromUsage() * @see ::getUsage() * @see ::getAllUsage() */ public static function clearUsage() { $connection = Database::getConnection(); $connection -> delete (self::USAGE_TABLE)->execute(); } /** * Deletes the entries for a list of users. * * @param int[]|int $uids * (optional, default = -1) With a -1, usage statistics are deleted * for all users by forwarding to clearUsage(). Otherwise each user ID * given is deleted from the usage table. * * @see ::clearUsage() * @see ::getUsage() * @see ::getAllUsage() */ public static function deleteFromUsage( $uids = -1) { if ( $uids === -1 || $uids === '-1' || $uids === '' ) { self::clearUsage(); return ; } // User IDs are technically strings, but are often really integers and // are sometimes cast as integers. Accept either. if ( is_int ( $uids ) === TRUE || is_string [ $uids ] === TRUE) { $uids = [ $uids ]; } if ( is_array ( $uids ) === TRUE) { for ( $i = 0; $i < count ( $uids ); ++ $i ) { $uids [ $i ] = (string) $uids [ $i ]; } $connection = Database::getConnection(); $query = $connection -> delete (self::USAGE_TABLE); $query ->condition( 'uid' , $uids , 'IN' ); $query ->execute(); } } /** * Returns usage statistics of all users. * * The returned array has one entry for each user in the * database. Array keys are user IDs, and array values are associative * arrays with keys for specific metrics and values for those * metrics. Supported array keys are: * * - nFolders: the number of folders. * - nFiles: the number of files. * - nBytes: the total storage of all files. * * All metrics are for the total number of items or bytes owned by * the user. * * The returned values for bytes used is the current storage space use * for each user. This value does not include any database storage space * required for file and folder metadata. * * The returned array only contains records for those users that * have current usage. Users who have no recorded metrics * will not be listed in the returned array. * * @return array * An array with user ID array keys. Each array value is an * associative array with keys for each of the above usage. * * @see ::clearUsage() * @see ::deleteFromUsage() * @see ::getUsage() * @see ::updateUsage() */ public static function getAllUsage() { // Query the usage table for all entries. $connection = Database::getConnection(); $select = $connection ->select(self::USAGE_TABLE, 'u' ); $select ->addField( 'u' , 'uid' , 'uid' ); $select ->addField( 'u' , 'nFolders' , 'nFolders' ); $select ->addField( 'u' , 'nFiles' , 'nFiles' ); $select ->addField( 'u' , 'nBytes' , 'nBytes' ); $records = $select ->execute()->fetchAll(); // Build and return an array from the records. Array keys // are user IDs, while values are usage info. $usage = []; foreach ( $records as $record ) { $usage [ $record ->uid] = [ 'nFolders' => $record ->nFolders, 'nFiles' => $record ->nFiles, 'nBytes' => $record ->nBytes, ]; } return $usage ; } /** * Returns the time of the last usage statistics update. * * @return string * The last update time. */ public static function getLastUpdateTime() { return \Drupal::state()->get( 'foldershare.usage_last' ); } /** * Returns usage statistics for a user. * * The returned associative array has keys for specific metrics, * and values for those metrics. Supported array keys are: * * - nFolders: the number of folders. * - nFiles: the number of files. * - nBytes: the total storage of all files. * * All metrics are for the total number of items or bytes owned by * the user. * * The returned value for bytes used is the current storage space use * for the user. This value does not include any database storage space * required for file and folder metadata. * * If there is no recorded usage information for the user, an * array is returned with all metric values zero. * * @param int|string $uid * The user ID of the user whose usage is to be returned. * * @return array * An associative array is returned that includes keys for each * of the above usage. * * @see ::clearUsage() * @see ::deleteFromUsage() * @see ::getAllUsage() * @see ::updateUsage() */ public static function getUsage( $uid ) { // User IDs are technically strings, but are often really integers and // are sometimes cast as integers. Accept either. if ( is_int ( $uid ) === FALSE && is_string ( $uid ) === FALSE) { return [ 'nFolders' => 0, 'nFiles' => 0, 'nBytes' => 0, ]; } $uid = (string) $uid ; // Query the usage table for an entry for this user. // There could be none, or one, but not multiple entries. $connection = Database::getConnection(); $select = $connection ->select(self::USAGE_TABLE, 'u' ); $select ->addField( 'u' , 'uid' , 'uid' ); $select ->addField( 'u' , 'nFolders' , 'nFolders' ); $select ->addField( 'u' , 'nFiles' , 'nFiles' ); $select ->addField( 'u' , 'nBytes' , 'nBytes' ); $select ->condition( 'u.uid' , $uid , '=' ); $select ->range(0, 1); $records = $select ->execute()->fetchAll(); // If none, return an empty usage array. if ( count ( $records ) === 0) { return [ 'nFolders' => 0, 'nFiles' => 0, 'nBytes' => 0, ]; } // Otherwise return the usage. $record = array_shift ( $records ); return [ 'nFolders' => $record ->nFolders, 'nFiles' => $record ->nFiles, 'nBytes' => $record ->nBytes, ]; } /** * Updates the usage table. * * All current usage information is deleted and a new set assembled * and saved for all users at the site. Users that have no files or * folders are not included. * * <B>Process locks</B> * This method uses a process lock to insure that the usage table is * updated by only one process at a time. If the table is found to be * locked, this method returns immediately without updating the table. * * @return bool * Returns FALSE if the update aborted because another update is already * in progress. Otherwise returns TRUE. * * @see ::clearUsage() * @see ::deleteFromUsage() * @see ::getAllUsage() * @see ::getUsage() */ public static function updateUsage() { // LOCK DURING REBUILD. if (\Drupal::lock()->acquire( 'foldershare_usage_lock' , 30) === FALSE) { // Another update is in progress. return FALSE; } \Drupal::state()->set( 'foldershare.usage_last' , 'pending' ); // Empty the table. $connection = Database::getConnection(); $connection -> delete (self::USAGE_TABLE)->execute(); // For each user, count the number of files, folders, and bytes, then // update the usage table. $userIds = \Drupal::entityQuery( 'user' )->execute(); foreach ( $userIds as $uid ) { $nFolders = FolderShare::countNumberOfFolders( $uid ); $nFiles = FolderShare::countNumberOfFiles( $uid ); $nBytes = FolderShare::countNumberOfBytes( $uid ); // Add a new entry. $query = $connection ->insert(self::USAGE_TABLE); $query ->fields( [ 'uid' => $uid , 'nFolders' => $nFolders , 'nFiles' => $nFiles , 'nBytes' => $nBytes , ]); $query ->execute(); } // UNLOCK. \Drupal::lock()->release( 'foldershare_usage_lock' ); // Update the stored date. \Drupal::state()->set( 'foldershare.usage_last' , '@' . (string) time()); ManageLog::notice( 'Usage statistics updated' ); return TRUE; } /*-------------------------------------------------------------------- * * Totals. * *-------------------------------------------------------------------*/ /** * Returns the total number of bytes. * * The returned value only includes storage space used for files. * Any storage space required in the database for folder or file * metadata is not included. * * @return int * The total number of bytes. * * @see FolderShare::countNumberOfBytes() */ public static function getNumberOfBytes() { return FolderShare::countNumberOfBytes(); } /** * Returns the total number of folders. * * @return int * The total number of folders. * * @see FolderShare::countNumberOfFolders() */ public static function getNumberOfFolders() { return FolderShare::countNumberOfFolders(); } /** * Returns the total number of files. * * @return int * The total number of files. * * @see FolderShare::countNumberOfFiles() */ public static function getNumberOfFiles() { return FolderShare::countNumberOfFiles(); } /*--------------------------------------------------------------------- * * Update scheduling. * *---------------------------------------------------------------------*/ /** * Returns the usage update task run interval. * * The run interval indicates the time between execution of the usage * updating scheduled task. Known values are: * * - 'manual' = the table is only updated manually. * - 'hourly' = the table is updated hourly. * - 'daily' = the table is updated daily. * - 'weekly' = the table is updated weekly. * * @return string * Returns the run interval setting. * * @see \Drupal\foldershare\Settings::getUsageUpdateInterval() */ public static function getIndexInterval() { return Settings::getUsageUpdateInterval(); } /** * Returns the usage update task run interval in seconds. * * The current run interval is interpreted to compute and return the * interval time in seconds. * * @return int * Returns the run interval in seconds. Zero is returned if the * interval is 'manual'. * * @see ::getIndexInterval() * @see \Drupal\foldershare\Settings::getUsageUpdateInterval() */ private static function getIndexIntervalSeconds() { switch (self::getIndexInterval()) { default : case 'manual' : // No update task. return 0; case 'hourly' : // 60 minutes/hour * 60 seconds/minute. return (60 * 60); case 'daily' : // 24 hours/day * 60 minutes/hour * 60 seconds/minute. return (24 * 60 * 60); case 'weekly' : // 7 days/week * 24 hours/day * 60 minutes/hour * 60 seconds/minute. return (7 * 24 * 60 * 60); } } /** * Schedules usage statistics updates. * * <B>This method is internal and strictly for use by the FolderShare * module itself.</B> * * The current usage updating task, if any, is deleted and a new task * scheduled, if the current interval is not 'manual'. * * @see ::getIndexInterval() * @see ::taskUpdateUsage() * @see \Drupal\foldershare\Settings::getUsageUpdateInterval() */ public static function scheduleUsageUpdate() { // If a task is already scheduled, delete it first. FolderShareScheduledTask::deleteTasks( '\Drupal\foldershare\ManageUsageStatistics::taskUpdateUsage' ); $seconds = self::getIndexIntervalSeconds(); if ( $seconds === 0) { // There is no scheduled update task. return ; } // Schedule a new task with the current interval. FolderShareScheduledTask::createTask( time() + $seconds , '\Drupal\foldershare\ManageUsageStatistics::taskUpdateUsage' , (int) \Drupal::currentUser()->id(), NULL, time(), self::getIndexInterval() . ' usage table update' , 0); } /*--------------------------------------------------------------------- * * Usage update task. * *---------------------------------------------------------------------*/ /** * Updates the usage table as a scheduled task. * * <B>This method is internal and strictly for use by the FolderShare * module itself.</B> * * The task updates the usage table. * * @param int $requester * The user ID of the user that requested the update. This is ignored. * @param array $parameters * The queued task's parameters. This is ignored. * @param int $started * The timestamp of the start date & time for an operation that causes * a chain of tasks. * @param string $comments * A comment on the current task. * @param int $executionTime * The accumulated total execution time of the task chain, in seconds. */ public static function taskUpdateUsage( int $requester , array $parameters , int $started , string $comments , int $executionTime ) { $seconds = self::getIndexIntervalSeconds(); if ( $seconds === 0) { // There is no scheduled update task. return ; } // Schedule the next task with the current interval. FolderShareScheduledTask::createTask( time() + $seconds , '\Drupal\foldershare\ManageUsageStatistics::taskUpdateUsage' , $requester , NULL, time(), self::getIndexInterval() . ' usage table update' , 0); // Update the usage table. self::updateUsage(); } } |