QA fixes
[civicrm-core.git] / CRM / Core / Resources.php
index e7bcf5046ce6dfd5f9a1dd53d43b464c581cb069..af9c6932fbeb505d5bff8f184365445bf505312e 100644 (file)
@@ -210,24 +210,41 @@ class CRM_Core_Resources {
   }
 
   /**
-   * Add JavaScript variables to the global CRM object.
+   * Add JavaScript variables to CRM.vars
    *
    * Example:
    * From the server:
-   * CRM_Core_Resources::singleton()->addSetting(array('myNamespace' => array('foo' => 'bar')));
-   * From javascript:
-   * CRM.myNamespace.foo // "bar"
+   * CRM_Core_Resources::singleton()->addVars('myNamespace', array('foo' => 'bar'));
+   * Access var from javascript:
+   * CRM.vars.myNamespace.foo // "bar"
    *
    * @see http://wiki.civicrm.org/confluence/display/CRMDOC/Javascript+Reference
    *
+   * @param string $nameSpace - usually the name of your extension
+   * @param array $vars
+   * @return CRM_Core_Resources
+   */
+  public function addVars($nameSpace, $vars) {
+    $existing = CRM_Utils_Array::value($nameSpace, CRM_Utils_Array::value('vars', $this->settings), array());
+    $vars = $this->mergeSettings($existing, $vars);
+    $this->addSetting(array('vars' => array($nameSpace => $vars)));
+    return $this;
+  }
+
+  /**
+   * Add JavaScript variables to the root of the CRM object.
+   * This function is usually reserved for low-level system use.
+   * Extensions and components should generally use addVars instead.
+   *
    * @param $settings array
    * @return CRM_Core_Resources
    */
   public function addSetting($settings) {
     $this->settings = $this->mergeSettings($this->settings, $settings);
     if (!$this->addedSettings) {
+      $region = self::isAjaxMode() ? 'ajax-snippet' : 'html-header';
       $resources = $this;
-      CRM_Core_Region::instance('html-header')->add(array(
+      CRM_Core_Region::instance($region)->add(array(
         'callback' => function(&$snippet, &$html) use ($resources) {
           $html .= "\n" . $resources->renderSetting();
         },
@@ -284,7 +301,14 @@ class CRM_Core_Resources {
    * @return string
    */
   public function renderSetting() {
-    $js = 'var CRM = ' . json_encode($this->getSettings()) . ';';
+    // On a standard page request we construct the CRM object from scratch
+    if (!self::isAjaxMode()) {
+      $js = 'var CRM = ' . json_encode($this->getSettings()) . ';';
+    }
+    // For an ajax request we append to it
+    else {
+      $js = 'CRM.$.extend(true, CRM, ' . json_encode($this->getSettings()) . ');';
+    }
     return sprintf("<script type=\"text/javascript\">\n%s\n</script>\n", $js);
   }
 
@@ -426,18 +450,24 @@ class CRM_Core_Resources {
 
   /**
    * @param $value
+   * @return CRM_Core_Resources
    */
   public function setCacheCode($value) {
     $this->cacheCode = $value;
     if ($this->cacheCodeKey) {
       CRM_Core_BAO_Setting::setItem($value, CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, $this->cacheCodeKey);
     }
+    return $this;
   }
 
+  /**
+   * @return CRM_Core_Resources
+   */
   public function resetCacheCode() {
     $this->setCacheCode(CRM_Utils_String::createRandom(5, CRM_Utils_String::ALPHANUMERIC));
     // Also flush cms resource cache if needed
     CRM_Core_Config::singleton()->userSystem->clearResourceCache();
+    return $this;
   }
 
   /**
@@ -452,7 +482,7 @@ class CRM_Core_Resources {
    * @access public
    */
   public function addCoreResources($region = 'html-header') {
-    if (!isset($this->addedCoreResources[$region])) {
+    if (!isset($this->addedCoreResources[$region]) && !self::isAjaxMode()) {
       $this->addedCoreResources[$region] = TRUE;
       $config = CRM_Core_Config::singleton();
 
@@ -470,7 +500,7 @@ class CRM_Core_Resources {
       }
 
       // Dynamic localization script
-      $this->addScriptUrl($this->addLocalizationJs(), $jsWeight++, $region);
+      $this->addScriptUrl(CRM_Utils_System::url('civicrm/ajax/l10n-js/' . $config->lcMessages, array('r' => $this->getCacheCode())), $jsWeight++, $region);
 
       // Add global settings
       $settings = array('config' => array(
@@ -479,7 +509,7 @@ class CRM_Core_Resources {
       ));
       // Disable profile creation if user lacks permission
       if (!CRM_Core_Permission::check('edit all contacts') && !CRM_Core_Permission::check('add contacts')) {
-        $settings['profileCreate'] = FALSE;
+        $settings['config']['entityRef']['contactCreate'] = FALSE;
       }
       $this->addSetting($settings);
 
@@ -518,9 +548,11 @@ class CRM_Core_Resources {
 
   /**
    * Flushes cached translated strings
+   * @return CRM_Core_Resources
    */
   public function flushStrings() {
     $this->cache->flush();
+    return $this;
   }
 
   /**
@@ -549,35 +581,25 @@ class CRM_Core_Resources {
     $this->addString($stringsByFile[$file]);
   }
 
-  /**
-   * Add dynamic l10n js
-   *
-   * @return string URL of JS file
-   */
-  private function addLocalizationJs() {
-    $config = CRM_Core_Config::singleton();
-    $fileName = 'l10n-' . $config->lcMessages . '.js';
-    if (!is_file(CRM_Utils_File::dynamicResourcePath($fileName))) {
-      CRM_Utils_File::addDynamicResource($fileName, $this->createLocalizationJs());
-    }
-    // Dynamic localization script
-    return CRM_Utils_File::dynamicResourceUrl($fileName);
-  }
-
   /**
    * Create dynamic script for localizing js widgets
    *
    * @return string javascript content
    */
-  private function createLocalizationJs() {
+  static function outputLocalizationJS() {
+    CRM_Core_Page_AJAX::setJsHeaders();
     $config = CRM_Core_Config::singleton();
     $vars = array(
       'moneyFormat' => json_encode(CRM_Utils_Money::format(1234.56)),
       'contactSearch' => json_encode($config->includeEmailInName ? ts('Start typing a name or email...') : ts('Start typing a name...')),
       'otherSearch' => json_encode(ts('Enter search term...')),
-      'contactCreate' => CRM_Core_BAO_UFGroup::getCreateLinks(),
+      'entityRef' => array(
+        'contactCreate' => CRM_Core_BAO_UFGroup::getCreateLinks(),
+        'filters' => self::getEntityRefFilters(),
+      ),
     );
-    return CRM_Core_Smarty::singleton()->fetchWith('CRM/common/localization.js.tpl', $vars);
+    print CRM_Core_Smarty::singleton()->fetchWith('CRM/common/l10n.js.tpl', $vars);
+    CRM_Utils_System::civiExit();
   }
 
   /**
@@ -634,6 +656,11 @@ class CRM_Core_Resources {
       $items[] = "js/jquery/jquery.crmeditable.js";
     }
 
+    // JS for multilingual installations
+    if (!empty($config->languageLimit) && count($config->languageLimit) > 1 && CRM_Core_Permission::check('translate CiviCRM')) {
+      $items[] = "js/crm.multilingual.js";
+    }
+
     // Enable administrators to edit option lists in a dialog
     if (CRM_Core_Permission::check('administer CiviCRM') && $this->ajaxPopupsEnabled) {
       $items[] = "js/crm.optionEdit.js";
@@ -652,6 +679,55 @@ class CRM_Core_Resources {
         }
       }
     }
+
+    // CMS-specific resources
+    $config->userSystem->appendCoreResources($items);
+
     return $items;
   }
+
+  /**
+   * @return bool - is this page request an ajax snippet?
+   */
+  static function isAjaxMode() {
+    return in_array(CRM_Utils_Array::value('snippet', $_REQUEST), array(CRM_Core_Smarty::PRINT_SNIPPET, CRM_Core_Smarty::PRINT_NOFORM, CRM_Core_Smarty::PRINT_JSON));
+  }
+
+  /**
+   * 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
+   */
+  static function getEntityRefFilters() {
+    $filters = array();
+
+    $filters['event'] = array(
+      array('key' => 'event_type_id', 'value' => ts('Event Type')),
+      array('key' => 'start_date', 'value' => ts('Start Date'), 'options' => array(
+        array('key' => '{">":"now"}', 'value' => ts('Upcoming')),
+        array('key' => '{"BETWEEN":["now - 3 month","now"]}', 'value' => ts('Past 3 Months')),
+        array('key' => '{"BETWEEN":["now - 6 month","now"]}', 'value' => ts('Past 6 Months')),
+        array('key' => '{"BETWEEN":["now - 1 year","now"]}', 'value' => ts('Past Year')),
+      )),
+    );
+
+    $filters['activity'] = array(
+      array('key' => 'activity_type_id', 'value' => ts('Activity Type')),
+      array('key' => 'status_id', 'value' => ts('Activity Status')),
+    );
+
+    $contactTypes = CRM_Utils_Array::makeNonAssociative(CRM_Contact_BAO_ContactType::getSelectElements(FALSE, TRUE, '.'));
+    $filters['contact'] = array(
+      array('key' => 'contact_type', 'value' => ts('Contact Type'), 'options' => $contactTypes),
+      array('key' => 'group', 'value' => ts('Group'), 'entity' => 'group_contact'),
+      array('key' => 'tag', 'value' => ts('Tag'), 'entity' => 'entity_tag'),
+      array('key' => 'state_province', 'value' => ts('State/Province'), 'entity' => 'address'),
+      array('key' => 'country', 'value' => ts('Country'), 'entity' => 'address'),
+      array('key' => 'gender_id', 'value' => ts('Gender')),
+      array('key' => 'is_deceased', 'value' => ts('Deceased')),
+    );
+
+    return $filters;
+  }
 }