Move jQuery.validate to bower
[civicrm-core.git] / CRM / Core / Resources.php
index 55cb7f856b67b2dad27f5516fe6f9a072a406b6e..89bcdd9632f0b207b649047a0ea2a833ee0c1bd7 100644 (file)
@@ -58,9 +58,9 @@ class CRM_Core_Resources {
   private $extMapper = NULL;
 
   /**
-   * @var CRM_Utils_Cache_Interface
+   * @var CRM_Core_Resources_Strings
    */
-  private $cache = NULL;
+  private $strings = NULL;
 
   /**
    * @var array free-form data tree
@@ -99,7 +99,7 @@ class CRM_Core_Resources {
   public $ajaxPopupsEnabled;
 
   /**
-   * Get or set the single instance of CRM_Core_Resources
+   * Get or set the single instance of CRM_Core_Resources.
    *
    * @param CRM_Core_Resources $instance
    *   New copy of the manager.
@@ -125,7 +125,7 @@ class CRM_Core_Resources {
   }
 
   /**
-   * Construct a resource manager
+   * Construct a resource manager.
    *
    * @param CRM_Extension_Mapper $extMapper
    *   Map extension names to their base path or URLs.
@@ -135,7 +135,7 @@ class CRM_Core_Resources {
    */
   public function __construct($extMapper, $cache, $cacheCodeKey = NULL) {
     $this->extMapper = $extMapper;
-    $this->cache = $cache;
+    $this->strings = new CRM_Core_Resources_Strings($cache);
     $this->cacheCodeKey = $cacheCodeKey;
     if ($cacheCodeKey !== NULL) {
       $this->cacheCode = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, $cacheCodeKey);
@@ -148,6 +148,29 @@ class CRM_Core_Resources {
     );
   }
 
+  /**
+   * Export permission data to the client to enable smarter GUIs.
+   *
+   * Note: Application security stems from the server's enforcement
+   * of the security logic (e.g. in the API permissions). There's no way
+   * the client can use this info to make the app more secure; however,
+   * it can produce a better-tuned (non-broken) UI.
+   *
+   * @param array $permNames
+   *   List of permission names to check/export.
+   * @return CRM_Core_Resources
+   */
+  public function addPermissions($permNames) {
+    $permNames = (array) $permNames;
+    $perms = array();
+    foreach ($permNames as $permName) {
+      $perms[$permName] = CRM_Core_Permission::check($permName);
+    }
+    return $this->addSetting(array(
+      'permissions' => $perms,
+    ));
+  }
+
   /**
    * Add a JavaScript file to the current page using <SCRIPT SRC>.
    *
@@ -159,13 +182,18 @@ class CRM_Core_Resources {
    *   relative weight within a given region.
    * @param string $region
    *   location within the file; 'html-header', 'page-header', 'page-footer'.
-   * @param $translate , whether to parse this file for strings enclosed in ts()
+   * @param bool|string $translate
+   *   Whether to load translated strings for this file. Use one of:
+   *   - FALSE: Do not load translated strings.
+   *   - TRUE: Load translated strings. Use the $ext's default domain.
+   *   - string: Load translated strings. Use a specific domain.
    *
    * @return CRM_Core_Resources
    */
   public function addScriptFile($ext, $file, $weight = self::DEFAULT_WEIGHT, $region = self::DEFAULT_REGION, $translate = TRUE) {
     if ($translate) {
-      $this->translateScript($ext, $file);
+      $domain = ($translate === TRUE) ? $ext : $translate;
+      $this->addString($this->strings->get($domain, $this->getPath($ext, $file), 'text/javascript'), $domain);
     }
     // Look for non-minified version if we are in debug mode
     if (CRM_Core_Config::singleton()->debug && strpos($file, '.min.js') !== FALSE) {
@@ -281,7 +309,7 @@ class CRM_Core_Resources {
   }
 
   /**
-   * Helper fn for addSettingsFactory
+   * Helper fn for addSettingsFactory.
    */
   public function getSettings() {
     $result = $this->settings;
@@ -308,7 +336,7 @@ class CRM_Core_Resources {
   }
 
   /**
-   * Helper fn for addSetting
+   * Helper fn for addSetting.
    * Render JavaScript variables for the global CRM object.
    *
    * @return string
@@ -352,15 +380,23 @@ class CRM_Core_Resources {
    * And from javascript access it at CRM.myNamespace.myString
    *
    * @param string|array $text
+   * @param string|NULL $domain
    * @return CRM_Core_Resources
    */
-  public function addString($text) {
+  public function addString($text, $domain = 'civicrm') {
     foreach ((array) $text as $str) {
-      $translated = ts($str);
+      $translated = ts($str, array(
+        'domain' => ($domain == 'civicrm') ? NULL : array($domain, NULL),
+        'raw' => TRUE,
+      ));
+
       // We only need to push this string to client if the translation
       // is actually different from the original
       if ($translated != $str) {
-        $this->addSetting(array('strings' => array($str => $translated)));
+        $bucket = $domain == 'civicrm' ? 'strings' : 'strings::' . $domain;
+        $this->addSetting(array(
+          $bucket => array($str => $translated),
+        ));
       }
     }
     return $this;
@@ -427,18 +463,21 @@ class CRM_Core_Resources {
   }
 
   /**
-   * Determine file path of a resource provided by an extension
+   * Determine file path of a resource provided by an extension.
    *
    * @param string $ext
    *   extension name; use 'civicrm' for core.
-   * @param string $file
+   * @param string|NULL $file
    *   file path -- relative to the extension base dir.
    *
    * @return bool|string
    *   full file path or FALSE if not found
    */
-  public function getPath($ext, $file) {
+  public function getPath($ext, $file = NULL) {
     // TODO consider caching results
+    if ($file === NULL) {
+      return $this->extMapper->keyToBasePath($ext);
+    }
     $path = $this->extMapper->keyToBasePath($ext) . '/' . $file;
     if (is_file($path)) {
       return $path;
@@ -447,7 +486,7 @@ class CRM_Core_Resources {
   }
 
   /**
-   * Determine public URL of a resource provided by an extension
+   * Determine public URL of a resource provided by an extension.
    *
    * @param string $ext
    *   extension name; use 'civicrm' for core.
@@ -468,6 +507,40 @@ class CRM_Core_Resources {
     return $this->extMapper->keyToUrl($ext) . '/' . $file;
   }
 
+  /**
+   * Evaluate a glob pattern in the context of a particular extension.
+   *
+   * @param string $ext
+   *   Extension name; use 'civicrm' for core.
+   * @param string|array $patterns
+   *   Glob pattern; e.g. "*.html".
+   * @param null|int $flags
+   *   See glob().
+   * @return array
+   *   List of matching files, relative to the extension base dir.
+   * @see glob()
+   */
+  public function glob($ext, $patterns, $flags = NULL) {
+    $path = $this->getPath($ext);
+    $patterns = (array) $patterns;
+    $files = array();
+    foreach ($patterns as $pattern) {
+      if ($pattern{0} === '/') {
+        // Absolute path.
+        $files = array_merge($files, (array) glob($pattern, $flags));
+      }
+      else {
+        // Relative path.
+        $files = array_merge($files, (array) glob("$path/$pattern", $flags));
+      }
+    }
+    sort($files); // Deterministic order.
+    $files = array_unique($files);
+    return array_map(function ($file) use ($path) {
+      return CRM_Utils_File::relativize($file, "$path/");
+    }, $files);
+  }
+
   /**
    * @return string
    */
@@ -517,7 +590,7 @@ class CRM_Core_Resources {
       foreach ($this->coreResourceList() as $file) {
         if (substr($file, -2) == 'js') {
           // Don't bother  looking for ts() calls in packages, there aren't any
-          $translate = (substr($file, 0, 9) != 'packages/');
+          $translate = (substr($file, 0, 3) == 'js/');
           $this->addScriptFile('civicrm', $file, $jsWeight++, $region, $translate);
         }
         else {
@@ -531,7 +604,6 @@ class CRM_Core_Resources {
       // Add global settings
       $settings = array(
         'config' => array(
-          'ajaxPopupsEnabled' => $this->ajaxPopupsEnabled,
           'isFrontend' => $config->userFrameworkFrontend,
         ),
       );
@@ -575,41 +647,19 @@ class CRM_Core_Resources {
   }
 
   /**
-   * Flushes cached translated strings
+   * Flushes cached translated strings.
    * @return CRM_Core_Resources
    */
   public function flushStrings() {
-    $this->cache->flush();
+    $this->strings->flush();
     return $this;
   }
 
   /**
-   * Translate strings in a javascript file
-   *
-   * @param string $ext
-   *   extension name.
-   * @param string $file
-   *   file path.
-   * @return void
-   */
-  private function translateScript($ext, $file) {
-    // For each extension, maintain one cache record which
-    // includes parsed (translatable) strings for all its JS files.
-    $stringsByFile = $this->cache->get($ext); // array($file => array(...strings...))
-    if (!$stringsByFile) {
-      $stringsByFile = array();
-    }
-    if (!isset($stringsByFile[$file])) {
-      $filePath = $this->getPath($ext, $file);
-      if ($filePath && is_readable($filePath)) {
-        $stringsByFile[$file] = CRM_Utils_JS::parseStrings(file_get_contents($filePath));
-      }
-      else {
-        $stringsByFile[$file] = array();
-      }
-      $this->cache->set($ext, $stringsByFile);
-    }
-    $this->addString($stringsByFile[$file]);
+   * @return CRM_Core_Resources_Strings
+   */
+  public function getStrings() {
+    return $this->strings;
   }
 
   /**
@@ -626,13 +676,14 @@ class CRM_Core_Resources {
         'contactCreate' => CRM_Core_BAO_UFGroup::getCreateLinks(),
         'filters' => self::getEntityRefFilters(),
       ),
+      'ajaxPopupsEnabled' => self::singleton()->ajaxPopupsEnabled,
     );
     print CRM_Core_Smarty::singleton()->fetchWith('CRM/common/l10n.js.tpl', $vars);
     CRM_Utils_System::civiExit();
   }
 
   /**
-   * List of core resources we add to every CiviCRM page
+   * List of core resources we add to every CiviCRM page.
    *
    * @return array
    */
@@ -645,13 +696,13 @@ class CRM_Core_Resources {
     // Scripts needed by everyone, everywhere
     // FIXME: This is too long; list needs finer-grained segmentation
     $items = array(
-      "packages/jquery/jquery-1.11.1$min.js",
-      "packages/jquery/jquery-ui/jquery-ui$min.js",
-      "packages/jquery/jquery-ui/jquery-ui$min.css",
-      "packages/backbone/lodash.compat$min.js",
+      "bower_components/jquery/dist/jquery.min.js",
+      "bower_components/jquery-ui/jquery-ui.min.js",
+      "bower_components/jquery-ui/themes/smoothness/jquery-ui$min.css",
+      "bower_components/lodash-compat/lodash.min.js",
       "packages/jquery/plugins/jquery.mousewheel$min.js",
-      "packages/jquery/plugins/select2/select2$min.js",
-      "packages/jquery/plugins/select2/select2.css",
+      "bower_components/select2/select2$min.js",
+      "bower_components/select2/select2.css",
       "packages/jquery/plugins/jquery.tableHeader.js",
       "packages/jquery/plugins/jquery.textarearesizer.js",
       "packages/jquery/plugins/jquery.form$min.js",
@@ -659,7 +710,7 @@ class CRM_Core_Resources {
       "packages/jquery/plugins/jquery.blockUI$min.js",
       "packages/jquery/plugins/DataTables/media/js/jquery.dataTables$min.js",
       "packages/jquery/plugins/DataTables/media/css/jquery.dataTables$min.css",
-      "packages/jquery/plugins/jquery.validate$min.js",
+      "bower_components/jquery-validation/dist/jquery.validate$min.js",
       "packages/jquery/plugins/jquery.ui.datepicker.validation.pack.js",
       "js/Common.js",
       "js/crm.ajax.js",
@@ -668,7 +719,7 @@ class CRM_Core_Resources {
     // These scripts are only needed by back-office users
     if (CRM_Core_Permission::check('access CiviCRM')) {
       $items[] = "packages/jquery/plugins/jquery.menu$min.js";
-      $items[] = "packages/jquery/css/menu.css";
+      $items[] = "css/navigation.css";
       $items[] = "packages/jquery/plugins/jquery.jeditable$min.js";
       $items[] = "packages/jquery/plugins/jquery.notify$min.js";
       $items[] = "js/jquery/jquery.crmeditable.js";
@@ -688,7 +739,7 @@ class CRM_Core_Resources {
     if ($config->lcMessages && $config->lcMessages != 'en_US') {
       // Search for i18n file in order of specificity (try fr-CA, then fr)
       list($lang) = explode('_', $config->lcMessages);
-      $path = "packages/jquery/jquery-ui/i18n";
+      $path = "bower_components/jquery-ui/ui/i18n";
       foreach (array(str_replace('_', '-', $config->lcMessages), $lang) as $language) {
         $localizationFile = "$path/datepicker-{$language}.js";
         if ($this->getPath('civicrm', $localizationFile)) {
@@ -717,7 +768,7 @@ class CRM_Core_Resources {
   }
 
   /**
-   * Provide a list of available entityRef filters
+   * Provide a list of available entityRef filters.
    * FIXME: This function doesn't really belong in this class
    * @TODO: Provide a sane way to extend this list for other entities - a hook or??
    * @return array