Answers.Body: <p><strong>If you want the tokens only in the context of a schedule reminder, you should use the new better way to do tokens instead : <a href="https://docs.civicrm.org/dev/en/latest/framework/token/#token-processor" rel="nofollow noreferrer">TokenProcessor</a>.</strong></p>
  <p><code>hook_civicrm_tokenValues</code> is only working for <code>Contact</code> entity. You can't really add tokens on other entities like CiviCase using this hook.</p>
  <p>If you need the token to work in every contexts (transactional email, mass mailings, schedule reminders, Print/merge document) then you might consider the following workaround.</p>
  <p>If you are sure you can find the proper case_id for the current contact, for example if it's the latest created or the only one of a certain type, then you could do something like :</p>
  <pre><code>function example_civicrm_tokens() {
    $tokens['mytokens'] = [
      'mytokens.casetoken' =&gt; E::ts('Token related to a Case'),
    ];
  }
  
  function example_civicrm_tokenValues(&amp;$values, $cids, $job = null, $tokens = array(), $context = null) {
  
    foreach ($cids as $cid) {
      $result = civicrm_api3('Case', 'get', [
        'sequential' =&gt; 1,
        'contact_id' =&gt; $cid,
        'case_type_id' =&gt; ...
      ]);
      if ($result['count'] == 1) {
        $case_id = $result['values'][0]['id'];
        // do your stuff now that you have a $case_id for the current contact
        $values[$cid]['mytokens.casetoken'] = ...
      }
      else {
        // case_id is either non existent or gives several results which is not workable
        // let's keep token empty
        $values[$cid]['mytokens.casetoken'] = '';
      }
    }
  
  }
  </code></pre>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2021-09-20T22:32:39.050Z
Answers.Text: Thank you very much for your reply and advice about TokenProcessor. 
  
  As well thanks for code, but I'm not sure if I can find the right case_id for the current contact, because each contact can have many of the same cases by type and creation time. 
  
  
  Maybe you have an idea how to get the current activity_id which was executed by Cron Job... For me will be easy to resolve the thing when i'll get this variable.
Answers.UserDisplayName: Vadim Kozhevnikov
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2021-09-22T13:42:32.097Z
Answers.Text: No sorry, only contact_id is provided using hook_civicirm_tokenValues. You really need to use TokenProcessor in that case.
Answers.UserDisplayName: samuelsov
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2021-09-20T16:11:49.623Z
Answers.LastActivityDate: 2021-09-20T16:11:49.623Z
Answers.UserDisplayName: samuelsov
Body: <p><strong>How to get $activity_id or $case_id variables in HOOKs when cron job execute in Joomla?</strong></p>
  <p>I have 2 functions in HOOK for CiviCase</p>
  <ul>
  <li>function joomla_civicrm_tokens(&amp;$tokens)</li>
  <li>function joomla_civicrm_tokenValues(&amp;$values, $cids, $job = null, $tokens = array(), $context = null)</li>
  </ul>
  <p>1 - I can get variables for the tokens in Scheduled Reminders when I run a job manually.</p>
  <p><a href="https://i.sstatic.net/7ay40.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/7ay40.png" alt="enter image description here" /></a></p>
  <p>2 - But if a server executed Cron Job i will get message: Failure, Error message: You have an error ...</p>
  <p>I know it's happen because i get $case_id from joomla session
  $case_id = $session-&gt;get(&quot;case_id&quot;);</p>
  <p><strong>Could you explain me how to get $case_id or $activity_id from civicrm when cron job execute</strong></p>
  <p>Below you can find my HOOKs:</p>
  <pre><code>function joomla_civicrm_tokens(&amp;$tokens) {
    if (isset($tokens['charter'])) {
      return;
    }
  
    $tokens['charter'] = array('charter.vardump' =&gt; 'vardump','charter.note2' =&gt; 'Note 2','charter.note' =&gt; 'Note','charter.cid' =&gt; 'CID','charter.caseid' =&gt; 'Case ID','charter.clientlastname' =&gt; 'Client Sur', 'charter.clientfirstname' =&gt; 'Client Name', 'charter.date_short' =&gt; 'Today\'s Date: dd/mm/yyyy' /*etc...*/ );
  
  //  print_r($tokens);
  }
  
  
  function joomla_civicrm_tokenValues(&amp;$values, $cids, $job = null, $tokens = array(), $context = null) {
    // Date tokens
    if (!empty($tokens['charter'])) {
    
      $db = JFactory::getDBO();
      $session = JFactory::getSession();
      $case_id =  $session-&gt;get(&quot;case_id&quot;);
                  
  
  /*
      $sql = &quot;SELECT * FROM  `civicrm_case_activity` WHERE `activity_id` = &quot;.$activity_id;
      $db-&gt;setQuery($sql);
      $rows  = $db-&gt;loadObjectList();     
      foreach ($rows as $row)
      {
          $case_id =  $row-&gt;case_id;
      }
  
  */
  
  
  
      $sql = &quot;SELECT * FROM  `civicrm_case_yachts` WHERE `case_id` = &quot;.$case_id.&quot; AND `selected` = 1;&quot;;
  
      $db-&gt;setQuery($sql);
      $rows  = $db-&gt;loadObjectList();
          
      foreach ($rows as $row)
          {
      $id =  $row-&gt;id;
      $case_id =  $row-&gt;case_id;
      $case_id_forlink =  $row-&gt;case_id;
      $name =  $row-&gt;name;
      $model =  $row-&gt;model;
      $yachtname =  $row-&gt;name;
      $link =  $row-&gt;link;
      $order =  $row-&gt;order_number;
      $company =  $row-&gt;company;
      $email =  $row-&gt;email;
      $phone =  $row-&gt;phone;
      $selected =  $row-&gt;selected;
      $base =  $row-&gt;base;
      $address =  $row-&gt;address;
      $country =  $row-&gt;country;
      $days =  $row-&gt;days;
      $endofcharter =  date('d-m-Y', strtotime($row-&gt;endofcharter));
      $total =  $row-&gt;total;
      $firstpayment =  $row-&gt;firstpayment;
      $secondpayment =  $row-&gt;secondpayment;
      $extras =  $row-&gt;extras;
      $servicepack =  $row-&gt;servicepack;
      $deposit =  $row-&gt;deposit;
      $totaltocompany =  $row-&gt;totaltocompany;
      $firstpaymenttocompany =  $row-&gt;firstpaymenttocompany;      
      $secondpaymenttocompany =  $row-&gt;secondpaymenttocompany;    
      $ourcomission =  $row-&gt;ourcomission;    
      $agentcomission =  $row-&gt;agentcomission;
      $note =  $row-&gt;note;
  
  
  }
  
      $sql ='SELECT start_date FROM  `civicrm_case` WHERE `id` = '.$case_id;
      $db-&gt;setQuery($sql);
  //  $startofcharter = date('d-m-Y', strtotime($db-&gt;loadResult()));
      $startofcharter = date(&quot;d-m-Y&quot;, strtotime(&quot;-&quot;.$days.&quot; days&quot;, strtotime($endofcharter)));    
  
  
      $first_payment_date = date('d-m-Y', strtotime(&quot;+3 days&quot;));
      $second_payment_date = date(&quot;d-m-Y&quot;, strtotime(&quot;-35 days&quot;, strtotime($startofcharter)));
      $totalplusextras = $total + $extras + $servicepack; 
      $firstpaymentandbankcomission = $firstpayment + 25;
      $secondpaymentandbankcomission = $secondpayment + 25;
      
      
      $sql ='SELECT co.*, ca.`case_id` as `case_id` FROM `civicrm_contact` co left join `civicrm_case_contact` ca on co.`id` = ca.`contact_id` WHERE case_id = '.$case_id;
      $db-&gt;setQuery($sql);
      $rows  = $db-&gt;loadObjectList();
          
      foreach ($rows as $row)
          {
          $firstname =  $row-&gt;first_name;
          $lastname =  $row-&gt;last_name;
      }
  
  
  // get contact_id for to do case link
      $sql ='SELECT * FROM `civicrm_case_contact` WHERE case_id = '.$case_id;
      $db-&gt;setQuery($sql);
      $rows  = $db-&gt;loadObjectList();
          
      foreach ($rows as $row)
          {
          $cid =  $row-&gt;contact_id;
  
      }
      
      
  // get note 2
      $sql ='SELECT * FROM  `civicrm_case` WHERE `id` = '.$case_id;
      $db-&gt;setQuery($sql);    
      $rows  = $db-&gt;loadObjectList();
          
      foreach ($rows as $row)
          {
              $note2 =  $row-&gt;details;
          }
      
  
  
      $db-&gt;disconnect();
  
  
  
  $link = mysqli_connect(&quot;localhost&quot;, &quot;user&quot;, &quot;password&quot;, &quot;DB&quot;) or die (&quot;sorry&quot;);    
  $sql = 'SELECT `course` FROM `__eb_currencies` WHERE `id`=2';
  
  $euro = mysqli_query($link, $sql);
  $euro_1 = mysqli_fetch_assoc($euro);
  $euro_final0 = round($euro_1['course'] + $euro_1['course']*2/100, 2);
  mysqli_close($link);  
  
  $totalrub_first = round($euro_final0 * $firstpaymentandbankcomission, 0);
  $totalrub_second = round($euro_final0 * $secondpaymentandbankcomission, 0);
    
      $date = array('charter.vardump' =&gt; $vardump,'charter.cid' =&gt; $cid,'charter.caseid' =&gt; $case_id_forlink,'charter.clientlastname' =&gt; $lastname, 'charter.clientfirstname' =&gt; $firstname, 'charter.date_short' =&gt; date('d-m-Y'), 'charter.yachtmodel' =&gt; $model, 'charter.yachtname' =&gt; $yachtname, 'charter.numbercontract' =&gt; $order, 'charter.startdate' =&gt; $startofcharter, 'charter.enddate' =&gt; $endofcharter, 'charter.company' =&gt; $company, 'charter.companyemail' =&gt; $email, 'charter.companyphone' =&gt; $phone, 'charter.companyaddress' =&gt; $address, 'charter.country' =&gt; $country, 'charter.base' =&gt; $base, 'charter.days' =&gt; $days, 'charter.total' =&gt; $total, 'charter.firstpayment' =&gt; $firstpayment, 'charter.secondpayment' =&gt; $secondpayment, 'charter.extras' =&gt; $extras, 'charter.servicepack' =&gt; $servicepack, 'charter.deposit' =&gt; $deposit, 'charter.firstpaymentdate' =&gt; $first_payment_date, 'charter.secondpaymentdate' =&gt; $second_payment_date, 'charter.totalplusextras' =&gt; $totalplusextras, 'charter.paymentpluscomission' =&gt; $firstpaymentandbankcomission, 'charter.secondpaymentpluscomission' =&gt; $secondpaymentandbankcomission, 'charter.totalrubfirst' =&gt; $totalrub_first, 'charter.totalrubsecond' =&gt; $totalrub_second, 'charter.totaltocompany' =&gt; $totaltocompany, 'charter.firsttocompany' =&gt; $firstpaymenttocompany, 'charter.secondtocompany' =&gt; $secondpaymenttocompany, 'charter.ourcomission' =&gt; $ourcomission,'charter.note' =&gt; $note,'charter.note2' =&gt; $note2, 'charter.agentcomission' =&gt; $agentcomission
      );
      foreach ($cids as $cid) {
        $values[$cid] = empty($values[$cid]) ? $date : $values[$cid] + $date;
      }
    }
  }
  </code></pre>
  
Comments.ContentLicense: CC BY-SA 4.0
Comments.CreationDate: 2021-09-20T14:01:18.263Z
Comments.Text: How are you running cron? If running as the anonymous user joomla might not initialize a session.
Comments.UserDisplayName: Demerit
Comments.ContentLicense: CC BY-SA 4.0
Comments.CreationDate: 2021-09-21T10:57:25.407Z
Comments.Text: Like this: wget --no-check-certificate -O - -q -t 1 '<cron-url>?name=<username>&pass=<password>&key=<site-key>'
Comments.UserDisplayName: Vadim Kozhevnikov
Tags: <civicase><hooks>
Title: How to get $activity_id or $case_id variables in HOOKs when cron job execute in Joomla?
ThreadText: # How to get $activity_id or $case_id variables in HOOKs when cron job execute in Joomla?
  
  (Asked by: username_0 on 2021-09-20)
  
  **How to get $activity\_id or $case\_id variables in HOOKs when cron job execute in Joomla?**
  
  I have 2 functions in HOOK for CiviCase
  
  * function joomla\_civicrm\_tokens(&$tokens)
  * function joomla\_civicrm\_tokenValues(&$values, $cids, $job = null, $tokens = array(), $context = null)
  
  1 - I can get variables for the tokens in Scheduled Reminders when I run a job manually.
  
  [![enter image description here](https://i.sstatic.net/7ay40.png)](https://i.sstatic.net/7ay40.png)
  
  2 - But if a server executed Cron Job i will get message: Failure, Error message: You have an error ...
  
  I know it's happen because i get $case\_id from joomla session
  $case\_id = $session->get("case\_id");
  
  **Could you explain me how to get $case\_id or $activity\_id from civicrm when cron job execute**
  
  Below you can find my HOOKs:
  
  ```
  function joomla_civicrm_tokens(&$tokens) {
    if (isset($tokens['charter'])) {
      return;
    }
  
    $tokens['charter'] = array('charter.vardump' => 'vardump','charter.note2' => 'Note 2','charter.note' => 'Note','charter.cid' => 'CID','charter.caseid' => 'Case ID','charter.clientlastname' => 'Client Sur', 'charter.clientfirstname' => 'Client Name', 'charter.date_short' => 'Today\'s Date: dd/mm/yyyy' /*etc...*/ );
  
  //  print_r($tokens);
  }
  
  function joomla_civicrm_tokenValues(&$values, $cids, $job = null, $tokens = array(), $context = null) {
    // Date tokens
    if (!empty($tokens['charter'])) {
    
      $db = JFactory::getDBO();
      $session = JFactory::getSession();
      $case_id =  $session->get("case_id");
                  
  
  /*
      $sql = "SELECT * FROM  `civicrm_case_activity` WHERE `activity_id` = ".$activity_id;
      $db->setQuery($sql);
      $rows  = $db->loadObjectList();     
      foreach ($rows as $row)
      {
          $case_id =  $row->case_id;
      }
  
  */
  
      $sql = "SELECT * FROM  `civicrm_case_yachts` WHERE `case_id` = ".$case_id." AND `selected` = 1;";
  
      $db->setQuery($sql);
      $rows  = $db->loadObjectList();
          
      foreach ($rows as $row)
          {
      $id =  $row->id;
      $case_id =  $row->case_id;
      $case_id_forlink =  $row->case_id;
      $name =  $row->name;
      $model =  $row->model;
      $yachtname =  $row->name;
      $link =  $row->link;
      $order =  $row->order_number;
      $company =  $row->company;
      $email =  $row->email;
      $phone =  $row->phone;
      $selected =  $row->selected;
      $base =  $row->base;
      $address =  $row->address;
      $country =  $row->country;
      $days =  $row->days;
      $endofcharter =  date('d-m-Y', strtotime($row->endofcharter));
      $total =  $row->total;
      $firstpayment =  $row->firstpayment;
      $secondpayment =  $row->secondpayment;
      $extras =  $row->extras;
      $servicepack =  $row->servicepack;
      $deposit =  $row->deposit;
      $totaltocompany =  $row->totaltocompany;
      $firstpaymenttocompany =  $row->firstpaymenttocompany;      
      $secondpaymenttocompany =  $row->secondpaymenttocompany;    
      $ourcomission =  $row->ourcomission;    
      $agentcomission =  $row->agentcomission;
      $note =  $row->note;
  
  }
  
      $sql ='SELECT start_date FROM  `civicrm_case` WHERE `id` = '.$case_id;
      $db->setQuery($sql);
  //  $startofcharter = date('d-m-Y', strtotime($db->loadResult()));
      $startofcharter = date("d-m-Y", strtotime("-".$days." days", strtotime($endofcharter)));    
  
      $first_payment_date = date('d-m-Y', strtotime("+3 days"));
      $second_payment_date = date("d-m-Y", strtotime("-35 days", strtotime($startofcharter)));
      $totalplusextras = $total + $extras + $servicepack; 
      $firstpaymentandbankcomission = $firstpayment + 25;
      $secondpaymentandbankcomission = $secondpayment + 25;
      
      
      $sql ='SELECT co.*, ca.`case_id` as `case_id` FROM `civicrm_contact` co left join `civicrm_case_contact` ca on co.`id` = ca.`contact_id` WHERE case_id = '.$case_id;
      $db->setQuery($sql);
      $rows  = $db->loadObjectList();
          
      foreach ($rows as $row)
          {
          $firstname =  $row->first_name;
          $lastname =  $row->last_name;
      }
  
  // get contact_id for to do case link
      $sql ='SELECT * FROM `civicrm_case_contact` WHERE case_id = '.$case_id;
      $db->setQuery($sql);
      $rows  = $db->loadObjectList();
          
      foreach ($rows as $row)
          {
          $cid =  $row->contact_id;
  
      }
      
      
  // get note 2
      $sql ='SELECT * FROM  `civicrm_case` WHERE `id` = '.$case_id;
      $db->setQuery($sql);    
      $rows  = $db->loadObjectList();
          
      foreach ($rows as $row)
          {
              $note2 =  $row->details;
          }
      
  
      $db->disconnect();
  
  $link = mysqli_connect("localhost", "user", "password", "DB") or die ("sorry");    
  $sql = 'SELECT `course` FROM `__eb_currencies` WHERE `id`=2';
  
  $euro = mysqli_query($link, $sql);
  $euro_1 = mysqli_fetch_assoc($euro);
  $euro_final0 = round($euro_1['course'] + $euro_1['course']*2/100, 2);
  mysqli_close($link);  
  
  $totalrub_first = round($euro_final0 * $firstpaymentandbankcomission, 0);
  $totalrub_second = round($euro_final0 * $secondpaymentandbankcomission, 0);
    
      $date = array('charter.vardump' => $vardump,'charter.cid' => $cid,'charter.caseid' => $case_id_forlink,'charter.clientlastname' => $lastname, 'charter.clientfirstname' => $firstname, 'charter.date_short' => date('d-m-Y'), 'charter.yachtmodel' => $model, 'charter.yachtname' => $yachtname, 'charter.numbercontract' => $order, 'charter.startdate' => $startofcharter, 'charter.enddate' => $endofcharter, 'charter.company' => $company, 'charter.companyemail' => $email, 'charter.companyphone' => $phone, 'charter.companyaddress' => $address, 'charter.country' => $country, 'charter.base' => $base, 'charter.days' => $days, 'charter.total' => $total, 'charter.firstpayment' => $firstpayment, 'charter.secondpayment' => $secondpayment, 'charter.extras' => $extras, 'charter.servicepack' => $servicepack, 'charter.deposit' => $deposit, 'charter.firstpaymentdate' => $first_payment_date, 'charter.secondpaymentdate' => $second_payment_date, 'charter.totalplusextras' => $totalplusextras, 'charter.paymentpluscomission' => $firstpaymentandbankcomission, 'charter.secondpaymentpluscomission' => $secondpaymentandbankcomission, 'charter.totalrubfirst' => $totalrub_first, 'charter.totalrubsecond' => $totalrub_second, 'charter.totaltocompany' => $totaltocompany, 'charter.firsttocompany' => $firstpaymenttocompany, 'charter.secondtocompany' => $secondpaymenttocompany, 'charter.ourcomission' => $ourcomission,'charter.note' => $note,'charter.note2' => $note2, 'charter.agentcomission' => $agentcomission
      );
      foreach ($cids as $cid) {
        $values[$cid] = empty($values[$cid]) ? $date : $values[$cid] + $date;
      }
    }
  }
  
  ```
  
  **Tags:** civicase, hooks
  
  > **Comments:**
  > **username_1**: How are you running cron? If running as the anonymous user joomla might not initialize a session.  
  > **username_0**: Like this: wget --no-check-certificate -O - -q -t 1 '<cron-url>?name=<username>&pass=<password>&key=<site-key>'  
  
  ---
  
  ## 1 answers
  
  ### Answer by username_2 on 2021-09-20. Score: 0
  
  **If you want the tokens only in the context of a schedule reminder, you should use the new better way to do tokens instead : [TokenProcessor](https://docs.civicrm.org/dev/en/latest/framework/token/#token-processor).**
  
  `hook_civicrm_tokenValues` is only working for `Contact` entity. You can't really add tokens on other entities like CiviCase using this hook.
  
  If you need the token to work in every contexts (transactional email, mass mailings, schedule reminders, Print/merge document) then you might consider the following workaround.
  
  If you are sure you can find the proper case\_id for the current contact, for example if it's the latest created or the only one of a certain type, then you could do something like :
  
  ```
  function example_civicrm_tokens() {
    $tokens['mytokens'] = [
      'mytokens.casetoken' => E::ts('Token related to a Case'),
    ];
  }
  
  function example_civicrm_tokenValues(&$values, $cids, $job = null, $tokens = array(), $context = null) {
  
    foreach ($cids as $cid) {
      $result = civicrm_api3('Case', 'get', [
        'sequential' => 1,
        'contact_id' => $cid,
        'case_type_id' => ...
      ]);
      if ($result['count'] == 1) {
        $case_id = $result['values'][0]['id'];
        // do your stuff now that you have a $case_id for the current contact
        $values[$cid]['mytokens.casetoken'] = ...
      }
      else {
        // case_id is either non existent or gives several results which is not workable
        // let's keep token empty
        $values[$cid]['mytokens.casetoken'] = '';
      }
    }
  
  }
  
  ```
  
  > **Comments:**
  > **username_0**: Thank you very much for your reply and advice about TokenProcessor.   As well thanks for code, but I'm not sure if I can find the right case_id for the current contact, because each contact can have many of the same cases by type and creation time.    Maybe you have an idea how to get the current activity_id which was executed by Cron Job... For me will be easy to resolve the thing when i'll get this variable.  
  > **username_2**: No sorry, only contact_id is provided using hook_civicirm_tokenValues. You really need to use TokenProcessor in that case.  
  
  ---
  
  