source: sandbox/workflow/branches/993/inc/class.bo_agent_mail_smtp.inc.php @ 2492

Revision 2492, 28.7 KB checked in by pedroerp, 14 years ago (diff)

Ticket #993 - Trocando acessos à GLOBALS por acessos à Settings.

  • Property svn:executable set to *
Line 
1<?php
2/**************************************************************************\
3* eGroupWare Workflow - Mail SMTP Agent Connector - business layer         *
4* ------------------------------------------------------------------------ *
5* This program is free software; you can redistribute it and/or modify it  *
6* under the terms of the GNU General Public License as published           *
7* by the Free Software Foundation; either version 2 of the License, or     *
8* any later version.                                                       *
9\**************************************************************************/
10
11require_once(dirname(__FILE__) . SEP . 'class.bo_agent.inc.php');
12
13//some define for the send mode
14if (!defined('_SMTP_MAIL_AGENT_SND_COMP'))              define('_SMTP_MAIL_AGENT_SND_COMP'    , 0);
15if (!defined('_SMTP_MAIL_AGENT_SND_POST'))              define('_SMTP_MAIL_AGENT_SND_POST'        , 1);
16if (!defined('_SMTP_MAIL_AGENT_SND_AUTO_PRE'))  define('_SMTP_MAIL_AGENT_SND_AUTO_PRE', 2);
17if (!defined('_SMTP_MAIL_AGENT_SND_AUTO_POS'))  define('_SMTP_MAIL_AGENT_SND_AUTO_POS', 3);
18/**
19 * This class connects the workflow agent to the egroupware phpmailer and emailadmin
20 * This let the workflow activities send emails. It contains some logic to replace
21 * known tokens by workflow information (user, owner, activity name, etc...)
22 *
23 * @package Workflow
24 * @license http://www.gnu.org/copyleft/gpl.html GPL
25 * @author regis.leroy@glconseil.com
26 */     
27class bo_agent_mail_smtp extends bo_agent
28{
29        /**
30         * @var array $public_functions Public functions
31         * @access public
32         */
33        var $public_functions = array(
34                'bo_agent_mail_smtp'                    => true,
35                'load'                                                  => true,
36                'save'                                                  => true,
37                'getAdminActivityOptions'               => true,
38                'decode_fields_in_final_array'  => true,
39        );
40        /**
41         * @var object $mail the phpmailer object used at runtime to send email
42         * @access public
43         */
44        var $mail = null;       
45        /**
46         * @var object $bo_emailadmin object the emailadmin bo object to retriev egroupware mail configuration
47         * @access public
48         */
49        var $bo_emailadmin = null;             
50        /**
51         * @var integer $profileID profile ID
52         * @access public
53         */
54        var $profileID;
55        // some maybe usefull egroupware or engine objects. Vars usefull to create only the first time
56        // to avoid multiple SQL queries
57        /**
58         * @var object $role_manager Role manager
59         * @access public
60         */
61        var $role_manager;
62        /**
63         * @var object $account The account
64         * @access public
65         */
66        var $account;
67        /**
68         * @var string $process_name The process name
69         * @access public
70         */
71        var $process_name = '';
72        /**
73         * @var string $process_version The process version
74         * @access public
75         */
76        var $process_version = '';
77        /**
78         * @var integer $process_id The process id
79         * @access public
80         */
81        var $process_id = '';
82        /**
83         * @var object $activity_id The activity id
84         * @access public
85         */
86        var $activity_id = '';
87        /**
88         * @var integer $instance_id The instance id
89         * @access public
90         */
91        var $instance_id = '';
92        /**
93         * @var array $final_array array containing part or this->fields recomputed to handle real email address and real values
94         * @access public
95         */
96        var $final_array = Array();     
97        /**
98         * @var boolean $debugmode can be usefull to test mails building without sending them
99         * @access public
100         */
101        var $debugmode = false;
102       
103        /**
104         * Contructor
105         * @access public
106         * @return object
107         */
108        function bo_agent_mail_smtp()
109        {
110                parent::bo_agent();
111                $this->so_agent = Factory::getInstance('so_agent_mail_smtp');
112                $this->bo_emailadmin = Factory::getInstance('bo');
113                //the showProcessConfigurationFields is not done here, quite harder to build
114                $this->ProcessConfigurationFieldsdefault = array(
115                        'mail_smtp_profile'             => false,
116                        'mail_smtp_signature'           => lang('Mail automatically sent by Mail SMTP Agent for eGroupware\'s Workflow'),
117                        'mail_smtp_local_link_prefix'   => '',
118                        'mail_smtp_debug'               => false,
119                );
120               
121                $this->title = lang('Mail Smtp Agent');
122                $this->description = lang('This agent gives the activity the possibility to send an SMTP message (mail)');
123                $this->help = lang('Use <a href="%1">EmailAdmin</a> to create mail profiles', $GLOBALS['phpgw']->link('/index.php',array('menuaction' => 'emailadmin.ui.listProfiles')));
124                $this->help .= "<br />\n".lang('Mails can be sent at the begining or at the end of the activity, For interactive activities only it can be sent after completion.');
125                $this->help .= "<br />\n".lang('Be carefull with interactive activity, end and start of theses activities are multiple.');
126                $this->help .= "<br />\n".lang('You can use special values with this mail agent:');
127                $this->help .= "<ul>\n";
128                $this->help .=  '<li>'.lang('<strong>%user%</strong> is the instance user email')."\n";
129                $this->help .=  '<li>'.lang('<strong>%owner%</strong> is the instance owner email')."\n";
130                $this->help .=  '<li>'.lang('<strong>%roles%</strong> are the emails of all users mapped to any role on this activity')."\n";
131                $this->help .=  '<li>'.lang('<strong>%role_XX%</strong> are all the emails of all users mapped to the role XX')."\n";
132                $this->help .=  '<li>'.lang('<strong>%user_XX%</strong> is the email of the acount XX')."\n";
133                $this->help .=  '<li>'.lang('<strong>%property_XX%</strong> is the content of the instance\'s property XX')."\n";
134                $this->help .=  '<li>'.lang('<strong>%signature%</strong> is the agent signature defined in the process configuration')."\n";
135                $this->help .=  '<li>'.lang('see as well <strong>%instance_name%</strong>, <strong>%activity_name%</strong>, <strong>%process_name%</strong>,<strong>%process_version%</strong>, <strong>%instance_id%</strong>, <strong>%activity_id%</strong> and <strong>%process_id%</strong>')."\n";
136                $this->help .=  '<li>'.lang('finally you have links with <strong>%link_XX|YY%</strong> syntax, XX is the address part, YY the text part.')."\n";
137                $this->help .= lang('Link addresses are considered local if not containing <strong>http://</strong>. They will get appended the configured local prefix and scanned by egroupware link engine');
138                $this->help .= "</ul>\n";
139                $this->fields = array(
140                        'wf_to'         => array(
141                                'type'          => 'text',
142                                'label'         => lang('To:'),
143                                'size'          => 255,
144                                'value'         => '',
145                                ),
146                        'wf_cc'         => array(
147                                'type'          => 'text',
148                                'label'         => lang('Cc:'),
149                                'size'          => 255,
150                                'value'         => '',
151                                ),
152                        'wf_bcc'        => array(
153                                'type'          => 'text',
154                                'label'         => lang('Bcc:'),
155                                'size'          => 255,
156                                'value'         => '',
157                                ),
158                        'wf_from'       => array(
159                                'type'          => 'text',
160                                'label'         => lang('From:'),
161                                'size'          => 255,
162                                'value'         => '',
163                                ),
164                        'wf_replyto'    => array(
165                                'type'          => 'text',
166                                'label'         => lang('ReplyTo:'),
167                                'size'          => 255,
168                                'value'         => '',
169                                ),
170                        'wf_subject'    => array(
171                                'type'          => 'text',
172                                'label'         => lang('Subject:'),
173                                'size'          => 255,
174                                'value'         => '',
175                                ),
176                        'wf_message'    => array(
177                                'type'          => 'textarea',
178                                'label'         => lang('Message:'),
179                                'value'         => '',
180                                ),
181                        'wf_send_mode'  => array(
182                                'type'  => 'select',
183                                'label' => lang('When to send the Message:'),
184                                'value' => '',
185                                'values'=>  array(
186                                        _SMTP_MAIL_AGENT_SND_COMP       => lang('send after interactive activity is completed'),
187                                        /*_SMTP_MAIL_AGENT_SND_POST     => lang("send when wf_agent_mail_smtp['submit_send'] is posted"),*/
188                                        _SMTP_MAIL_AGENT_SND_AUTO_PRE   => lang("send when the activity is starting"),
189                                        _SMTP_MAIL_AGENT_SND_AUTO_POS   => lang("send when the activity is ending"),
190                                        ),
191                                ),
192                );
193               
194        }
195
196   /**
197        * Factory: Load the agent values stored somewhere in the agent object and retain the agent id
198        * @param int $agent_id is the agent id
199        * @param bool $really_load boolean, true by default, if false the data wont be loaded from database and
200        * the only thing done by this function is storing the agent_id (usefull if you know you wont need actual data)
201        * @return bool  false if the agent cannot be loaded, true else
202        * @access public
203        */
204        function load($agent_id, $really_load=true)
205        {
206                //read values from the so_object
207                if ($really_load)
208                {
209                        $values =& $this->so_agent->read($agent_id);
210                        foreach($values as $key => $value)
211                        {
212                                //load only known fields
213                                if (isset($this->fields[$key]))
214                                {
215                                        $this->fields[$key]['value'] = $value;
216                                        //echo "<br> DEBUG loading value $value for $key";
217                                }
218                        }
219                }
220                //store the id
221                $this->agent_id = $agent_id;
222        }
223
224        /**
225         * Save the agent
226         * @return bool false if the agent cannot be saved, true else
227         * @access public
228         */
229        function save()
230        {
231                //make a simplified version of $this->fields with just values
232                $simplefields = Array();
233                foreach ($this->fields as $field => $arrayfield)
234                {
235                        $simplefields[$field] = $arrayfield['value'];
236                }
237                return $this->so_agent->save($this->agent_id, $simplefields);
238        }
239       
240        /**
241         * Lists activity level options avaible for the agent
242         * @return array an associative array which can be empty
243         * @access public
244         */
245        function getAdminActivityOptions ()
246        {
247                return $this->fields;
248        }
249       
250        /**
251         * This function tell the engine which process level options have to be set
252         * for the agent. Theses options will be initialized for all processes by the engine
253         * and can be different for each process.
254         * @return array an array which can be empty
255         * @access public
256         */
257        function listProcessConfigurationFields()
258        {
259                $profile_list = $this->bo_emailadmin->getProfileList();
260                foreach($profile_list as $profile)
261                {
262                        $my_profile_list[$profile['profileID']] = $profile['description'];
263                }
264                $this->showProcessConfigurationFields = array(
265                        'Mail SMTP Agent'               => 'title',
266                        'mail_smtp_profile'             => $my_profile_list,
267                        'mail_smtp_signature'           => 'text',
268                        'mail_smtp_local_link_prefix'   => 'text',
269                        'mail_smtp_debug'               => 'yesno',
270                );
271                return $this->showProcessConfigurationFields;
272        }
273
274        /**
275         * Return the SMTP config values stored by the emailadmin egw application
276         * @return array an associative array containing the'emailConfigValid' token at true if it was ok, and at false else
277         * @access public
278         */
279        function getSMTPConfiguration()
280        {
281                $data =Array();
282                $this->profileID = $this->conf['mail_smtp_profile'];
283                $data['emailConfigValid'] = true;
284                //code inspired by felamimail bo_preferences
285                $profileData = $this->bo_emailadmin->getProfile($this->profileID);
286                if(!is_array($profileData))
287                {
288                        $data['emailConfigValid'] = false;
289                        return $data;
290                }
291                elseif ($this->profileID != $profileData['profileID'])
292                {
293                        $this->profileID = $profileData['profileID'];
294                }
295               
296                // set values to the global values
297                $data['defaultDomain']          = $profileData['defaultDomain'];
298                $data['smtpServerAddress']      = $profileData['smtpServer'];
299                $data['smtpPort']               = $profileData['smtpPort'];
300                $data['smtpAuth']               = $profileData['smtpAuth'];
301                $data['smtpType']               = $profileData['smtpType'];
302                $useremail = $this->bo_emailadmin->getAccountEmailAddress(Settings::get('expresso', 'user', 'userid'), $this->profileID);
303                $data['emailAddress']           = $useremail[0]['address'];
304                return $data;
305        }
306       
307        /**
308         * Initialize objects we will need for the mailing and retrieve the conf
309         * @return void
310         * @access public
311         */
312        function init()
313        {
314                $this->mail = Factory::getInstance('phpmailer');
315                //set the $this->conf
316                $this->getProcessConfigurationFields($this->activity->getProcessId());
317                if ($this->conf['mail_smtp_debug']) $this->debugmode = true;
318               
319        }
320       
321        /**
322         * Says that we send email on POSTed forms
323         * @return bool true if the conf says that we send email on POSTed forms, else false.
324         * @access public
325         */
326        function sendOnPosted()
327        {
328                return ($this->fields['wf_send_mode']['value']== _SMTP_MAIL_AGENT_SND_POST);
329        }
330       
331        /**
332         * If this activity is defined as an activity sending the email when starting we'll send it now
333         * WARNING : on interactive queries the user code is parsed several times and this function is called
334         * each time you reach the begining of the code, this means at least the first time when you show the form
335         * and every time you loop on the form + the last time when you complete the code (if the user did not cancel).
336         * @return bool true if everything was ok, false if something went wrong
337         * @access public
338         */
339        function send_start()
340        {
341                if ($this->fields['wf_send_mode']['value']== _SMTP_MAIL_AGENT_SND_AUTO_PRE)
342                {
343                        if ($this->debugmode) $this->error[] = 'Sending at the start of the activity';
344                        if (!($this->prepare_mail())) return false;
345                        return $this->send();
346                }
347                else
348                {
349                        if ($this->debugmode) $this->error[] = 'Not sending at the start of the activity';
350                        return true;
351                }
352        }
353
354        /**
355         * If this activity is defined as an activity sending the email when finishing the code we'll send it now
356         * WARNING : on interactive queries the user code is parsed several times and this function is called
357         * each time you reach the end of the code without completing, this means at least the first time
358         * and every time you loop on the form.
359         * @return bool true if everything was ok, false if something went wrong
360         * @access public
361         */
362        function send_end()
363        {
364                if ($this->fields['wf_send_mode']['value']== _SMTP_MAIL_AGENT_SND_AUTO_POS)
365                {
366                        if ($this->debugmode) $this->error[] = 'Sending at the end of the activity';
367                        if (!($this->prepare_mail())) return false;
368                        return $this->send();
369                }
370                else
371                {
372                        if ($this->debugmode) $this->error[] = 'Not sending at the end of the activity';
373                        return true;
374                }
375        }
376
377        /**
378         * If this activity is defined as an activity sending the email when the user post a command for it we'll send it now
379         * @return bool true if everything was ok, false if something went wrong
380         * @access public
381         */
382        function send_post()
383        {
384                if ($this->fields['wf_send_mode']['value']== _SMTP_MAIL_AGENT_SND_POST)
385                {
386                        if ($this->debugmode) $this->error[] = 'Sending at POST in the activity';
387                        if (!($this->prepare_mail())) return false;
388                        return $this->send();
389                }
390                else
391                {
392                        if ($this->debugmode) $this->error[] = 'Not sending at POST in the activity';
393                        return true;
394                }
395        }
396       
397        /**
398         * If this activity is defined as an activity sending the email when completing we'll send it now
399         * @return bool true if everything was ok, false if something went wrong
400         * @access public
401         */
402        function send_completed()
403        {
404                if ($this->fields['wf_send_mode']['value']== _SMTP_MAIL_AGENT_SND_COMP)
405                {
406                        if ($this->debugmode) $this->error[] = 'Sending when completing activity';
407                        if (!($this->prepare_mail())) return false;
408                        return $this->send();
409                }
410                else
411                {
412                        if ($this->debugmode) $this->error[] = 'Not Sending when completing activity';
413                        return true;
414                }
415        }
416
417        /**
418         * Buid the email fields
419         * @return boolean true ok false error
420         * @access public
421         */
422        function prepare_mail()
423        {
424                $userLang = Settings::get('expresso', 'preferences', 'lang');
425                $langFile = PHPGW_SERVER_ROOT."/phpgwapi/setup/phpmailer.lang-$userLang.php";
426                if(file_exists($langFile))
427                {
428                        $this->mail->SetLanguage($userLang, PHPGW_SERVER_ROOT."/phpgwapi/setup/");
429                }
430                else
431                {
432                        $this->mail->SetLanguage("en", PHPGW_SERVER_ROOT."/phpgwapi/setup/");
433                }
434                $this->mail->PluginDir = PHPGW_SERVER_ROOT."/phpgwapi/inc/";
435                $this->mail->IsSMTP();
436               
437                //SMTP Conf
438                $smtpconf =& $this->getSMTPConfiguration();
439                if (!($smtpconf['emailConfigValid']))
440                {
441                        $this->error[] = lang('The SMTP configuration cannot be loaded by the mail_smtp workflow agent');
442                        return false;
443                }
444                $this->mail->Host       = $smtpconf['smtpServerAddress'];
445                $this->mail->Port       = $smtpconf['smtpPort'];
446                //SMTP Auth?
447                if ($smtpconf['smtpAuth'])
448                {
449                        $this->mail->SMTPAuth   = true;
450                        $this->mail->Username   = Settings::get('expresso', 'user', 'userid');
451                        $this->mail->Password   = Settings::get('expresso', 'user', 'passwd');
452                }
453               
454                $this->mail->Encoding = '8bit';
455                //TODO: handle Charset
456                //$this->mail->CharSet  = $this->displayCharset;
457                $this->mail->AddCustomHeader("X-Mailer: Egroupware Workflow");
458                $this->mail->WordWrap = 76;
459                //we need HTMl for handling nicely links
460                $this->mail->IsHTML(true);
461                //compute $this->final_fields if not done already
462                if (!( $this->decode_fields_in_final_fields($smtpconf['defaultDomain']) ))
463                {
464                        $this->error[] = lang('We were not able to build the message');
465                        return false;
466                }
467
468                $process = Factory::getInstance('workflow_process');
469                $process->getProcess($this->process_id);
470                $this->process_name = $process->getName();
471                $this->process_version = $process->getVersion();
472                unset ($process);
473               
474                $this->mail->From       = $this->mail->EncodeHeader($this->final_fields['wf_from']);
475                //$this->mail->FromName         = $this->activity->getName();
476                $this->mail->FromName   = $this->process_name;
477                $this->mail->Subject    = $this->mail->EncodeHeader($this->final_fields['wf_subject']);
478                $this->mail->Body       = str_replace("\n",'<br />',html_entity_decode($this->final_fields['wf_message']));
479                // if you need compatibility to older email clients (e.g. mutt), uncomment the line below
480                //$this->mail->AltBody  = $this->final_fields['wf_message'];
481                $this->mail->ClearAllRecipients();
482                foreach ($this->final_fields['wf_to'] as $email)
483                {
484                        if (!(empty($email))) $this->mail->AddAddress($email);
485                }
486                foreach ($this->final_fields['wf_cc'] as $email)
487                {
488                        if (!(empty($email))) $this->mail->AddCC($email);
489                }
490                foreach ($this->final_fields['wf_bcc'] as $email)
491                {
492                        if (!(empty($email))) $this->mail->AddBCC($email);
493                }
494                $email = $this->final_fields['wf_replyto'];
495                if (!(empty($email))) $this->mail->AddReplyTo($email);
496                return true;
497        }
498       
499        /**
500          * This function is used to decode admin instructions about the final value or the activity fields.
501          *
502          *  i.e.: decoding %user% in toto@foo.com for example
503          *     If you call this function twice the final result will NOT be recalculated. except with the $force
504          *     parameter. This is done so that you can call this function sooner than the engine and add or remove
505          *     emails from final fields. The engine will not recompute automatically theses fields if you done it already.
506          * @param string $defaultDomain is the default mail Domain, used with empty domains
507          * @param bool $force is falmse by default, if true the final are recalculated even if they are already there
508          * @return bool true/false and set the $this->final_fields array containing the fields with the 'real' final value and for
509          * the wf_to, wf_bcc and wf_cc fields you'll have arrays with email values.
510          * @access public
511         */
512        function decode_fields_in_final_fields($defaultDomain, $force=false)
513        {
514                if ($force || (!(isset($this->final_fields['calculated']))) )
515                {
516                        $res = Array();
517                        $result = Array();
518                        $address_array = Array();
519                        $email_list = Array();
520                        foreach ($this->fields as $key => $value)
521                        {
522                                $res[$key] =& $this->replace_tokens($value['value']);
523                                //for all adresse fields we make an email array to detect repetitions
524                                if (($key=='wf_to') || ($key=='wf_cc') || ($key=='wf_bcc'))
525                                {
526                                         //_debug_array($res[$key]);//DEBUG
527                                         //clean ',,' or ', ,'  or starting or ending by ','
528                                         $res[$key] = $this->cleanup_adress_string($res[$key]);
529                                        //_debug_array($res[$key]);//DEBUG
530                                       
531                                        //warning, need to handle < and > as valid chars for emails
532                                        $address_array  = imap_rfc822_parse_adrlist(str_replace('&gt;','>',str_replace('&lt;','<',$res[$key])),'');
533                                        //_debug_array($address_array);//DEBUG
534                                        if (is_array($address_array) && (!(empty($address_array))))
535                                        {
536                                                foreach ($address_array as $val)
537                                                {
538                                                        //we retain this email is used in To or Bcc or Cc
539                                                        //and we affect this email only the first time
540                                                        //first detect errors
541                                                        if ($val->host == '.SYNTAX-ERROR.')
542                                                        {
543                                                                $this->error[] = lang("at least one email address cannot be validated.");
544                                                                if ($this->debugmode)
545                                                                {
546                                                                        $this->error[] = $res[$key];
547                                                                }
548                                                                return false;
549                                                        }
550                                                        //detect empty domains
551                                                        if (empty($val->host))
552                                                        {
553                                                                $val->host = $defaultDomain;
554                                                        }
555                                                        //build email adress
556                                                        $his_email = $val->mailbox.'@'. $val->host;
557                                                        if (!isset($email_list[$his_email]))
558                                                        {
559                                                                $email_list[$his_email] = $key;
560                                                                $result[$key][]= $his_email;
561                                                        }
562                                                }
563                                        }
564                                        else
565                                        {
566                                                $result[$key] = Array();
567                                        }
568                                }
569                                elseif ( ($key=='wf_from') || ($key=='wf_replyto'))
570                                {
571                                        //warning, need to handle < and > as valid chars for emails
572                                        $result[$key] = str_replace('&gt;','>',str_replace('&lt;','<',$res[$key]));
573                                }
574                                else
575                                {
576                                        $result[$key] = $res[$key];
577                                }
578                        }
579                        $this->final_fields =& $result;
580                        $this->final_fields['calculated']=true;
581                }
582                return true;
583        }
584
585        /**
586         * This function will clean ',,' or ', ,'  or starting or ending by ',' in the email address string list.
587         * @param string $address_string is the string we should clean
588         * @return string the cleaned up string
589         * @access public
590         */
591        function cleanup_adress_string($address_string)
592        {
593                //in PHP5 we could ve been using the count parameter to stop recursivity
594                $new = str_replace(array(', ,' , ',,'),array(',', ','),trim(trim($address_string),','));
595                if ($new == $address_string)
596                {
597                        //it did nothing, lets stop recursivity
598                        return $new;
599                }
600                {
601                        //we made sime changes, lets verify the new string is syntaxically correct, recursivity
602                        return $this->cleanup_adress_string($new);
603                }
604        }
605
606        /**
607         * This function is used to find and replace tokens in the fields
608         * @param string $string is the string to analyse
609     * @return string the modified string
610     * @access public
611         */
612        function replace_tokens(&$string)
613        {
614                //first we need to escape the \% before the analysis
615                $string = str_replace('\%','&workflowpourcent;',$string);
616                $matches = Array();
617                preg_match_all("/%([^%]+)%/",$string, $matches);
618                $final = $string;
619                if ($this->activity_id =='') $this->activity_id = $this->activity->getActivityId();
620                if ($this->instance_id =='') $this->instance_id = $this->instance->getInstanceId();
621                if ($this->process_id =='') $this->process_id = $this->activity->getProcessId();
622                foreach($matches[1] as $key => $value)
623                {
624                        //$value is our %token%
625                        switch($value)
626                        {
627                                case 'signature':
628                                                        $matches[1][$key] = $this->conf['mail_smtp_signature'];
629                                                        break;
630                                case 'instance_name' :
631                                        $matches[1][$key] = $this->instance->getName();
632                                        break;
633                                case 'activity_name' :
634                                        $matches[1][$key] = $this->activity->getName();
635                                        break;
636                                case 'process_name' :
637                                        if ($this->process_name=='')
638                                        {
639                                                $process = Factory::getInstance('workflow_process');
640                                                $process->getProcess($this->process_id);
641                                                $this->process_name = $process->getName();
642                                                $this->process_version = $process->getVersion();
643                                                unset ($process);
644                                        }
645                                        $matches[1][$key] = $this->process_name;
646                                        break;
647                                case 'process_version' :
648                                        if ($this->process_version=='')
649                                        {
650                                                $process = Factory::getInstance('workflow_process');
651                                                $process->getProcess($this->process_id);
652                                                $this->process_name = $process->getName();
653                                                $this->process_version = $process->getVersion();
654                                                unset ($process);
655                                        }
656                                        $matches[1][$key] = $this->process_version;
657                                        break;
658                                case 'process_id' :
659                                        $matches[1][$key] = $this->process_id;
660                                        break;
661                                case 'instance_id' :
662                                        $matches[1][$key] = $this->instance_id;
663                                        break;
664                                case 'activity_id' :
665                                        $matches[1][$key] = $this->activity_id;
666                                        break;
667                                case 'user' :
668                                        //the current instance/activity user which is in fact running
669                                        //this class actually
670                                        $matches[1][$key] = Settings::get('expresso', 'user', 'email');
671                                        break;
672                                case 'owner' :
673                                        //the owner of the instance
674                                        if (!is_object($this->account))
675                                        {
676                                                $this->account = Factory::getInstance('accounts');
677                                        }
678                                        $ask_user = $this->instance->getOwner();
679                                        $matches[1][$key] = $this->account->id2name($ask_user, 'account_email');
680                                        break;
681                                case 'roles' :
682                                        //all users having at least one role on this activity
683                                        if (!is_object($this->role_manager))
684                                        {
685                                                $this->role_manager = Factory::getInstance('workflow_rolemanager');
686                                        }
687                                        if (!is_object($this->account))
688                                        {
689                                                $this->account = Factory::getInstance('accounts');
690                                        }
691                                        $my_subset = array('wf_activity_name' => $this->activity->getName());
692                                        $listing =& $this->role_manager->list_mapped_users($this->instance->getProcessId(),true, $my_subset);
693                                        $matches[1][$key] = '';
694                                        foreach ($listing as $user_id => $user_name)
695                                        {
696                                                $user_email = $this->account->id2name($user_id);
697                                                if ($matches[1][$key] == '')
698                                                {
699                                                        $matches[1][$key] = $this->account->id2name($user_id, 'account_email');
700                                                }
701                                                else
702                                                {
703                                                        $matches[1][$key] .= ', '.$this->account->id2name($user_id, 'account_email');
704                                                }
705                                        }
706                                        break;
707                                default:
708                                        //Now we need to handle role_foo or property_bar or user_foobar
709                                        $matches2 = Array();
710                                        //echo "<br>2nd analysis on ".$value;
711                                        preg_match_all("/([^_]+)([_])([A-z0-9\|:\/\.\?\=\'\&\; ]*)/",$value, $matches2);
712                                        $first_part = $matches2[1][0];
713                                        $second_part = $matches2[3][0];
714                                        switch ($first_part)
715                                        {
716                                                case 'user' :
717                                                        //we retrieve the asked user email
718                                                        if (!is_object($this->account))
719                                                        {
720                                                                $this->account = Factory::getInstance('accounts');
721                                                        }
722                                                        $ask_user = $this->account->name2id($second_part);
723                                                        $matches[1][$key] = $this->account->id2name($ask_user, 'account_email');
724                                                        break;
725                                                case 'property' :
726                                                        //we take the content of the given property on the instance
727                                                        $matches[1][$key] = $this->instance->get($second_part);
728                                                        break;
729                                                case 'role' :
730                                                        //all user mapped to this role
731                                                        if (!is_object($this->role_manager))
732                                                        {
733                                                                $this->role_manager = Factory::getInstance('workflow_rolemanager');
734                                                        }
735                                                        if (!is_object($this->account))
736                                                        {
737                                                                $this->account = Factory::getInstance('accounts');
738                                                        }
739                                                        $my_subset = array('wf_role_name' => $second_part);
740                                                        $listing =& $this->role_manager->list_mapped_users($this->instance->getProcessId(),true, $my_subset);
741                                                        $matches[1][$key] = '';
742                                                        foreach ($listing as $user_id => $user_name)
743                                                        {
744                                                                $user_email = $this->account->id2name($user_id);
745                                                                if ($matches[1][$key] == '')
746                                                                {
747                                                                        $matches[1][$key] = $this->account->id2name($user_id, 'account_email');
748                                                                }
749                                                                else
750                                                                {
751                                                                        $matches[1][$key] .= ', '.$this->account->id2name($user_id, 'account_email');
752                                                                }
753                                                        }
754                                                        break;
755                                                case 'link' :
756                                                        //we want a link
757                                                        //the HTML characters are escaped, so we need this function
758                                                        //and we now some usefull links:
759                                                        //$second_part should be in this form link adress|text
760                                                        $matches3 = Array();
761                                                        //echo "<br>3rd analysis on ".$second_part;
762                                                        preg_match_all("/([^\|]+)([\|])([A-z0-9 \'\&\;]*)/",$second_part, $matches3);
763                                                        $link_part = $matches3[1][0];
764                                                        $text_part = $matches3[3][0];
765                                                        //need something in the text
766                                                        if (empty($text_part)) $text_part=$link_part;
767                                                        //and something in the link
768                                                        switch ($link_part)
769                                                        {
770                                                                default:
771                                                                        //now it can be an external or local link
772                                                                        if (substr($link_part,0,7)=='http://')
773                                                                        {//external link
774                                                                                $my_link = $link_part;
775                                                                        }
776                                                                        else
777                                                                        {//local link
778                                                                                $my_link = $this->conf['mail_smtp_local_link_prefix'].$GLOBALS['phpgw']->link($link_part);
779                                                                        }
780                                                        }
781                                                        $matches[1][$key] = '<a href="'.$my_link.'">'.$text_part.'</a>';
782                                                        break;
783                                               
784                                                default:
785                                                        $matches[1][$key] = '';
786                                        }
787                        }
788                        $final = str_replace($matches[0][$key],$matches[1][$key],$final);
789                }
790                //now get back the % escaped before the analysis
791                $final = str_replace('&workflowpourcent;','%',$final);
792                return $final;
793        }
794       
795        /**
796         * This function is used to send mail
797         * @return bool true ok false error
798         * @access public
799         */
800        function Send()
801        {
802                //$this->mail->SMTPDebug = 10;
803                if (!($this->debugmode))
804                {
805                        if(!$this->mail->Send())
806                        {
807                                if ($this->mail->ErrorInfo != $this->mail->Lang("data_not_accepted"))
808                                {
809                                        $this->error[] = $this->mail->ErrorInfo;
810                                        return false;
811                                }
812                        }
813                }
814                else
815                {
816                        //_debug_array($this->mail);
817                        $this->error[] = 'DEBUG mode: '.lang('if not in debug mail_smtp agent would have sent this email:');
818                        $this->error[] = 'DEBUG mode: Host:'.$this->mail->Host;
819                        $this->error[] = 'DEBUG mode: Port:'.$this->mail->Port;
820                        $this->error[] = 'DEBUG mode: From:'.htmlentities($this->mail->From);
821                        $this->error[] = 'DEBUG mode: FromName:'.htmlentities($this->mail->FromName);
822                        $msg = 'DEBUG mode: ReplyTo:';
823                        foreach ($this->mail->ReplyTo as $address)
824                        {
825                                $msg .= htmlentities($address[0]);
826                        }
827                        $this->error[] = $msg;
828                        $msg = 'DEBUG mode: To:';
829                        foreach ($this->mail->to as $address)
830                        {
831                                $msg .= htmlentities($address[0]);
832                        }
833                        $this->error[] = $msg;
834                        $msg = 'DEBUG mode: Cc:';
835                        foreach ($this->mail->cc as $address)
836                        {
837                                $msg .= htmlentities($address[0]);
838                        }
839                        $this->error[] = $msg;
840                        $msg = 'DEBUG mode: Bcc:';
841                        foreach ($this->mail->bcc as $address)
842                        {
843                                $msg .= ' '.htmlentities($address[0]);
844                        }
845                        $this->error[] = $msg;
846                        $this->error[] = 'DEBUG mode: Subject:'.htmlentities($this->mail->Subject);
847                        //$this->error[] = 'DEBUG mode: AltBody:'.htmlentities($this->mail->AltBody);
848                        $this->error[] = 'DEBUG mode: Body (hmtl):'.$this->mail->Body;
849                }
850                return true;
851        }
852       
853}
854?>
Note: See TracBrowser for help on using the repository browser.