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