/[drupal]/contributions/modules/civinode/civinode_utils.inc
ViewVC logotype

Diff of /contributions/modules/civinode/civinode_utils.inc

Parent Directory Parent Directory | Revision Log Revision Log | View Revision Graph Revision Graph | View Patch Patch

revision 1.31.2.8, Fri Jul 6 21:45:22 2007 UTC revision 1.31.2.9, Mon Sep 17 22:42:44 2007 UTC
# Line 95  function civinode_check_admin_access($op Line 95  function civinode_check_admin_access($op
95   * @param mixed $obj value returned by CiviCRM API that may be error.   * @param mixed $obj value returned by CiviCRM API that may be error.
96   * @return boolean TRUE if $obj is a CiviCRM error.   * @return boolean TRUE if $obj is a CiviCRM error.
97   */   */
98  function civinode_check_error($obj = NULL, $log_error = TRUE){  function civinode_check_error($obj = NULL){
99    //Reset the error    //Reset the error
100    civinode_clear_error();    civinode_clear_error();
101    if (!civinode_check_init()){    if (!civinode_check_init()){
# Line 108  function civinode_check_error($obj = NUL Line 108  function civinode_check_error($obj = NUL
108    //Docs are wrong... :-(    //Docs are wrong... :-(
109    //if(crm_is_error($obj)){    //if(crm_is_error($obj)){
110    if($obj and is_a($obj, 'CRM_Core_Error')){    if($obj and is_a($obj, 'CRM_Core_Error')){
111      //$msg = $obj->_errors[0]['message'];      $msg = $obj->_errors[0]['message'];
     _civinode_set_error($obj);  
     if (!$log_error)  
       return TRUE;  
112      //may want to record the calling URL as well...      //may want to record the calling URL as well...
113      $trace = debug_backtrace();      $trace = debug_backtrace();
114      $caller = $trace[1]['function'] . "@" . $trace[1]['line'];      $caller = $trace[1]['function'] . "@" . $trace[1]['line'];
115      watchdog('CRM', "$msg ($caller)", WATCHDOG_ERROR);      watchdog('CRM', "$msg ($caller)", WATCHDOG_ERROR);
116        _civinode_set_error($msg);
117      return TRUE;      return TRUE;
118    }    }
119    else    else
# Line 130  function civinode_check_error($obj = NUL Line 128  function civinode_check_error($obj = NUL
128   * @return string Error string.   * @return string Error string.
129   */   */
130  function civinode_get_last_error(){  function civinode_get_last_error(){
131    $err_obj = _civinode_set_error();    return _civinode_set_error();
   if ($err_obj) {  
     $msg = $err_obj->_errors[0]['message'];  
     return $msg;  
   }  
   return '';  
 }  
   
 /**  
  * Get the last error object checked via civinode_check_error  
  *  
  * @ingroup Error_Handlers  
  * @return object PEAR error object.  
  */  
   
 function civinode_get_last_error_object() {  
   $err_obj = _civinode_set_error();  
   return $err_obj;  
132  }  }
133    
134  /**  /**
# Line 197  function &_civinode_get_last_error(){ Line 178  function &_civinode_get_last_error(){
178    //return just the tip of the stack.    //return just the tip of the stack.
179    if ($error_stack->hasErrors()) {    if ($error_stack->hasErrors()) {
180      $errors = $error_stack->getErrors();      $errors = $error_stack->getErrors();
181      $last_error = array_pop($errors);      $lastError = array_pop($errors);
182    }    }
183    
184    return $last_error;    return $last_error;
# Line 267  function civinode_get_default_profile_id Line 248  function civinode_get_default_profile_id
248    
249    
250  /**  /**
251     * Generate a Forms API structure for a Profile
252     *
253     */
254    function civinode_get_profile_form($pid, &$form, $params = array()) {
255      if (!civinode_check_init()){
256        watchdog('CRM', t('CiviCRM must be installed for CiviNode'), WATCHDOG_ERROR);
257        return FALSE;
258      }
259      $meta = civinode_get_profile_metadata($pid);
260      if (!$meta)
261        return FALSE;
262      if (!$form or !is_array($form))
263        $form = array();
264      //We may need to retrieve some non-standard fields...
265      $extra_fields = array();
266      if ($params['contact_id']) {
267        foreach ($meta as $item) {
268          $extra_key = $item['name'];
269          if (!isset($params[$extra_key])) {
270            $extra_fields[$extra_key] = 1;
271          }
272        }
273        if ($extra_fields) {
274          $extra_params =
275            array('contact_id' => $params['contact_id']);
276          $extra_info = crm_contact_search($extra_params, $extra_fields,
277                                           NULL, 0, 1);
278          if (isset($extra_info[0]) and is_array($extra_info[0])) {
279            $data = array_shift($extra_info[0]);
280            foreach ($extra_fields as $fld_name => $dummy) {
281              if (isset($data[$fld_name])) {
282                $val = $data[$fld_name];
283                if (is_string($val) and $val[0] == chr(1)) {
284                  //we have an encoded checkbox, explode it
285                  $boxes = explode(chr(1), $val);
286                  $val = array();
287                  foreach ($boxes as $box) {
288                    $val[$box] = $box;
289                  }
290                }
291                $params[$fld_name] = $val;
292              }
293            }
294          }
295    
296        }
297      }
298      //Now, we build the form
299      foreach ($meta as $item) {
300        $html_type = $item['html_type'];
301        //Valid types listed in CRM_Custom_Form_Field
302        //support will be incremental, since I don't
303        //know all the formats yet
304        //  array(  'Text' => 'Text', 'Select' => 'Select',
305        //          'Radio' => 'Radio', 'CheckBox' => 'CheckBox',
306        //          'Multi-Select' => 'Multi-Select'),
307        //  also: TextArea, Date, some geographical
308        $name = $item['name'];
309        $label = $item['title'];
310    
311        switch ($html_type) {
312          case 'CheckBox': //actually, a set of them
313            //remove the '---' item
314            unset($item['options'][0]);
315            $form[$name] =
316              array('#title' => $label,
317                    '#type' => 'checkboxes',
318                    '#options' => $item['options'],
319                    );
320            break;
321          case 'Radio': //civicrm 1.6 is a little odd
322            //remove the '---' item
323            if ($item['options']) {
324              unset($item['options'][0]);
325              $form[$name] =
326                array('#title' => $label,
327                      '#type' => 'radios',
328                      '#options' => $item['options'],
329                      );
330            }
331            else {
332              //this is just a free-standing boolean.
333              //We render it as a single checkbox
334              $form[$name] =
335                array('#title' => $label,
336                      '#type' => 'checkbox',
337                      );
338            }
339            break;
340          case 'Select':
341            $form[$name] =
342              array('#title' => $label,
343                    '#type' => 'select',
344                    '#options' => $item['options'],
345                    );
346            break;
347          case 'Text':
348          //we deliberately fall through to default, since textfield is the
349          //default rendering
350          default:
351            $form[$name] =
352              array('#title' => $label,
353                    '#type' => 'textfield',
354                    );
355            if ($item['attributes']) {
356              $size = $item['attributes']['size'];
357              $max = $item['attributes']['maxlength'];
358              if ($size) {
359                $form[$name]['#size'] = $size;
360                if ($max)
361                  $form[$name]['#maxlength'] = $max;
362              }
363    
364            }
365            break;
366        }
367        if (isset($params[$name])) {
368          //Note: this may need to be moved into the switch
369          //if some items require special processing.  Dates
370          //may well need this.
371          $form[$name]['#default_value'] = $params[$name];
372        }
373    
374        if ($item['help_post'])
375          $form[$name]['#description'] = $item['help_post'];
376      }
377    
378    }
379    
380    /**
381     * Save back profile related data.
382     *
383     * This function should be called in your FAPI submit function
384     *
385     */
386    function civinode_save_profile_fields($pid, $uid, $params) {
387      if (!civinode_check_init()){
388        watchdog('CRM', t('CiviCRM must be installed for CiviNode'), WATCHDOG_ERROR);
389        return FALSE;
390      }
391      //We need to flatten the array valued item that comes back
392      //for a set of checkboxes
393      $old_params = $params;
394      foreach ($old_params as $key => $val) {
395        if (is_array($val)) {
396          //CiviCRM does a weird trick with Ctrl-A...
397          //$params[$key] = chr(1) . implode(chr(1), array_values($val)) . chr(1);
398          $new_val = array();
399          foreach (array_values($val) as $key_val) {
400            if ($key_val) {
401              $new_val[$key_val] = 1;
402            }
403          }
404          $params[$key] = $new_val;
405        }
406      }
407      $fields =  crm_uf_get_profile_fields($pid);
408      //We need to work around a bug that will cause the display_name to
409      //unset.  This will be fixed in 1.8, so this code will no longer
410      //be needed once we are no longer supporting 1.6 and 1.7
411      $contact_params = array('contact_id' => $uid);
412      $disp_fields = array('first_name' => 1, 'last_name' => 1, 'middle_name' => 1);
413    
414      $contact = crm_fetch_contact($contact_params, $disp_fields);
415      if (!civinode_check_error($contact)) {
416        foreach ($disp_fields as $fld => $dummy) {
417          if (!isset($params[$fld]) and isset($contact[$fld]))
418            $params[$fld] = $contact[$fld];
419        }
420      }
421      //End of display_name fix
422      crm_create_profile_contact( $params, $fields, $pid, $uid);
423    }
424    
425    /**
426   * Get the appropriate meta data for this PID and operation   * Get the appropriate meta data for this PID and operation
427   *   *
428   * @ingroup CiviCRM_MetaData   * @ingroup CiviCRM_MetaData
# Line 279  function civinode_get_profile_metadata($ Line 435  function civinode_get_profile_metadata($
435      watchdog('CRM', t('CiviCRM must be installed for CiviNode'), WATCHDOG_ERROR);      watchdog('CRM', t('CiviCRM must be installed for CiviNode'), WATCHDOG_ERROR);
436      return FALSE;      return FALSE;
437    }    }
438    static $cache;    static $cache, $exportable;
439    $action = CRM_CORE_ACTION_VIEW;    $action = CRM_CORE_ACTION_VIEW;
440    switch($op){    switch($op){
441    default:    default:
# Line 294  function civinode_get_profile_metadata($ Line 450  function civinode_get_profile_metadata($
450    }    }
451    else    else
452      $cache[$pid] = array();      $cache[$pid] = array();
453        //Gather info about field structure
454    //what should visibility be set to??      require_once 'CRM/Contact/BAO/Contact.php';
455    $raw_data = crm_uf_get_profile_fields($pid, FALSE, $action);      require_once 'CRM/Utils/Type.php';
456    $title = crm_uf_get_profile_title($pid);      $dummy = new CRM_Contact_BAO_Contact();
457    $cache[$pid][$action] = $raw_data;      $exportable = $dummy->exportableFields();
458    
459        //what should visibility be set to??
460        $raw_data = crm_uf_get_profile_fields($pid, FALSE, $action);
461        $keys = array_keys($raw_data);
462        foreach ($keys as $key) {
463          if (isset($exportable[$key])) {
464            //is it a custom field?
465            if ($exportable[$key]['custom_field_id']) {
466              $params = array('id' =>  $exportable[$key]['custom_field_id']);
467              $obj = crm_get_custom_field( $params );
468              if (!civinode_check_error($obj)) {
469                $values = crm_get_option_values($obj);
470                $options = array();
471                if ($values) {
472                  if (!$raw_data[$key]['is_required']) {
473                    $options = array('0' => t('---') );
474                  }
475                  foreach ($values as $val_key => $val) {
476                    $options[$val['value']] = $val['label'];
477                  }
478                  $raw_data[$key]['options'] = $options;
479                }
480              }
481            }
482            //Note: type for built-in, data_type and html_type for custom
483            $data_type = $exportable[$key]['data_type'] ?
484              $exportable[$key]['data_type'] :
485              CRM_Utils_Type::typeToString($exportable[$key]['type']);
486            $raw_data[$key]['type'] = $data_type;
487            $raw_data[$key]['html_type'] = $exportable[$key]['html_type'] ?
488              $exportable[$key]['html_type'] : _civinode_html_typer($data_type);
489          }
490        }
491        //$title = crm_uf_get_profile_title($pid);
492        $cache[$pid][$action] = $raw_data;
493    
494    return $cache[$pid][$action];      return $cache[$pid][$action];
495    }
496    
497    function _civinode_html_typer($type) {
498      switch ($type) {
499        case 'Boolean':
500          return 'Radio';
501        default:
502          return 'Text';
503      }
504  }  }
505    
506    
# Line 508  function civinode_get_groups($params = N Line 708  function civinode_get_groups($params = N
708    
709    
710  /**  /**
711   * List static groups for a contact.   * List groups for a contact.
712   *   *
713   * @ingroup CiviCRM_Groups   * @ingroup CiviCRM_Groups
714   * @param int $cid CiviCRM Contact ID   * @param int $cid CiviCRM Contact ID
# Line 524  function civinode_get_groups_for_cid($ci Line 724  function civinode_get_groups_for_cid($ci
724        watchdog('CRM', t('CiviCRM must be installed for CiviNode'), WATCHDOG_ERROR);        watchdog('CRM', t('CiviCRM must be installed for CiviNode'), WATCHDOG_ERROR);
725        return FALSE;        return FALSE;
726      }      }
     //Get static groups  
      //$list = CiviNode_LL_getContactGroup($cid, 'Added');  
      //LL is required since crm_contact_get_groups stupidly requires  
      //you to belong to a group to check membership  
727      $list = CiviNode_LL_getContactGroup($cid, 'Added');      $list = CiviNode_LL_getContactGroup($cid, 'Added');
728        //$list = crm_contact_get_groups($cid, 'Added');
     if (civinode_check_error($list))  
       return FALSE;  
   
729      foreach ($list as $eid => $data) {      foreach ($list as $eid => $data) {
730        $groups[] = $data['group_id'];        $groups[] = $data['group_id'];
731      }      }
# Line 707  function civinode_get_current_target_gro Line 900  function civinode_get_current_target_gro
900   * @return bool TRUE if it belongs   * @return bool TRUE if it belongs
901   */   */
902  function civinode_util_cid_in_group($cid, $gid){  function civinode_util_cid_in_group($cid, $gid){
   if (!$cid or !$gid)  
     return FALSE; //sanity clause  
903    if (!civinode_check_init()){    if (!civinode_check_init()){
904      watchdog('CRM', t('CiviCRM must be installed for CiviNode'), WATCHDOG_ERROR);      watchdog('CRM', t('CiviCRM must be installed for CiviNode'), WATCHDOG_ERROR);
905      return FALSE;      return FALSE;
906    }    }
907    //use a search instead, since it detects smart groups also.  
908    $params = array('group' => array($gid => 1), 'contact_id' => $cid);    //TO DO: use a search instead.
909    $contact = crm_fetch_contact($params);  
910    if (civinode_check_error($contact))    //What groups does this cid know about?
911      return FALSE;    $list = CiviNode_LL_getContactGroup($cid, 'Added');
912    //return $cnt ? TRUE : FALSE;    //$list = crm_contact_get_groups($cid, 'Added');
913    return TRUE;    //AFAIR keys are gid
914      $groups = array_keys($list);
915      return in_array($gid, $groups);
916  }  }
917    
918    
# Line 739  function civinode_util_group_contacts($g Line 932  function civinode_util_group_contacts($g
932      watchdog('CRM', t('CiviCRM must be installed for CiviNode'), WATCHDOG_ERROR);      watchdog('CRM', t('CiviCRM must be installed for CiviNode'), WATCHDOG_ERROR);
933      return NULL;      return NULL;
934    }    }
935    $groups = array( $gid => 1);    $group = crm_get_groups(array('id' => $gid));
   $params = array( 'group' => $groups );  
   $returnProperties = array('contact_id' => 1);  
   $limit = $num_recs ? $num_recs : 100;  
   $contacts = crm_contact_search($params, $returnProperties, NULL, $start, $limit);  
936    $list = array();    $list = array();
937    foreach($contacts[0] as $contact){    //establish a limit, due to memory bugs
938      $list[] = $contact['contact_id'];    //in 1.4.
939      $limit = $num_recs ? $num_recs : 1000;
940      if(civinode_check_error($group))
941        return NULL;
942      if (!count($group))
943        return array();
944      $contacts = crm_get_group_contacts($group[0],
945                                         //array('id' => 1), //bare min please
946                                         NULL, //default instead
947                                         'Added', NULL, //status and sort
948                                         $start, $limit); //up to first 10K records
949      foreach($contacts as $contact){
950        $list[] = $contact->contact_id;
951    }    }
952    return $list;    return $list;
953    
954  }  }
955    
956    
# Line 1271  function _civinode_dojo_render_callback_ Line 1473  function _civinode_dojo_render_callback_
1473    $js = "    $js = "
1474    function $funcname(value) {    function $funcname(value) {
1475      var control_did = '$targ_did';      var control_did = '$targ_did';
     var key_did = '$self_id';  
     var key_handle = document.getElementById(key_did);  
     //if (!key_handle)  
      // alert('No key handle for ' + key_did);  
1476      var handle = document.getElementById(control_did);      var handle = document.getElementById(control_did);
     //alert('$targ_did = ' + value + ',  key = ' + key_handle.value);  
1477      if (handle) {      if (handle) {
1478        handle.value = value;        handle.value = value;
1479      }      }
# Line 1297  function _civinode_dojo_render_callback_ Line 1494  function _civinode_dojo_render_callback_
1494      drupal_add_js($init_js, 'inline', 'footer', TRUE);      drupal_add_js($init_js, 'inline', 'footer', TRUE);
1495    }    }
1496  }  }
1497    /**
1498     * Put path info in one place (since this may change)
1499     *
1500     * @param string $item
1501     */
1502    function _civinode_get_path($item = 'base') {
1503      global $civicrm_root;
1504      $docroot = $_SERVER['DOCUMENT_ROOT'];
1505      $len = strlen($docroot);
1506      $base = substr($civicrm_root, $len + 1);
1507      switch ($item) {
1508        case 'ajax':
1509          return $base . "extern/ajax.php";
1510        case 'dojo_lib':
1511          return $base . "packages/dojo/dojo.js";
1512        default:
1513          return $base;
1514      }
1515    }
1516    
1517  function _civinode_dojo_dataurl($group_id = 0) {  function _civinode_dojo_dataurl($group_id = 0) {
1518    //$path = _civinode_get_path('ajax');    //$path = _civinode_get_path('ajax');
1519    //TODO generalized domain_id as set below    //TODO generalized domain_id as set below
1520    $path = base_path() . "civinode/dojo/contact/$group_id";    $path = url("civinode/dojo/contact/$group_id");
   //$path = "http://crm17dj/civinode/dojo/contact/$group_id";  
1521    return $path . "?d=1&s=%{searchString}";    return $path . "?d=1&s=%{searchString}";
1522  }  }
1523    
# Line 1313  function civinode_dojo_widgets($widget_t Line 1527  function civinode_dojo_widgets($widget_t
1527      require_once _civinode_get_path() . "CRM/Utils/Type.php";      require_once _civinode_get_path() . "CRM/Utils/Type.php";
1528      $domainID = CRM_Utils_Type::escape( $_GET['d'], 'Integer' );      $domainID = CRM_Utils_Type::escape( $_GET['d'], 'Integer' );
1529      $name     = strtolower( CRM_Utils_Type::escape( $_GET['s'], 'String'  ) );      $name     = strtolower( CRM_Utils_Type::escape( $_GET['s'], 'String'  ) );
   
     $host = $_SERVER['HTTP_HOST'];  
     //error_log("Host was $host");  
1530    
1531      $elements = _civinode_contact_list_by_group($group_id, $size, $name);      $elements = _civinode_contact_list_by_group($group_id, $size, $name);
1532      //$cnt = count($elements);      //$cnt = count($elements);
# Line 1414  LIMIT 6"; Line 1625  LIMIT 6";
1625    
1626    }    }
1627    exit();    exit();
 }  
   
 /**  
  * Validation and install routines  
  */  
   
 /**  
  * Get the Drupal (i.e., relative) path to the CiviCRM install  
  *  
  * @return string  
  */  
 function _civinode_get_civicrm_install_path() {  
   if (!civinode_check_init())  
     return FALSE;  
   $path_to_module = drupal_get_path('module', 'civicrm');  
   //if this is a normal install, the module is sitting  
   //in a "drupal" subdirectory.  If it isn't, bail.  
   $matches = array();  
   if (!preg_match('/^(.+)\/drupal$/', $path_to_module, $matches))  
     return FALSE; //diagnostics maybe too?  
   return $matches[1];  
   
 }  
   
   
 /**  
  * Put path info in one place (since this may change)  
  *  
  * @param string $item  
  */  
 function _civinode_get_path($item = 'base') {  
   global $civicrm_root;  
   
   //$install_root = realpath($_SERVER['DOCUMENT_ROOT'] . base_path());  
   //$len = strlen($install_root);  
   //$base = substr($civicrm_root, $len + 1);  
   civinode_check_init();  
   $config =& CRM_Core_Config::singleton();  
   $resbase = $config->resourceBase;  
   $url_base = url(NULL, NULL, NULL, TRUE);  
   $base = substr($resbase, strlen($url_base));  
   switch ($item) {  
     case 'ajax':  
       return $base . "extern/ajax.php";  
     case 'dojo_lib':  
       return $base . "packages/dojo/dojo.js";  
     default:  
       return $base;  
   }  
 }  
   
 /**  
  * Helper function for extracting CiviCRM config strings  
  *  
  * @param string $key  
  * @return  
  *   string if $key is set, an array of config strings otherwise.  
  */  
 function _civinode_get_civicrm_config($key = NULL) {  
   if (!civinode_check_init())  
     return FALSE;  
   $config =& CRM_Core_Config::singleton();  
   if (!$key) {  
     return (array)$config;  
   }  
   if (!isset($config->$key))  
     return NULL;  
   $setting = $config->$key;  
   return $setting;  
 }  
   
 /**  
  * File system path to Drupal install, with trailing slash.  
  *  
  * @return string  
  */  
 function _civinode_get_drupal_install_path() {  
   //FIXME This is probably not correct for Windows.  
   $doc_root = rtrim($_SERVER['DOCUMENT_ROOT'], DIRECTORY_SEPARATOR);  
   return $doc_root . base_path();  
 }  
   
 /**  
  * Run sanity checks for the CiviCRM configuration.  
  */  
 function civinode_validate_config(){  
   global $civicrm_root, $base_url;  
   $problem_cnt = 0;  
   //Full FS path to drupal  
   $d_path = _civinode_get_drupal_install_path();  
   //Relative path to CiviCRM install  
   $c_path = _civinode_get_civicrm_install_path();  
   $full_c_path = $d_path . $c_path . DIRECTORY_SEPARATOR;  
   if ($full_c_path != $civicrm_root) {  
     $msg = t('$civicrm_root is not set correctly; was expecting @path',  
              array('@path' => $full_c_path));  
     drupal_set_message($msg, 'error');  
     $problem_cnt++;  
   }  
   else {  
     drupal_set_message(t('$civicrm_root looks good'), 'status');  
   }  
   $predicted_uf_base = $base_url  . "/";  
   if (!defined('CIVICRM_UF_BASEURL') or  
       CIVICRM_UF_BASEURL != $predicted_uf_base) {  
     $msg = t('CIVICRM_UF_BASEURL is not set correctly, expecting @url',  
              array('@url' => $predicted_uf_base));  
     drupal_set_message($msg, 'error');  
     $problem_cnt++;  
   }  
   else {  
     drupal_set_message(t('CIVICRM_UF_BASEURL looks good'), 'status');  
   }  
   //Validate the resource path  
   $predicted_res_path = $predicted_uf_base . $c_path . "/";  
   $res_path = _civinode_get_civicrm_config('resourceBase');  
   if ($predicted_res_path != $res_path) {  
     $msg = t('Resource Path looks bad; was expecting @url',  
              array('@url' => $predicted_res_path));  
     drupal_set_message($msg, 'error');  
     $problem_cnt++;  
   }  
   else {  
     drupal_set_message(t('Resource Path is set correctly'));  
   }  
   return $problem_cnt ?  
      t('Problems found with CiviCRM') :  
      t('Your CiviCRM installation looks good');  
 }  
   
 function civinode_install_location() {  
   return dirname(__FILE__);  
1628  }  }

Legend:
Removed from v.1.31.2.8  
changed lines
  Added in v.1.31.2.9

  ViewVC Help
Powered by ViewVC 1.1.2