3 * Table Definition for Person
5 require_once 'DB/DataObject.php';
7 class Pman_Core_DataObjects_Person extends DB_DataObject
10 /* the code below is auto generated do not remove the above tag */
12 public $__table = 'Person'; // table name
13 public $id; // int(11) not_null primary_key auto_increment
14 public $email; // string(128) not_null
16 public $company_id; // int(11)
17 public $office_id; // int(11)
19 public $name; // string(128) not_null
20 public $firstname; // string(128) not_null
21 public $lastname; // string(128) not_null
22 public $phone; // string(32) not_null
23 public $fax; // string(32) not_null
25 public $role; // string(32) not_null
26 public $remarks; // blob(65535) not_null blob
27 public $passwd; // string(64) not_null
28 public $owner_id; // int(11) not_null
29 public $lang; // string(8)
30 public $no_reset_sent; // int(11)
31 public $action_type; // string(32)
32 public $project_id; // int(11)
35 public $active; // int(11) not_null
36 public $deleted_by; // int(11) not_null
37 public $deleted_dt; // datetime(19) binary
40 /* the code above is auto generated do not remove the tag below */
47 * FIXME !!!! -- USE Pman_Core_Mailer !!!!!
53 function buildMail($templateFile, $args)
56 $args = (array) $args;
57 $content = clone($this);
59 foreach((array)$args as $k=>$v) {
63 $ff = HTML_FlexyFramework::get();
66 //?? is this really the place for this???
69 empty($args['no_auth']) &&
70 !in_array($templateFile, array(
71 // templates that can be sent without authentication.
77 $content->authUser = $this->getAuthUser();
78 if (!$content->authUser) {
79 return PEAR::raiseError("Not authenticated");
83 // should handle x-forwarded...
85 $content->HTTP_HOST = isset($_SERVER["HTTP_HOST"]) ?
86 $_SERVER["HTTP_HOST"] :
87 (isset($ff->HTTP_HOST) ? $ff->HTTP_HOST : 'localhost');
89 /* use the regex compiler, as it doesnt parse <tags */
92 'compiler' => 'Flexy',
94 'filters' => array('SimpleTags','Mail'),
100 if (!empty($args['templateDir'])) {
101 $tops['templateDir'] = $args['templateDir'];
106 require_once 'HTML/Template/Flexy.php';
107 $template = new HTML_Template_Flexy( $tops );
108 $template->compile("mail/$templateFile.txt");
110 /* use variables from this object to ouput data. */
111 $mailtext = $template->bufferedOutputObject($content);
114 // if a html file with the same name exists, use that as the body
115 // I've no idea where this code went, it was here before..
116 if (false !== $template->resolvePath ( "mail/$templateFile.html" )) {
117 $tops['nonHTML'] = false;
118 $template = new HTML_Template_Flexy( $tops );
119 $template->compile("mail/$templateFile.html");
120 $htmlbody = $template->bufferedOutputObject($content);
126 //echo "<PRE>";print_R($mailtext);
127 //print_R($mailtext);exit;
128 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
129 require_once 'Mail/mimeDecode.php';
130 require_once 'Mail.php';
132 $decoder = new Mail_mimeDecode($mailtext);
133 $parts = $decoder->getSendArray();
135 if (PEAR::isError($parts)) {
137 //echo "PROBLEM: {$parts->message}";
140 list($recipents,$headers,$body) = $parts;
141 $recipents = array($this->email);
142 if (!empty($content->bcc) && is_array($content->bcc)) {
143 $recipents =array_merge($recipents, $content->bcc);
145 $headers['Date'] = date('r');
147 if ($htmlbody !== false) {
148 require_once 'Mail/mime.php';
149 $mime = new Mail_mime(array('eol' => "\n"));
150 $mime->setTXTBody($body);
151 $mime->setHTMLBody($htmlbody);
152 // I think there might be code in mediaoutreach toEmail somewhere
153 // h embeds images here..
154 $body = $mime->get();
155 $headers = $mime->headers($headers);
162 'recipients' => $recipents,
163 'headers' => $headers,
173 * - user must be authenticate or args[no_auth] = true
174 * or template = password_[reset|welcome]
177 function sendTemplate($templateFile, $args)
180 $ar = $this->buildMail($templateFile, $args);
183 //print_r($recipents);exit;
184 $mailOptions = PEAR::getStaticProperty('Mail','options');
185 $mail = Mail::factory("SMTP",$mailOptions);
187 if (PEAR::isError($mail)) {
190 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
191 $ret = $mail->send($ar['recipients'],$ar['headers'],$ar['body']);
192 error_reporting($oe);
201 function getEmailFrom()
203 return '"' . addslashes($this->name) . '" <' . $this->email . '>';
205 function toEventString()
207 return empty($this->name) ? $this->email : $this->name;
209 function verifyAuth()
211 $ff= HTML_FlexyFramework::get();
212 if (!empty($ff->Pman['auth_comptype']) && $ff->Pman['auth_comptype'] != $this->company()->comptype) {
213 $ff->page->jerr("Login not permited to outside companies");
220 // ---------------- authentication / passwords and keys stuff ----------------
223 $db = $this->getDatabaseConnection();
224 // we combine db + project names,
225 // otherwise if projects use different 'auth' objects
226 // then we get unserialize issues.
227 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
231 if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
233 $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
235 $u = DB_DataObject::factory('Person');
236 if ($u->get($a->id)) { //&& strlen($u->passwd)) {
242 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = '';
246 $u = DB_DataObject::factory('Person');
247 $ff = HTML_FlexyFramework::get();
248 if (!empty($ff->Pman['local_autoauth']) &&
249 (!empty($_SERVER['SERVER_ADDR'])) &&
250 ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
251 ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') &&
252 $u->get('email', $ff->Pman['local_autoauth'])
254 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($u);
259 $u = DB_DataObject::factory('Person');
261 if (!empty($_SERVER['PHP_AUTH_USER'])
263 !empty($_SERVER['PHP_AUTH_PW'])
265 $u->get('email', $_SERVER['PHP_AUTH_USER'])
267 $u->checkPassword($_SERVER['PHP_AUTH_PW'])
269 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($u);
276 // not in session or not matched...
277 $u = DB_DataObject::factory('Person');
278 $u->whereAdd(' LENGTH(passwd) > 0');
280 $error = PEAR::getStaticProperty('DB_DataObject','lastError');
282 die($error->toString()); // not really a good thing to do...
284 if (!$n){ // authenticated as there are no users in the system...
291 function getAuthUser()
293 if (!$this->isAuth()) {
296 $db = $this->getDatabaseConnection();
297 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
299 if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
300 $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
302 $u = DB_DataObject::factory('Person');
303 if ($u->get($a->id)) { /// && strlen($u->passwd)) {
311 $u = DB_DataObject::factory('Person');
312 $u->whereAdd(' LENGTH(passwd) > 0');
315 // fake person - open system..
316 //$ce = DB_DataObject::factory('core_enum');
320 $u = DB_DataObject::factory('Person');
329 $this->isAuth(); // force session start..
331 $db = $this->getDatabaseConnection();
332 // refresh admin group if we are logged in as one..
333 //DB_DataObject::debugLevel(1);
334 $g = DB_DataObject::factory('Groups');
336 $g->get('name', 'Administrators');
337 $gm = DB_DataObject::Factory('group_members');
338 if (in_array($g->id,$gm->listGroupMembership($this))) {
339 // refresh admin groups.
340 $gr = DB_DataObject::Factory('group_rights');
341 $gr->applyDefs($g, 0);
344 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
345 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($this);
350 $this->isAuth(); // force session start..
351 $db = $this->getDatabaseConnection();
352 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
353 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
356 function genPassKey ($t)
358 return md5($this->email . $t. $this->passwd);
360 function simpleAuthKey($m = 0)
362 $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
364 return md5(implode(',' , array($month, $this->email , $this->passwd, $this->id)));
366 function checkPassword($val)
369 if (substr($this->passwd,0,1) == '$') {
370 return crypt($val,$this->passwd) == $this->passwd ;
372 // old style md5 passwords...- cant be used with courier....
373 return md5($val) == $this->passwd;
375 function setPassword($value)
378 while(strlen($salt)<9) {
379 $salt.=chr(rand(64,126));
380 //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
382 $this->passwd = crypt($value, '$1$'. $salt. '$');
387 function generatePassword() // genearte a password (add set 'rawPasswd' to it's value)
389 require_once 'Text/Password.php';
390 $this->rawPasswd = strtr(ucfirst(Text_Password::create(5)).ucfirst(Text_Password::create(5)), array(
391 "a"=>"4", "e"=>"3", "i"=>"1", "o"=>"0", "s"=>"5", "t"=>"7"));
392 $this->setPassword($this->rawPasswd);
393 return $this->rawPasswd;
398 $x = DB_DataObject::factory('Companies');
399 $x->get($this->company_id);
402 function loadCompany()
404 $this->company = $this->company();
409 return $this->active;
411 function authUserName($n) // set username prior to acheck user exists query.
414 $this->whereAdd('LENGTH(passwd) > 1');
419 if ($val == $this->lang) {
429 function authUserArray()
432 $aur = $this->toArray();
439 //DB_DataObject::debugLevel(1);
440 $c = DB_Dataobject::factory('Companies');
441 $im = DB_Dataobject::factory('Images');
442 $c->joinAdd($im, 'LEFT');
444 $c->selectAs($c, 'company_id_%s');
445 $c->selectAs($im, 'company_id_logo_id_%s');
446 $c->id = $this->company_id;
450 $aur = array_merge( $c->toArray(),$aur);
452 if (empty($c->company_id_logo_id_id)) {
454 $im = DB_Dataobject::factory('Images');
455 $im->ontable = 'Companies';
457 $im->imgtype = 'LOGO';
460 $im->selectAs($im, 'company_id_logo_id_%s');
461 if ($im->find(true)) {
463 foreach($im->toArray() as $k=>$v) {
470 $aur['perms'] = $this->getPerms();
471 $g = DB_DataObject::Factory('group_members');
472 $aur['groups'] = $g->listGroupMembership($this, 'name');
475 $aur['dailykey'] = '';
482 // ----------PERMS------ ----------------
485 //DB_DataObject::debugLevel(1);
486 // find out all the groups they are a member of.. + Default..
488 // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
490 $g = DB_DataObject::Factory('group_rights');
496 return $g->adminRights(); // system is not set up - so they get full rights.
498 //DB_DataObject::debugLevel(1);
499 $g = DB_DataObject::Factory('group_members');
500 $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
502 // add the current user to the admin group..
503 $g = DB_DataObject::Factory('Groups');
504 if ($g->get('name', 'Administrators')) {
505 $gm = DB_DataObject::Factory('group_members');
506 $gm->group_id = $g->id;
507 $gm->user_id = $this->id;
513 // ------ STANDARD PERMISSION HANDLING.
514 $isOwner = $this->company()->comptype == 'OWNER';
515 $g = DB_DataObject::Factory('group_members');
516 $grps = $g->listGroupMembership($this);
518 $isAdmin = $g->inAdmin;
519 //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
520 // the load all the perms for those groups, and add them all together..
521 // then load all those
522 $g = DB_DataObject::Factory('group_rights');
523 $ret = $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
524 //echo '<PRE>';print_r($ret);
530 *Basic group fetching - probably needs to filter by type eventually.
532 *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
535 function groups($what=false)
537 $g = DB_DataObject::Factory('group_members');
538 $grps = $g->listGroupMembership($this);
539 $g = DB_DataObject::Factory('Groups');
540 $g->whereAddIn('id', $grps, 'int');
541 return $g->fetchAll($what);
547 function hasPerm($name, $lvl)
549 static $pcache = array();
551 if (!isset($pcache[$this->id])) {
552 $pcache[$this->id] = $this->getPerms();
554 // echo "<PRE>";print_r($pcache[$au->id]);
555 // var_dump($pcache[$au->id]);
556 if (empty($pcache[$this->id][$name])) {
560 return strpos($pcache[$this->id][$name], $lvl) > -1;
564 // ------------ROO HOOKS------------------------------------
565 function applyFilters($q, $au, $roo)
567 //DB_DataObject::DebugLevel(1);
568 if (!empty($q['query']['person_not_internal'])) {
569 $this->whereAdd(" join_company_id_id.isOwner = 0 ");
573 if (!empty($q['query']['person_internal_only_all'])) {
576 // must be internal and not current user (need for distribution list)
577 // user has a projectdirectory entry and role is not blank.
578 //DB_DataObject::DebugLevel(1);
579 $pd = DB_DataObject::factory('ProjectDirectory');
580 $pd->whereAdd("role != ''");
582 $pd->selectAdd('distinct(person_id) as person_id');
583 $roled = $pd->fetchAll('person_id');
585 {$this->tableName()}.id IN (".implode(',', $roled) . ")
587 $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
590 // -- for distribution
591 if (!empty($q['query']['person_internal_only'])) {
592 // must be internal and not current user (need for distribution list)
593 $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
595 //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
596 // ".id != ".$au->id);
597 $this->whereAdd("Person.id != {$au->id}");
600 if (!empty($q['query']['comptype_or_company_id'])) {
601 // DB_DataObject::debugLevel(1);
602 $bits = explode(',', $q['query']['comptype_or_company_id']);
603 $id = (int) array_pop($bits);
604 $ct = $this->escape($bits[0]);
606 $this->whereAdd(" join_company_id_id.comptype = '$ct' OR Person.company_id = $id");
612 if (!empty($q['query']['person_inactive'])) {
613 // DB_Dataobject::debugLevel(1);
616 $tn_p = $this->tableName();
617 $tn_gm = DB_DataObject::Factory('group_members')->tableName();
618 $tn_g = DB_DataObject::Factory('Groups')->tableName();
620 ///---------------- Group views --------
621 if (!empty($q['query']['in_group'])) {
622 // DB_DataObject::debugLevel(1);
623 $ing = (int) $q['query']['in_group'];
624 if ($q['query']['in_group'] == -1) {
626 // list all staff who are not in a group.
627 $this->whereAdd("Person.id NOT IN (
628 SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
629 $tn_g ON $tn_g.id = $tn_gm.group_id
630 WHERE $tn_g.type = ".$q['query']['type']."
636 $this->whereAdd("$tn_p.id IN (
637 SELECT distinct(user_id) FROM $tn_gm
638 WHERE group_id = $ing
644 if (!empty($q['query']['not_in_directory'])) {
645 // it's a Person list..
646 // DB_DATaobjecT::debugLevel(1);
648 // specific to project directory which is single comp. login
650 $owncomp = DB_DataObject::Factory('Companies');
651 $owncomp->get('comptype', 'OWNER');
652 if ($q['company_id'] == $owncomp->id) {
658 if ( $q['query']['not_in_directory'] > -1) {
659 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
660 // can list current - so that it does not break!!!
661 $this->whereAdd("$tn_p.id NOT IN
662 ( SELECT distinct person_id FROM $tn_pd WHERE
663 project_id = " . $q['query']['not_in_directory'] . " AND
664 company_id = " . $this->company_id . ')');
668 if (!empty($q['query']['role'])) {
669 // it's a Person list..
670 // DB_DATaobjecT::debugLevel(1);
672 // specific to project directory which is single comp. login
674 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
675 // can list current - so that it does not break!!!
676 $this->whereAdd("$tn_p.id IN
677 ( SELECT distinct person_id FROM $tn_pd WHERE
678 role = '". $this->escape($q['query']['role']) ."'
684 if (!empty($q['query']['project_member_of'])) {
685 // this is also a flag to return if they are a member..
686 //DB_DataObject::debugLevel(1);
687 $do = DB_DataObject::factory('ProjectDirectory');
688 $do->project_id = $q['query']['project_member_of'];
689 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
690 $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
691 $this->selectAdd("IF($tn_pd.id IS NULL, 0, $tn_pd.id ) as is_member");
694 if (!empty($q['query']['project_member_filter'])) {
695 $this->having('is_member !=0');
701 if (!empty($q['query']['search'])) {
702 $s = $this->escape($q['query']['search']);
704 $tn_p.name LIKE '%$s%' OR
705 $tn_p.email LIKE '%$s%' OR
706 $tn_p.role LIKE '%$s%' OR
707 $tn_p.phone LIKE '%$s%' OR
708 $tn_p.remarks LIKE '%$s%'
715 function setFromRoo($ar, $roo)
718 if (!empty($ar['passwd1'])) {
719 $this->setPassword($ar['passwd1']);
724 ($this->email == $roo->old->email)&&
725 ($this->company_id == $roo->old->company_id)
729 if (empty($this->email)) {
732 $xx = DB_Dataobject::factory('Person');
734 'email' => $this->email,
735 // 'company_id' => $x->company_id
739 return "Duplicate Email found";
745 * before Delete - delete significant dependancies..
746 * this is called after checkPerm..
749 function beforeDelete()
752 $e = DB_DataObject::Factory('Events');
753 $e->whereAdd('person_id = ' . $this->id);
762 * Check if the a user has access to modify this item.
763 * @param String $lvl Level (eg. Core.Projects)
764 * @param Pman_Core_DataObjects_Person $au The authenticated user.
765 * @param boolean $changes alllow changes???
767 * @return false if no access..
769 function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
772 // do we have an empty system..
773 if ($au && $au->id == -1) {
777 // determine if it's staff!!!
779 if ($au->company()->comptype != 'OWNER') {
781 // - can not change company!!!
783 isset($changes['company_id']) &&
784 $changes['company_id'] != $au->company_id) {
787 // can only set new emails..
789 !empty($this->email) &&
790 isset($changes['email']) &&
791 $changes['email'] != $this->email) {
795 // edit self... - what about other staff members...
797 return $this->company_id == $au->company_id;
801 // yes, only owner company can mess with this...
802 $owncomp = DB_DataObject::Factory('Companies');
803 $owncomp->get('comptype', 'OWNER');
805 $isStaff = ($this->company_id == $owncomp->id);
809 // extra case change passwod?
810 case 'P': //??? password
811 // standard perms -- for editing + if the user is dowing them selves..
812 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
813 return $ret || $au->id == $this->id;
816 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
821 function onInsert($req, $roo)
824 $p = DB_DataObject::factory('person');
825 if ($roo->authUser->id < 0 && $p->count() == 1) {
826 // this seems a bit risky...
828 $g = DB_DataObject::factory('Groups');
832 $g->get('name', 'Administrators');
834 $p = DB_DataObject::factory('group_members');
835 $p->group_id = $g->id;
836 $p->user_id = $this->id;
839 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
843 if (!empty($req['project_id_addto'])) {
844 $pd = DB_DataObject::factory('ProjectDirectory');
845 $pd->project_id = $req['project_id_addto'];
846 $pd->person_id = $this->id;
848 $pd->office_id = $this->office_id;
849 $pd->company_id = $this->company_id;