generateFileHash() and validateFileHash() should be colocated
[civicrm-core.git] / CRM / Core / BAO / File.php
index d02ec078ce5db563864f8c9148e5cfac09e5a982..4468dd8c0f2da465d58767675902703c09170074 100644 (file)
@@ -773,12 +773,44 @@ AND       CEF.entity_id    = %2";
    * @param int $fid file ID
    * @return string
    */
-  public static function generateFileHash($eid = NULL, $fid = NULL) {
+  public static function generateFileHash($eid = NULL, $fid = NULL, $genTs = NULL, $life = NULL) {
     // Use multiple (but stable) inputs for hash information.
     $siteKey = defined('CIVICRM_SITE_KEY') ? CIVICRM_SITE_KEY : 'NO_SITE_KEY';
+
+    if (!$genTs) {
+      $genTs = time();
+    }
+    if (!$life) {
+      $life = 24 * 2;
+    }
     // Trim 8 chars off the string, make it slightly easier to find
     // but reveals less information from the hash.
-    return substr(md5("{$siteKey}_{$eid}_{$fid}"), 8);
+    $cs = hash_hmac('sha256', "{$fid}_{$life}", $siteKey);
+    return "{$cs}_{$genTs}_{$life}";
+  }
+
+  /**
+   * Validate a file Hash
+   * @param string $hash
+   * @param int $eid Entity Id the file is attached to
+   * @param int $fid File Id
+   * @return bool
+   */
+  public static function validateFileHash($hash, $eid, $fid) {
+    $input = CRM_Utils_System::explode('_', $hash, 3);
+    $inputTs = CRM_Utils_Array::value(1, $input);
+    $inputLF = CRM_Utils_Array::value(2, $input);
+    $testHash = CRM_Core_BAO_File::generateFileHash($eid, $fid, $inputTs, $inputLF);
+    if (hash_equals($testHash, $hash)) {
+      $now = time();
+      if ($inputTs + ($inputLF * 60 * 60) >= $now) {
+        return TRUE;
+      }
+      else {
+        return FALSE;
+      }
+    }
+    return FALSE;
   }
 
 }