DataObjects/I18n.php
[Pman.Core] / DataObjects / Person.php
1 <?php
2 /**
3  * Table Definition for Person
4  */
5 require_once 'DB/DataObject.php';
6
7
8 class Pman_Core_DataObjects_Person extends DB_DataObject 
9 {
10     ###START_AUTOCODE
11     /* the code below is auto generated do not remove the above tag */
12
13     public $__table = 'Person';                          // table name
14     public $id;                              // int(11)  not_null primary_key auto_increment
15     public $email;                           // string(128)  not_null
16     public $alt_email;
17     
18     public $company_id;                      // int(11)  
19     public $office_id;                       // int(11)  
20     public $name;                            // string(128)  not_null
21     public $firstname;                            // string(128)  not_null
22     public $lastname;                            // string(128)  not_null
23     public $phone;                           // string(32)  not_null
24     public $fax;                             // string(32)  not_null
25     
26     public $role;                            // string(32)  not_null
27     public $remarks;                         // blob(65535)  not_null blob
28     public $passwd;                          // string(64)  not_null
29     public $owner_id;                        // int(11)  not_null
30     public $lang;                            // string(8)  
31     public $no_reset_sent;                   // int(11)  
32     public $action_type;                     // string(32)  
33     public $project_id;                      // int(11)
34
35     
36     public $active;                          // int(11)  not_null
37     public $deleted_by;                      // int(11)  not_null
38     public $deleted_dt;                      // datetime(19)  binary
39
40
41     public $name_facebook; // VARCHAR(128) NULL;
42     public $url_blog; // VARCHAR(256) NULL ;
43     public $url_twitter; // VARCHAR(256) NULL ;
44     public $url_linkedin; // VARCHAR(256) NULL ;
45     public $linkedin_id; // VARCHAR(256) NULL ;
46     
47     public $phone_mobile; // varchar(32)  NOT NULL  DEFAULT '';
48     public $phone_direct; // varchar(32)  NOT NULL  DEFAULT '';
49     public $countries; // VARCHAR(128) NULL;
50     
51     /* the code above is auto generated do not remove the tag below */
52     ###END_AUTOCODE
53     
54     function owner()
55     {
56         $p = DB_DataObject::Factory('Person');
57         $p->get($this->owner_id);
58         return $p;
59     }
60     
61     /**
62      *
63      *
64      *
65      *
66      *  FIXME !!!! -- USE Pman_Core_Mailer !!!!!
67      *
68      *
69      *
70      *  
71      */
72     function buildMail($templateFile, $args)
73     {
74           
75         $args = (array) $args;
76         $content  = clone($this);
77         
78         foreach((array)$args as $k=>$v) {
79             $content->$k = $v;
80         }
81         
82         $ff = HTML_FlexyFramework::get();
83         
84         
85         //?? is this really the place for this???
86         if (
87                 !$ff->cli && 
88                 empty($args['no_auth']) &&
89                 !in_array($templateFile, array(
90                     // templates that can be sent without authentication.
91                      'password_reset' ,
92                      'password_welcome'
93                  ))
94             ) {
95             
96             $content->authUser = $this->getAuthUser();
97             if (!$content->authUser) {
98                 return PEAR::raiseError("Not authenticated");
99             }
100         }
101         
102         // should handle x-forwarded...
103         
104         $content->HTTP_HOST = isset($_SERVER["HTTP_HOST"]) ?
105             $_SERVER["HTTP_HOST"] :
106             (isset($ff->HTTP_HOST) ? $ff->HTTP_HOST : 'localhost');
107             
108         /* use the regex compiler, as it doesnt parse <tags */
109         
110         $tops = array(
111             'compiler'    => 'Flexy',
112             'nonHTML' => true,
113             'filters' => array('SimpleTags','Mail'),
114             //     'debug'=>1,
115         );
116         
117         
118         
119         if (!empty($args['templateDir'])) {
120             $tops['templateDir'] = $args['templateDir'];
121         }
122         
123         
124         
125         require_once 'HTML/Template/Flexy.php';
126         $template = new HTML_Template_Flexy( $tops );
127         $template->compile("mail/$templateFile.txt");
128         
129         /* use variables from this object to ouput data. */
130         $mailtext = $template->bufferedOutputObject($content);
131         
132         $htmlbody = false;
133         // if a html file with the same name exists, use that as the body
134         // I've no idea where this code went, it was here before..
135         if (false !== $template->resolvePath ( "mail/$templateFile.html" )) {
136             $tops['nonHTML'] = false;
137             $template = new HTML_Template_Flexy( $tops );
138             $template->compile("mail/$templateFile.html");
139             $htmlbody = $template->bufferedOutputObject($content);
140             
141         }
142         
143         
144         
145         //echo "<PRE>";print_R($mailtext);
146         //print_R($mailtext);exit;
147         /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
148         require_once 'Mail/mimeDecode.php';
149         require_once 'Mail.php';
150         
151         $decoder = new Mail_mimeDecode($mailtext);
152         $parts = $decoder->getSendArray();
153         
154         if (PEAR::isError($parts)) {
155             return $parts;
156             //echo "PROBLEM: {$parts->message}";
157             //exit;
158         } 
159         list($recipents,$headers,$body) = $parts;
160         $recipents = array($this->email);
161         if (!empty($content->bcc) && is_array($content->bcc)) {
162             $recipents =array_merge($recipents, $content->bcc);
163         }
164         $headers['Date'] = date('r');
165         
166         if ($htmlbody !== false) {
167             require_once 'Mail/mime.php';
168             $mime = new Mail_mime(array('eol' => "\n"));
169             $mime->setTXTBody($body);
170             $mime->setHTMLBody($htmlbody);
171             // I think there might be code in mediaoutreach toEmail somewhere
172             // h embeds images here..
173             $body = $mime->get();
174             $headers = $mime->headers($headers);
175             
176         }
177         
178          
179         
180         return array(
181             'recipients' => $recipents,
182             'headers'    => $headers,
183             'body'      => $body
184         );
185         
186         
187     }
188     
189     
190     /**
191      * send a template
192      * - user must be authenticate or args[no_auth] = true
193      *   or template = password_[reset|welcome]
194      * 
195      */
196     function sendTemplate($templateFile, $args)
197     {
198         
199         $ar = $this->buildMail($templateFile, $args);
200       
201         
202         //print_r($recipents);exit;
203         $mailOptions = PEAR::getStaticProperty('Mail','options');
204         $mail = Mail::factory("SMTP",$mailOptions);
205         
206         if (PEAR::isError($mail)) {
207             return $mail;
208         } 
209         $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
210         $ret = $mail->send($ar['recipients'],$ar['headers'],$ar['body']);
211         error_reporting($oe);
212        
213         return $ret;
214     
215     }
216     
217   
218     
219     
220     function getEmailFrom()
221     {
222         if (empty($this->name)) {
223             return $this->email;
224         }
225         return '"' . addslashes($this->name) . '" <' . $this->email . '>';
226     }
227     
228     function toEventString() 
229     {
230         return empty($this->name) ? $this->email : $this->name;
231     } 
232     
233     function verifyAuth()
234     { 
235         $ff= HTML_FlexyFramework::get();
236         if (!empty($ff->Pman['auth_comptype']) &&
237             (!$this->company_id || ($ff->Pman['auth_comptype'] != $this->company()->comptype))
238            ){
239             
240             // force a logout - without a check on the isAuth - as this is called from there..
241             $db = $this->getDatabaseConnection();
242             $sesPrefix = $ff->appNameShort .'-'.get_class($this) .'-'.$db->dsn['database'] ;
243             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
244             return false;
245             
246             $ff->page->jerr("Login not permited to outside companies");
247         }
248         return true;
249         
250     }    
251    
252    
253     //   ---------------- authentication / passwords and keys stuff  ----------------
254     function isAuth()
255     {
256         $db = $this->getDatabaseConnection();
257         // we combine db + project names,
258         // otherwise if projects use different 'auth' objects
259         // then we get unserialize issues.
260         $ff= HTML_FlexyFramework::get();
261         $sesPrefix = $ff->appNameShort .'-' .get_class($this) .'-'.$db->dsn['database'] ;
262         
263         
264         @session_start();
265          
266         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
267             // in session...
268             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
269             
270             $u = DB_DataObject::factory('Person');
271             if ($u->get($a->id)) { //&& strlen($u->passwd)) {
272               
273                 return $u->verifyAuth();
274                 
275    
276                 return true;
277             }
278             
279             unset($_SESSION[__CLASS__][$sesPrefix .'-auth']);
280             
281         }
282         // local auth - 
283         $default_admin = false;
284         if (!empty($ff->Pman['local_autoauth']) && 
285             ($ff->Pman['local_autoauth'] === true) &&
286             (!empty($_SERVER['SERVER_ADDR'])) &&
287             ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
288             ($_SERVER['REMOTE_ADDR'] == '127.0.0.1')
289         ) {
290             $group = DB_DataObject::factory('Groups');
291             $group->get('name', 'Administrators');
292             
293             $member = DB_DataObject::factory('group_members');
294             $member->autoJoin();
295             $member->group_id = $group->id;
296             $member->whereAdd("
297                 join_user_id_id.id IS NOT NULL
298             ");
299             if($member->find(true)){
300                 $default_admin = DB_DataObject::factory('Person');
301                 if(!$default_admin->get($member->user_id)){
302                     $default_admin = false;
303                 }
304             }
305         }
306         
307          
308         $u = DB_DataObject::factory('Person');
309         $ff = HTML_FlexyFramework::get();
310         if (!empty($ff->Pman['local_autoauth']) && 
311             (!empty($_SERVER['SERVER_ADDR'])) &&
312             ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
313             ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') &&
314             ($default_admin ||  $u->get('email', $ff->Pman['local_autoauth']))
315         ) {
316             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($default_admin ? $default_admin : $u);
317             return true;
318         }
319            
320         // http basic auth..
321         $u = DB_DataObject::factory('Person');
322
323         if (!empty($_SERVER['PHP_AUTH_USER']) 
324             &&
325             !empty($_SERVER['PHP_AUTH_PW'])
326             &&
327             $u->get('email', $_SERVER['PHP_AUTH_USER'])
328             &&
329             $u->checkPassword($_SERVER['PHP_AUTH_PW'])
330            ) {
331             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($u);
332             return true; 
333         }
334         //var_dump(session_id());
335         //var_dump($_SESSION[__CLASS__]);
336         
337         //if (!empty(   $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
338         //    return false;
339         //}
340         //die("got this far?");
341         // not in session or not matched...
342         $u = DB_DataObject::factory('Person');
343         $u->whereAdd(' LENGTH(passwd) > 0');
344         $n = $u->count();
345         $_SESSION[__CLASS__][$sesPrefix .'-empty']  = $n;
346         $error =  PEAR::getStaticProperty('DB_DataObject','lastError');
347         if ($error) {
348             die($error->toString()); // not really a good thing to do...
349         }
350         if (!$n){ // authenticated as there are no users in the system...
351             return true;
352         }
353         
354         return false;
355         
356     }
357     function getAuthUser()
358     {
359         if (!$this->isAuth()) {
360             return false;
361         }
362         $db = $this->getDatabaseConnection();
363         
364         $ff= HTML_FlexyFramework::get();
365         $sesPrefix = $ff->appNameShort .'-' .get_class($this) .'-'.$db->dsn['database'] ;
366
367         
368         
369         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
370             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
371             
372             $u = DB_DataObject::factory('Person');
373             if ($u->get($a->id)) { /// && strlen($u->passwd)) {
374                 return clone($u);
375             }
376             unset($_SESSION[__CLASS__][$sesPrefix .'-auth']);
377         }
378         
379         if (empty(   $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
380             $u = DB_DataObject::factory('Person');
381             $u->whereAdd(' LENGTH(passwd) > 0');
382             $_SESSION[__CLASS__][$sesPrefix .'-empty']  = $u->count();
383         }
384                 
385              
386         if (isset(   $_SESSION[__CLASS__][$sesPrefix .'-empty'] ) && $_SESSION[__CLASS__][$sesPrefix .'-empty']  < 1) {
387             
388             // fake person - open system..
389             //$ce = DB_DataObject::factory('core_enum');
390             //$ce->initEnums();
391             
392             
393             $u = DB_DataObject::factory('Person');
394             $u->id = -1;
395             
396             // if a company has been created fill that in in company_id_id
397             $c = DB_DAtaObject::factory('Companies')->lookupOwner();
398             if ($c) {
399                 $u->company_id_id = $c->pid();
400                 $u->company_id = $c->pid();
401             }
402             
403             return $u;
404             
405         }
406         return false;
407     }     
408     function login()
409     {
410         $this->isAuth(); // force session start..
411         if (!$this->verifyAuth()) {
412             return false;
413         }
414         $db = $this->getDatabaseConnection();
415         
416         
417         // open up iptables at login..
418         $dbname = $this->database();
419         touch( '/tmp/run_pman_admin_iptables-'.$dbname);
420          
421         // refresh admin group if we are logged in as one..
422         //DB_DataObject::debugLevel(1);
423         $g = DB_DataObject::factory('Groups');
424         $g->type = 0;
425         $g->get('name', 'Administrators');
426         $gm = DB_DataObject::Factory('group_members');
427         if (in_array($g->id,$gm->listGroupMembership($this))) {
428             // refresh admin groups.
429             $gr = DB_DataObject::Factory('group_rights');
430             $gr->applyDefs($g, 0);
431         }
432         $ff= HTML_FlexyFramework::get();
433         $sesPrefix = $ff->appNameShort .'-' .get_class($this) .'-'.$db->dsn['database'] ;
434
435
436         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($this);
437         
438     }
439     function logout()
440     {
441         $this->isAuth(); // force session start..
442         $db = $this->getDatabaseConnection();
443         $ff= HTML_FlexyFramework::get();
444         $sesPrefix = $ff->appNameShort .'-' .get_class($this) .'-'.$db->dsn['database'] ;
445
446         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
447        
448         
449        
450         
451     }    
452     function genPassKey ($t) 
453     {
454         return md5($this->email . $t. $this->passwd);
455     }
456     function simpleAuthKey($m = 0)
457     {
458         $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
459         
460         return md5(implode(',' ,  array($month, $this->email , $this->passwd, $this->id)));
461     } 
462     function checkPassword($val)
463     {
464         
465         if (substr($this->passwd,0,1) == '$') {
466             return crypt($val,$this->passwd) == $this->passwd ;
467         }
468         // old style md5 passwords...- cant be used with courier....
469         return md5($val) == $this->passwd;
470     }
471     function setPassword($value) 
472     {
473         $salt='';
474         while(strlen($salt)<9) {
475             $salt.=chr(rand(64,126));
476             //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
477         }
478         $this->passwd = crypt($value, '$1$'. $salt. '$');
479        
480        
481     }      
482     
483     function generatePassword() // genearte a password (add set 'rawPasswd' to it's value)
484     {
485         require_once 'Text/Password.php';
486         $this->rawPasswd = strtr(ucfirst(Text_Password::create(5)).ucfirst(Text_Password::create(5)), array(
487         "a"=>"4", "e"=>"3",  "i"=>"1",  "o"=>"0", "s"=>"5",  "t"=>"7"));
488         $this->setPassword($this->rawPasswd);
489         return $this->rawPasswd;
490     }
491     
492     function company()
493     {
494         $x = DB_DataObject::factory('Companies');
495         $x->autoJoin();
496         $x->get($this->company_id);
497         return $x;
498     }
499     function loadCompany()
500     {
501         $this->company = $this->company();
502     }
503     
504     function active()
505     { 
506         return $this->active;
507     }
508     function authUserName($n) // set username prior to acheck user exists query.
509     {
510         
511         $this->whereAdd('LENGTH(passwd) > 1'); 
512         $this->email = $n;
513     }
514     function lang()
515     {
516         if (!func_num_args()) {
517             return $this->lang;
518         }
519         $val = array_shift(func_get_args());
520         if ($val == $this->lang) {
521             return;
522         }
523         $uu = clone($this);
524         $this->lang = $val;
525         $this->update($uu);
526         return $this->lang;
527     }
528             
529     
530     function authUserArray()
531     {
532         
533         $aur = $this->toArray();
534         
535         if ($this->id < 1) {
536             return $aur;
537         }
538         
539         
540         //DB_DataObject::debugLevel(1);
541         $c = DB_Dataobject::factory('Companies');
542         $im = DB_Dataobject::factory('Images');
543         $c->joinAdd($im, 'LEFT');
544         $c->selectAdd();
545         $c->selectAs($c, 'company_id_%s');
546         $c->selectAs($im, 'company_id_logo_id_%s');
547         $c->id = $this->company_id;
548         $c->limit(1);
549         $c->find(true);
550         
551         $aur = array_merge( $c->toArray(),$aur);
552         
553         if (empty($c->company_id_logo_id_id))  {
554                  
555             $im = DB_Dataobject::factory('Images');
556             $im->ontable = 'Companies';
557             $im->onid = $c->id;
558             $im->imgtype = 'LOGO';
559             $im->limit(1);
560             $im->selectAdd();
561             $im->selectAs($im,  'company_id_logo_id_%s');
562             if ($im->find(true)) {
563                     
564                 foreach($im->toArray() as $k=>$v) {
565                     $aur[$k] = $v;
566                 }
567             }
568         }
569       
570         // perms + groups.
571         $aur['perms']  = $this->getPerms();
572         $g = DB_DataObject::Factory('group_members');
573         $aur['groups']  = $g->listGroupMembership($this, 'name');
574         
575         $aur['passwd'] = '';
576         $aur['dailykey'] = '';
577         
578         
579         
580         return $aur;
581     }
582     
583     //   ----------PERMS------  ----------------
584     function getPerms() 
585     {
586          //DB_DataObject::debugLevel(1);
587         // find out all the groups they are a member of.. + Default..
588         
589         // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
590         
591         $g = DB_DataObject::Factory('group_rights');
592         if (!$g->count()) {
593             $g->genDefault();
594         }
595         
596         if ($this->id < 0) {
597             return $g->adminRights(); // system is not set up - so they get full rights.
598         }
599         //DB_DataObject::debugLevel(1);
600         $g = DB_DataObject::Factory('group_members');
601         $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
602         if (!$g->count()) {
603             // add the current user to the admin group..
604             $g = DB_DataObject::Factory('Groups');
605             if ($g->get('name', 'Administrators')) {
606                 $gm = DB_DataObject::Factory('group_members');
607                 $gm->group_id = $g->id;
608                 $gm->user_id = $this->id;
609                 $gm->insert();
610             }
611             
612         }
613         
614         // ------ STANDARD PERMISSION HANDLING.
615         $isOwner = $this->company()->comptype == 'OWNER';
616         $g = DB_DataObject::Factory('group_members');
617         $grps = $g->listGroupMembership($this);
618        //var_dump($grps);
619         $isAdmin = $g->inAdmin;
620         //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
621         // the load all the perms for those groups, and add them all together..
622         // then load all those 
623         $g = DB_DataObject::Factory('group_rights');
624         $ret =  $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
625         //echo '<PRE>';print_r($ret);
626         return $ret;
627          
628         
629     }
630     /**
631      *Basic group fetching - probably needs to filter by type eventually.
632      *
633      *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
634      */
635     
636     function groups($what=false)
637     {
638         $g = DB_DataObject::Factory('group_members');
639         $grps = $g->listGroupMembership($this);
640         $g = DB_DataObject::Factory('Groups');
641         $g->whereAddIn('id', $grps, 'int');
642         return $g->fetchAll($what);
643         
644     }
645     
646     
647     
648     function hasPerm($name, $lvl) 
649     {
650         static $pcache = array();
651         
652         if (!isset($pcache[$this->id])) {
653             $pcache[$this->id] = $this->getPerms();
654         }
655        // echo "<PRE>";print_r($pcache[$au->id]);
656        // var_dump($pcache[$au->id]);
657         if (empty($pcache[$this->id][$name])) {
658             return false;
659         }
660         
661         return strpos($pcache[$this->id][$name], $lvl) > -1;
662         
663     }    
664     
665     //  ------------ROO HOOKS------------------------------------
666     function applyFilters($q, $au, $roo)
667     {
668         //DB_DataObject::DebugLevel(1);
669         if (!empty($q['query']['person_not_internal'])) {
670             $this->whereAdd(" join_company_id_id.isOwner = 0 ");
671         }
672         
673         if (!empty($q['query']['person_internal_only_all'])) {
674             
675             
676             // must be internal and not current user (need for distribution list)
677             // user has a projectdirectory entry and role is not blank.
678             //DB_DataObject::DebugLevel(1);
679             $pd = DB_DataObject::factory('ProjectDirectory');
680             $pd->whereAdd("role != ''");
681             $pd->selectAdd();
682             $pd->selectAdd('distinct(person_id) as person_id');
683             $roled = $pd->fetchAll('person_id');
684             $rs = $roled  ? "  OR
685                     {$this->tableName()}.id IN (".implode(',', $roled) . ") 
686                     " : '';
687             $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
688             
689         }
690         // -- for distribution
691         if (!empty($q['query']['person_internal_only'])) {
692             // must be internal and not current user (need for distribution list)
693             $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
694             
695             //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
696             //    ".id  != ".$au->id);
697             $this->whereAdd("Person.id != {$au->id}");
698         } 
699         
700         if (!empty($q['query']['comptype_or_company_id'])) {
701            // DB_DataObject::debugLevel(1);
702             $bits = explode(',', $q['query']['comptype_or_company_id']);
703             $id = (int) array_pop($bits);
704             $ct = $this->escape($bits[0]);
705             
706             $this->whereAdd(" join_company_id_id.comptype = '$ct' OR Person.company_id = $id");
707             
708         }
709         
710         
711         // staff list..
712         if (!empty($q['query']['person_inactive'])) {
713            // DB_Dataobject::debugLevel(1);
714             $this->active = 1;
715         }
716         $tn_p = $this->tableName();
717         $tn_gm = DB_DataObject::Factory('group_members')->tableName();
718         $tn_g = DB_DataObject::Factory('Groups')->tableName();
719
720         ///---------------- Group views --------
721         if (!empty($q['query']['in_group'])) {
722             // DB_DataObject::debugLevel(1);
723             $ing = (int) $q['query']['in_group'];
724             if ($q['query']['in_group'] == -1) {
725              
726                 // list all staff who are not in a group.
727                 $this->whereAdd("Person.id NOT IN (
728                     SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
729                         $tn_g ON $tn_g.id = $tn_gm.group_id
730                         WHERE $tn_g.type = ".$q['query']['type']."
731                     )");
732                 
733                 
734             } else {
735                 
736                 $this->whereAdd("$tn_p.id IN (
737                     SELECT distinct(user_id) FROM $tn_gm
738                         WHERE group_id = $ing
739                     )");
740                }
741             
742         }
743         
744         // #2307 Search Country!!
745         if (!empty($q['query']['in_country'])) {
746             // DB_DataObject::debugLevel(1);
747             $inc = $q['query']['in_country'];
748             $this->whereAdd("$tn_p.countries LIKE '%{$inc}%'");
749         }
750         
751         if (!empty($q['query']['not_in_directory'])) { 
752             // it's a Person list..
753             // DB_DATaobjecT::debugLevel(1);
754             
755             // specific to project directory which is single comp. login
756             //
757             $owncomp = DB_DataObject::Factory('Companies');
758             $owncomp->get('comptype', 'OWNER');
759             if ($q['company_id'] == $owncomp->id) {
760                 $this->active =1;
761             }
762             
763             
764
765             if ( $q['query']['not_in_directory'] > -1) {
766                 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
767                 // can list current - so that it does not break!!!
768                 $this->whereAdd("$tn_p.id NOT IN 
769                     ( SELECT distinct person_id FROM $tn_pd WHERE
770                         project_id = " . $q['query']['not_in_directory'] . " AND 
771                         company_id = " . $this->company_id . ')');
772             }
773         }
774            
775         if (!empty($q['query']['role'])) { 
776             // it's a Person list..
777             // DB_DATaobjecT::debugLevel(1);
778             
779             // specific to project directory which is single comp. login
780             //
781             $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
782                 // can list current - so that it does not break!!!
783             $this->whereAdd("$tn_p.id IN 
784                     ( SELECT distinct person_id FROM $tn_pd WHERE
785                         role = '". $this->escape($q['query']['role']) ."'
786             )");
787         
788         }
789         
790         
791         if (!empty($q['query']['project_member_of'])) {
792                // this is also a flag to return if they are a member..
793             //DB_DataObject::debugLevel(1);
794             $do = DB_DataObject::factory('ProjectDirectory');
795             $do->project_id = $q['query']['project_member_of'];
796             $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
797             $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
798             $this->selectAdd("IF($tn_pd.id IS NULL, 0,  $tn_pd.id )  as is_member");
799                 
800                 
801             if (!empty($q['query']['project_member_filter'])) {
802                 $this->having('is_member !=0');
803             
804             }
805             
806         }
807         
808         if(!empty($q['query']['name'])){
809             $this->whereAdd("
810                 Person.name LIKE '%{$this->escape($q['query']['name'])}%'
811             ");
812         }
813         
814         if (!empty($q['query']['search'])) {
815             
816             // use our magic search builder...
817             
818              require_once 'Text/SearchParser.php';
819             $x = new Text_SearchParser($q['query']['search']);
820             
821             $props = array(
822                     "$tn_p.name",
823                     "$tn_p.email",
824                     "$tn_p.role",
825                     "$tn_p.phone",
826                     "$tn_p.remarks",
827                     "join_company_id_id.name"
828             );
829             
830             $str =  $x->toSQL(array(
831                 'default' => $props,
832                 'map' => array(
833                     'company' => 'join_company_id_id.name',
834                     //'country' => 'Clipping.country',
835                     //  'media' => 'Clipping.media_name',
836                 ),
837                 'escape' => array($this->getDatabaseConnection(), 'escapeSimple'), /// pear db or mdb object..
838
839             ));
840             
841             
842             $this->whereAdd($str); /*
843                         $tn_p.name LIKE '%$s%'  OR
844                         $tn_p.email LIKE '%$s%'  OR
845                         $tn_p.role LIKE '%$s%'  OR
846                         $tn_p.phone LIKE '%$s%' OR
847                         $tn_p.remarks LIKE '%$s%' 
848                         
849                     ");*/
850         }
851         
852     }
853     function setFromRoo($ar, $roo)
854     {
855         $this->setFrom($ar);
856         if (!empty($ar['passwd1'])) {
857             $this->setPassword($ar['passwd1']);
858         }
859         
860         
861         if (    $this->id &&
862                 ($this->email == $roo->old->email)&&
863                 ($this->company_id == $roo->old->company_id)
864             ) {
865             return true;
866         }
867         if (empty($this->email)) {
868             return true;
869         }
870         $xx = DB_Dataobject::factory('Person');
871         $xx->setFrom(array(
872             'email' => $this->email,
873            // 'company_id' => $x->company_id
874         ));
875         
876         if ($xx->count()) {
877             return "Duplicate Email found";
878         }
879         return true;
880     }
881     /**
882      *
883      * before Delete - delete significant dependancies..
884      * this is called after checkPerm..
885      */
886     
887     function beforeDelete()
888     {
889         
890         $e = DB_DataObject::Factory('Events');
891         $e->whereAdd('person_id = ' . $this->id);
892         $e->delete(true);
893         
894         // anything else?  
895         
896     }
897     
898     
899     /***
900      * Check if the a user has access to modify this item.
901      * @param String $lvl Level (eg. Core.Projects)
902      * @param Pman_Core_DataObjects_Person $au The authenticated user.
903      * @param boolean $changes alllow changes???
904      *
905      * @return false if no access..
906      */
907     function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
908     {
909          
910        // do we have an empty system..
911         if ($au && $au->id == -1) {
912             return true;
913         }
914         
915         // determine if it's staff!!!
916          
917         if ($au->company()->comptype != 'OWNER') {
918             
919             // - can not change company!!!
920             if ($changes && 
921                 isset($changes['company_id']) && 
922                 $changes['company_id'] != $au->company_id) {
923                 return false;
924             }
925             // can only set new emails..
926             if ($changes && 
927                     !empty($this->email) && 
928                     isset($changes['email']) && 
929                     $changes['email'] != $this->email) {
930                 return false;
931             }
932             
933             // edit self... - what about other staff members...
934             
935             return $this->company_id == $au->company_id;
936         }
937          
938          
939         // yes, only owner company can mess with this...
940         $owncomp = DB_DataObject::Factory('Companies');
941         $owncomp->get('comptype', 'OWNER');
942         
943         $isStaff = ($this->company_id ==  $owncomp->id);
944         
945     
946         switch ($lvl) {
947             // extra case change passwod?
948             case 'P': //??? password
949                 // standard perms -- for editing + if the user is dowing them selves..
950                 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
951                 return $ret || $au->id == $this->id;
952             
953             default:                
954                 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
955         
956         }
957         return false;
958     }
959     
960     function onInsert($req, $roo)
961     {
962          
963         $p = DB_DataObject::factory('person');
964         if ($roo->authUser->id < 0 && $p->count() == 1) {
965             // this seems a bit risky...
966             
967             $g = DB_DataObject::factory('Groups');
968             $g->initGroups();
969             
970             $g->type = 0;
971             $g->get('name', 'Administrators');
972             
973             $p = DB_DataObject::factory('group_members');
974             $p->group_id = $g->id;
975             $p->user_id = $this->id;     
976             if (!$p->count()) {
977                 $p->insert();
978                 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
979             }
980             $this->login();
981         }
982         if (!empty($req['project_id_addto'])) {
983             $pd = DB_DataObject::factory('ProjectDirectory');
984             $pd->project_id = $req['project_id_addto'];
985             $pd->person_id = $this->id; 
986             $pd->ispm =0;
987             $pd->office_id = $this->office_id;
988             $pd->company_id = $this->company_id;
989             $pd->insert();
990         }
991         
992     }
993     
994     function importFromArray($roo, $persons, $opts)
995     {
996         if (empty($opts['prefix'])) {
997             $roo->jerr("opts[prefix] is empty - you can not just create passwords based on the user names");
998         }
999         
1000         if (!is_array($persons) || empty($persons)) {
1001             $roo->jerr("error in the person data. - empty on not valid");
1002         }
1003         DB_DataObject::factory('groups')->initGroups();
1004         
1005         foreach($persons as $person){
1006             $p = DB_DataObject::factory('person');
1007             if($p->get('name', $person['name'])){
1008                 continue;
1009             }
1010             $p->setFrom($person);
1011             
1012             $companies = DB_DataObject::factory('companies');
1013             if(!$companies->get('comptype', 'OWNER')){
1014                 $roo->jerr("Missing OWNER companies!");
1015             }
1016             $p->company_id = $companies->pid();
1017             // strip the 'spaces etc.. make lowercase..
1018             $name = strtolower(str_replace(' ', '', $person['name']));
1019             $p->setPassword("{$opts['prefix']}{$name}");
1020             $p->insert();
1021             // set up groups
1022             // if $person->groups is set.. then
1023             // add this person to that group eg. groups : [ 'Administrator' ] 
1024             if(!empty($person['groups'])){
1025                 $groups = DB_DataObject::factory('groups');
1026                 if(!$groups->get('name', $person['groups'])){
1027                     $roo->jerr("Missing groups : {$person['groups']}");
1028                 }
1029                 $gm = DB_DataObject::factory('group_members');
1030                 $gm->change($p, $groups, true);
1031             }
1032             
1033             $p->onInsert(array(), $roo);
1034         }
1035     }
1036     
1037     function getEmailName()
1038     {
1039         $name = array();
1040         
1041         if(!empty($this->honor)){
1042             array_push($name, $this->honor);
1043         }
1044         
1045         if(!empty($this->name)){
1046             array_push($name, $this->name);
1047             
1048             return implode(' ', $name);
1049         }
1050         
1051         if(!empty($this->firstname) || !empty($this->lastname)){
1052             array_push($name, $this->firstname);
1053             array_push($name, $this->lastname);
1054             
1055             $name = array_filter($name);
1056             
1057             return $name;
1058         }
1059         
1060         return $this->email;
1061     }
1062  }