Improved caching system.
authorVimal Joseph <vimal.joseph@zyxware.com>
Tue, 18 Nov 2014 20:38:46 +0000 (02:08 +0530)
committerVimal Joseph <vimal.joseph@zyxware.com>
Tue, 18 Nov 2014 20:38:46 +0000 (02:08 +0530)
Improved the structure of caching system.
Fixed minor bugs in the caching system.

12 files changed:
CRM/Wci/BAO/WidgetCache.php
CRM/Wci/DAO/WidgetCache.php
CRM/Wci/Form/CreateWidget.php
CRM/Wci/Form/WCISettings.php
CRM/Wci/Upgrader.php
CRM/Wci/WidgetCode.php
extern/embed.php
info.xml
settings/wci.setting.php
sql/install.sql
templates/CRM/Wci/Form/CreateWidget.tpl
templates/CRM/Wci/Form/NewEmbedCode.tpl

index f33f5d1a377fecdad15f85ddbd54210d3a1bb671..513bc5e0b6004b236044775e12c42bbdd175aea6 100644 (file)
@@ -113,37 +113,39 @@ class CRM_Wci_BAO_WidgetCache extends CRM_Wci_DAO_WidgetCache {
   }
 
   public static function setWidgetCache($widgetId, $code) {
-    $query = "DELETE from civicrm_wci_widget_cache WHERE widget_id = %1";
-    CRM_Core_DAO::executeQuery($query, array(1=>array($widgetId, 'Integer')), 
-        TRUE, 'CRM_Wci_DAO_WidgetCache');
-        
-    $query = "INSERT into civicrm_wci_widget_cache (widget_id, widget_code) VALUES (%1, %2)";
-    $params = array(1=>array($widgetId, 'Integer'),
-          2=>array($code, 'String'),);
+    $cacheTime = civicrm_api3('setting', 'getValue',
+      array('group' => 'Wci Preference', 'name' => 'widget_cache_timeout'));
+    $expire_on = time() + ($cacheTime * 60);
+    $query = "INSERT INTO civicrm_wci_widget_cache (widget_id, widget_code, expire)
+    VALUES (%1, %2, %3)
+    ON DUPLICATE KEY UPDATE widget_id = %1, widget_code = %2, expire = %3";
+    $params = array(
+      1 => array($widgetId, 'Integer'),
+      2 => array($code, 'String'),
+      3 => array($expire_on, 'Integer')
+    );
     CRM_Core_DAO::executeQuery($query, $params, TRUE, 'CRM_Wci_DAO_WidgetCache');
   }
-  public static function getCurrentTsDiff($widgetId) {
-    $tsDiff = 0;
-    $query = "SELECT TIMESTAMPDIFF(MINUTE, `ts`, NOW()) as tsDiff FROM 
-      civicrm_wci_widget_cache where widget_id = %1";
-    $dao = CRM_Core_DAO::executeQuery($query, array(1=>array($widgetId, 'Integer')), 
-        TRUE, 'CRM_Wci_DAO_WidgetCache');
-    if ($dao->fetch()) {
-      $tsDiff = $dao->tsDiff;
-    } else {
-      $tsDiff = PHP_INT_MAX;
-    }
-    return $tsDiff;
-  }
   
   public static function getWidgetCache($widgetId) {
     $code = "";
-    $query = "SELECT widget_code FROM civicrm_wci_widget_cache where widget_id = %1";
-    $dao = CRM_Core_DAO::executeQuery($query, array(1=>array($widgetId, 'Integer')), 
-        TRUE, 'CRM_Wci_DAO_WidgetCache');
+    $query = "SELECT widget_code FROM civicrm_wci_widget_cache where widget_id = %1
+    AND expire >= %2";
+    $cacheTime = civicrm_api3('setting', 'getValue',
+      array('group' => 'Wci Preference', 'name' => 'widget_cache_timeout'));
+    $expire_on = time() + ($cacheTime * 60);
+    $dao = CRM_Core_DAO::executeQuery($query, array(1 => array($widgetId, 'Integer'),
+      2 => array($expire_on, 'Integer')), TRUE, 'CRM_Wci_DAO_WidgetCache');
     if ($dao->fetch()) {
       $code = $dao->widget_code;
     }  
     return $code;
   }
+
+  public static function deleteWidgetCache($widgetId) {
+    $code = "";
+    $query = "DELETE FROM civicrm_wci_widget_cache where widget_id = %1";
+    $dao = CRM_Core_DAO::executeQuery($query,
+      array(1 => array($widgetId, 'Integer')), TRUE, 'CRM_Wci_DAO_WidgetCache');
+  }
 }
index 379385e2eb6fe7d11e71e9d74be9f7f07e7c8ce6..7e8b2f6d205f1cf6d87f586706c258391b46fc3e 100644 (file)
@@ -134,16 +134,10 @@ class CRM_Wci_DAO_WidgetCache extends CRM_Core_DAO
   {
     if (!(self::$_fields)) {
       self::$_fields = array(
-        'widget_cache_id' => array(
-          'name' => 'id',
-          'type' => CRM_Utils_Type::T_INT,
-          'title' => ts('cahce Id', array('domain' => 'org.civicrm.wci')) ,
-          'required' => true,
-        ) ,
         'widget_id' => array(
           'name' => 'widget_id',
           'type' => CRM_Utils_Type::T_INT,
-          'required' => false,
+          'required' => true,
         ) ,
         'widget_code' => array(
           'name' => 'widget_code',
@@ -151,12 +145,11 @@ class CRM_Wci_DAO_WidgetCache extends CRM_Core_DAO
           'title' => ts('widget code', array('domain' => 'org.civicrm.wci')) ,
           'required' => false,
         ) ,
-        'ts' => array(
+        'expire' => array(
           'name' => 'ts',
-          'type' => CRM_Utils_Type::T_TIMESTAMP,
+          'type' => CRM_Utils_Type::T_INT,
           'title' => ts('timestamp', array('domain' => 'org.civicrm.wci')) ,
           'required' => false,
-          'maxlength' => 64,
         ) ,
 
 
@@ -175,10 +168,9 @@ class CRM_Wci_DAO_WidgetCache extends CRM_Core_DAO
   {
     if (!(self::$_fieldKeys)) {
       self::$_fieldKeys = array(
-        'id' => 'widget_cache_id',
         'widget_id' => 'widget_id',
         'widget_code' => 'widget_code',
-        'ts' => 'ts',
+        'expire' => 'expire',
       );
     }
     return self::$_fieldKeys;
index 3acfed0d24e9731b27c529533120d11591db743f..e0b357935c78b6009e807e69b55a46aec962f327 100644 (file)
@@ -345,10 +345,16 @@ where w.id=" . $this->_id;*/
       CRM_Core_DAO::executeQuery($sql, $params);
       CRM_Core_DAO::executeQuery("SET foreign_key_checks = 1;");
       $transaction->commit();
+      if (isset($this->_id)) {
+        $widget_id = $this->_id;
+        CRM_Wci_BAO_WidgetCache::deleteWidgetCache($widget_id);
+      }
+      else {
+        $widget_id = CRM_Core_DAO::singleValueQuery('SELECT LAST_INSERT_ID()');
+      }
       CRM_Core_Session::setStatus(ts('Widget created successfuly'), '', 'success');
+      
       if(isset($_REQUEST['_qf_CreateWidget_next'])) {
-        (isset($this->_id)) ? $widget_id = $this->_id : 
-              $widget_id = CRM_Core_DAO::singleValueQuery('SELECT LAST_INSERT_ID()');
         CRM_Utils_System::redirect('?action=update&reset=1&id=' . $widget_id);
       } else {
         CRM_Utils_System::redirect('widget?reset=1');
index 7e5001c8e6990d4fecccd34ba3184b4bc50f2f9c..0a028ba4e75511b1ea907c8d0d6549563c48fb0e 100644 (file)
@@ -9,24 +9,6 @@ require_once 'CRM/Core/Form.php';
  */
 class CRM_Wci_Form_WCISettings extends CRM_Core_Form {
   function buildQuickForm() {
-
-    // add form elements
-    /*$this->add(
-      'select', // field type
-      'default_profile', // field name
-      'Default profile', // field label
-      $this->getProfiles(), // list of options
-      true // is required
-    );*/
-   
-    /*$this->add(
-      'select', // field type
-      'default_widget', // field name
-      'Default widget', // field label
-      $this->getWidgets(), // list of options
-      false // is required
-    );*/
-    
     $this->add('text', 'default_profile', ts('Default profile'),true)->setSize(45);
     $this->add('text', 'widget_cache_timeout', ts('Widget cache timeout'),true)->setSize(45);
     $this->addButtons(array(
@@ -36,10 +18,9 @@ class CRM_Wci_Form_WCISettings extends CRM_Core_Form {
         'isDefault' => TRUE,
       ),
     ));
-
+$cacheTime = 1;
     $cacheTime = civicrm_api3('setting', 'getValue', array('group' => 'Wci Preference', 'name' => 'widget_cache_timeout'));
-    $defProf = civicrm_api3('setting', 'getValue', array('group' => 'Wci Preference', 'name' => 'default_wci_profile'));
-
+    $defProf =   civicrm_api3('setting', 'getValue', array('group' => 'Wci Preference', 'name' => 'default_wci_profile'));
     /*$this->setDefaults(array(
               'default_widget' => $widgetId));*/
     $this->setDefaults(array(
@@ -58,8 +39,8 @@ class CRM_Wci_Form_WCISettings extends CRM_Core_Form {
   function postProcess() {
     $values = $this->exportValues();
     /*civicrm_api3('setting', 'create', array('domain_id' => 1, 'default_wci_widget' => $values['default_widget'],));*/
-    civicrm_api3('setting', 'create', array('domain_id' => 1, 'default_wci_profile' => $values['default_profile'],));
-    civicrm_api3('setting', 'create', array('domain_id' => 1, 'widget_cache_timeout' => $values['widget_cache_timeout'],));
+    civicrm_api3('setting', 'create', array('sequential' => 1, 'default_wci_profile' => $values['default_profile']));
+    civicrm_api3('setting', 'create', array('sequential' => 1, 'widget_cache_timeout' => $values['widget_cache_timeout']));
     CRM_Core_Session::setStatus(ts('Widget settings are saved to database'), '', 'success');
     parent::postProcess();
   }
index d80fdcca2991e11e719d798e88fe09fdec0f06cc..56635740de3cb942f855dbcbbcbd6de5e254ec0d 100644 (file)
@@ -63,77 +63,14 @@ class CRM_Wci_Upgrader extends CRM_Wci_Upgrader_Base {
   public function upgrade_1001() {
     $this->ctx->log->info('Applying update 1001');
     CRM_Core_DAO::executeQuery('
-      CREATE TABLE IF NOT EXISTS civicrm_wci_widget_cache (
-        id int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT "cache Id.",
-        widget_id int(10) unsigned DEFAULT NULL COMMENT "widget id.",
-        widget_code text DEFAULT NULL COMMENT "Widget code.",
-        ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
-        PRIMARY KEY (`id`)
+      CREATE TABLE IF NOT EXISTS `civicrm_wci_widget_cache` (
+        `widget_id` int(10) unsigned NOT NULL COMMENT "widget id.",
+        `widget_code` text DEFAULT NULL COMMENT "Widget code.",
+        `expire` int(10) DEFAULT 0 COMMENT "A Unix timestamp indicating when the cache entry should expire.",
+        PRIMARY KEY (`widget_id`)
       ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
     ');
     return TRUE;
   }
 
-  /**
-   * Example: Run an external SQL script
-   *
-   * @return TRUE on success
-   * @throws Exception
-  public function upgrade_4201() {
-    $this->ctx->log->info('Applying update 4201');
-    // this path is relative to the extension base dir
-    $this->executeSqlFile('sql/upgrade_4201.sql');
-    return TRUE;
-  } // */
-
-
-  /**
-   * Example: Run a slow upgrade process by breaking it up into smaller chunk
-   *
-   * @return TRUE on success
-   * @throws Exception
-  public function upgrade_4202() {
-    $this->ctx->log->info('Planning update 4202'); // PEAR Log interface
-
-    $this->addTask(ts('Process first step'), 'processPart1', $arg1, $arg2);
-    $this->addTask(ts('Process second step'), 'processPart2', $arg3, $arg4);
-    $this->addTask(ts('Process second step'), 'processPart3', $arg5);
-    return TRUE;
-  }
-  public function processPart1($arg1, $arg2) { sleep(10); return TRUE; }
-  public function processPart2($arg3, $arg4) { sleep(10); return TRUE; }
-  public function processPart3($arg5) { sleep(10); return TRUE; }
-  // */
-
-
-  /**
-   * Example: Run an upgrade with a query that touches many (potentially
-   * millions) of records by breaking it up into smaller chunks.
-   *
-   * @return TRUE on success
-   * @throws Exception
-  public function upgrade_4203() {
-    $this->ctx->log->info('Planning update 4203'); // PEAR Log interface
-
-    $minId = CRM_Core_DAO::singleValueQuery('SELECT coalesce(min(id),0) FROM civicrm_contribution');
-    $maxId = CRM_Core_DAO::singleValueQuery('SELECT coalesce(max(id),0) FROM civicrm_contribution');
-    for ($startId = $minId; $startId <= $maxId; $startId += self::BATCH_SIZE) {
-      $endId = $startId + self::BATCH_SIZE - 1;
-      $title = ts('Upgrade Batch (%1 => %2)', array(
-        1 => $startId,
-        2 => $endId,
-      ));
-      $sql = '
-        UPDATE civicrm_contribution SET foobar = whiz(wonky()+wanker)
-        WHERE id BETWEEN %1 and %2
-      ';
-      $params = array(
-        1 => array($startId, 'Integer'),
-        2 => array($endId, 'Integer'),
-      );
-      $this->addTask($title, 'executeSql', $sql, $params);
-    }
-    return TRUE;
-  } // */
-
 }
index d0751cee7c784e53f5b644263ba9d7bb4c1f7ee0..e53c46051ba42433b34cffc4fbfab4cfd3d23073 100644 (file)
@@ -3,7 +3,7 @@ require_once '../wci-helper-functions.php';
 
 class CRM_Wci_WidgetCode {
 
-  static function get_widget_realtime_code($widgetId, $preview) {
+  static function generate_widget_code($widgetId, $preview = 0) {
     $data = CRM_Wci_BAO_Widget::getWidgetData($widgetId);
     $template = CRM_Core_Smarty::singleton();
     $template->assign('wciform', $data);
@@ -17,27 +17,24 @@ class CRM_Wci_WidgetCode {
       $wcidata = $template->fetch('string:' . html_entity_decode($data['custom_template']));
     }
     $code = json_encode($wcidata);
-    CRM_Wci_BAO_WidgetCache::setWidgetCache($widgetId, $code);
     return $code;
   }
   
-  static function get_widget_code($embedId, $preview=0) {
-    
-    if($preview) {
-      /**On preview time controller is called from create widget 
-          form so id will be widget id */
-      $code = CRM_Wci_WidgetCode::get_widget_realtime_code($embedId, $preview);
-    } else {
+  static function get_widget_code($embedId, $preview = 0) {
+    $code = '';
+    if ($preview) {
+      return CRM_Wci_WidgetCode::generate_widget_code($embedId, $preview);
+    }
+    else {
       $widgetId = CRM_Wci_BAO_EmbedCode::getWidgetId($embedId);
       $code = CRM_Wci_BAO_WidgetCache::getWidgetCache($widgetId);
-
-      $tsDiff = CRM_Wci_BAO_WidgetCache::getCurrentTsDiff($widgetId);
-      $cacheTime = civicrm_api3('setting', 'getValue', 
-          array('group' => 'Wci Preference', 'name' => 'widget_cache_timeout'));
-      if(($tsDiff > $cacheTime)||(empty($code))) {
-        $code = CRM_Wci_WidgetCode::get_widget_realtime_code($widgetId, $preview);
-      }
     }
+    
+    if (!$code) {
+      $code = CRM_Wci_WidgetCode::generate_widget_code($widgetId);
+      CRM_Wci_BAO_WidgetCache::setWidgetCache($widgetId, $code);
+    }
+
     return $code;
   }
 }
index 6f213fc122dc515b077a93e2c54e4747dadced65..0ba73fb6de7f631c6163244a3b4c082cc5714def 100644 (file)
  * $Id$
  */
 
-
-/*
-<script type="text/javascript" src="http://drupal.local/sites/all/modules/civicrm/extensions/civicrm-wci/extern/wciwidget.php?widgetId=1"></script>
-*/  
-
 require_once '../../../civicrm.config.php';
 
-$wciembed_js = '
-/*    
+$license_text = '
+        /*    
         @licstart  
 
         Copyright (C) 2014  Zyxware Technologies
@@ -55,7 +50,8 @@ $wciembed_js = '
 
         @licend
         */
-
+        ';
+$wciembed_js = '
 // Cleanup functions for the document ready method
 if ( document.addEventListener ) {
     DOMContentLoaded = function() {
@@ -100,9 +96,11 @@ $config = CRM_Core_Config::singleton();
 
 $embedId = CRM_Utils_Request::retrieve('id', 'Positive', CRM_Core_DAO::$_nullObject);
 $preview = CRM_Utils_Request::retrieve('preview', 'Positive', CRM_Core_DAO::$_nullObject);
-$output = 'var wciwidgetcode =  ' . CRM_Wci_WidgetCode::get_widget_code($embedId, $preview) . ';';
 
-$output = $output . $wciembed_js;
+$output  = $license_text;
+$output .= 'var wciwidgetcode =  ' . CRM_Wci_WidgetCode::get_widget_code($embedId, $preview) . ';';
+$output .= $wciembed_js;
+
 echo $output;
 
 CRM_Utils_System::civiExit();
index 7086a8b970668e5f4ae31c6523836677b76e04d9..940f19f8d2db05d8fa4ec31b8947747c8dfbeecc 100644 (file)
--- a/info.xml
+++ b/info.xml
@@ -12,9 +12,9 @@
   <version>1.0-beta3</version>
   <develStage>beta</develStage>
   <compatibility>
-    <ver>4.2</ver>
+    <ver>4.4</ver>
   </compatibility>
-  <comments></comments>
+  <comments>Contributed by Zyxware Technologies - www.zyxware.com</comments>
   <civix>
     <namespace>CRM/Wci</namespace>
   </civix>
index 12158ab16be851c98cd5a2433f3af4d26d73c96d..276e8aecab7cf1e0e7a1e4e72a58a4245f7fdf9f 100644 (file)
@@ -1,26 +1,11 @@
 <?php
 return array(
-  'default_wci_widget' => array(
-    'group_name' => 'Wci Preference',
-    'group' => 'wci',
-    'name' => 'default_wci_widget',
-    'type' => 'Integer',
-    'default' => 0,
-    'add' => '4.3',
-    'is_domain' => 1,
-    'is_contact' => 0,
-    'description' => 'Default widget id',
-    'help_text' => 'Sets default widget id',
-  ),
   'default_wci_profile' => array(
     'group_name' => 'Wci Preference',
     'group' => 'wci',
     'name' => 'default_wci_profile',
     'type' => 'Integer',
     'default' => 0,
-    'add' => '4.3',
-    'is_domain' => 1,
-    'is_contact' => 0,
     'description' => 'Default profile id',
     'help_text' => 'Sets default profile id',
   ),
@@ -30,10 +15,7 @@ return array(
     'name' => 'widget_cache_timeout',
     'type' => 'Integer',
     'default' => 0,
-    'add' => '4.3',
-    'is_domain' => 1,
-    'is_contact' => 0,
-    'description' => 'widget timeout',
+    'description' => 'Widget timeout',
     'help_text' => 'widget timeout',
   ),
  );
index a506792273a0be9f46ce7619f97ccd5c80da01fd..d20d6726a8dd8bd54c2a2416950671a828f7d7b3 100644 (file)
@@ -67,10 +67,9 @@ CREATE TABLE IF NOT EXISTS civicrm_wci_embed_code (
 
 -- WCI widget cache.
 CREATE TABLE IF NOT EXISTS civicrm_wci_widget_cache (
-  id int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'cache Id.',
-  widget_id int(10) unsigned DEFAULT NULL COMMENT 'widget id.',
+  widget_id int(10) id int(10) unsigned NOT NULL COMMENT 'widget id.',
   widget_code text DEFAULT NULL COMMENT 'Widget code.',
-  ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
-  PRIMARY KEY (`id`)
+  expire int(10) DEFAULT 0 COMMENT 'A Unix timestamp indicating when the cache entry should expire.';,
+  PRIMARY KEY (`widget_id`)
 
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
index a92052868fc5a67a79487c2a948ea627390e1c97..137e1c3c0dff8caa1ac48acc5fbc4ee417817af7 100644 (file)
@@ -7,16 +7,6 @@
   {if $form.title.value != ""}
     {php} 
       if(isset($_REQUEST['id'])) {
-        /*$wid_id = $_REQUEST['id'];
-        $data = CRM_Wci_BAO_Widget::getWidgetData($wid_id);
-        $template = CRM_Core_Smarty::singleton();
-        $template->assign('wciform', $data);
-        if($data["override"] == 0) {
-          $template->template_dir[] = getWciWidgetTemplatePath();
-          $wcidata = $template->fetch('wciwidget.tpl');
-        } else {
-          $wcidata = $template->fetch('string:' . $wid_page[$dao->id]['custom_template']);
-        }*/
         $widget_controller_path = getWciWidgetControllerPath();
         $extension_root_path = getExtensionRootPath();
       }
           <div class="description">
             Click <strong>Save &amp; Preview</strong> to save any changes to your settings, and preview the widget again on this page.
           </div>
-<!--          <script type="text/javascript" src="{php}echo $widget_controller_path;{/php}?widgetId={php}echo $wid_id;{/php}&preview=1&referalid=2442"></script></script> -->
-          <script type="text/javascript" src="{php}echo $widget_controller_path;{/php}?id={php}echo $_REQUEST['id'];{/php}&preview=1&referalid=2442"></script></script>
+          <script type="text/javascript" src="{php}echo $widget_controller_path;{/php}?id={php}echo $_REQUEST['id'];{/php}&preview=1"></script>
   <div id='widgetwci'></div>
         </div>
-<!--        <div class="col2">
-          <div class="description">
-            Add this widget to any web page by copying and pasting the code below.
-          </div>
-          <textarea rows="8" cols="40" name="widget_code" id="widget_code"><script type="text/javascript" src="{php}echo $widget_controller_path;{/php}?widgetId={php}echo $wid_id;{/php}&embed=1&referalId=2442"> </script> 
-<div id='widgetwci'></div></textarea>
-          <br>
-          <strong>
-            <a href="#" onclick="CreateWidget.widget_code.select(); return false;">ยป Select Code</a>
-          </strong>
-        </div> -->
     </div>
           <div class="clear"></div>
     </div>
index 3e6a14809fcaa94fcfd3acc16694ee76d8fcf384..1269a319af58df40dd91aa0b64cfcb376714a4a1 100644 (file)
       if(isset($_REQUEST['id'])) {
         $emb_id = $_REQUEST['id'];
         $wid_id = CRM_Wci_BAO_EmbedCode::getWidgetId($emb_id);
-        $data = CRM_Wci_BAO_Widget::getWidgetData($wid_id);
-        $template = CRM_Core_Smarty::singleton();
-        $template->assign('wciform', $data);
-        if($data["override"] == 0) {
-          $template->template_dir[] = getWciWidgetTemplatePath();
-          $wcidata = $template->fetch('wciwidget.tpl');
-        } else {
-          $wcidata = $template->fetch('string:' . $wid_page[$dao->id]['custom_template']);
-        }
         $widget_controller_path = getWciWidgetControllerPath();
         $extension_root_path = getExtensionRootPath();
       }
@@ -41,7 +32,7 @@
           <div class="description">
             Click <strong>Save &amp; Preview</strong> to save any changes to your settings, and preview the widget again on this page.
           </div>
-          <script type="text/javascript" src="{php}echo $widget_controller_path;{/php}?id={php}echo $emb_id;{/php}&embed=0&referal_id=2442"></script></script>
+          <script type="text/javascript" src="{php}echo $widget_controller_path;{/php}?id={php}echo $wid_id;{/php}&preview=1"></script></script>
   <div id='widgetwci'></div>
         </div>
         <div class="col2">