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