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)
18 public $name; // string(128) not_null
19 public $firstname; // string(128) not_null
20 public $lastname; // string(128) not_null
21 public $phone; // string(32) not_null
22 public $fax; // string(32) not_null
24 public $role; // string(32) not_null
25 public $remarks; // blob(65535) not_null blob
26 public $passwd; // string(64) not_null
27 public $owner_id; // int(11) not_null
28 public $lang; // string(8)
29 public $no_reset_sent; // int(11)
30 public $action_type; // string(32)
31 public $project_id; // int(11)
34 public $active; // int(11) not_null
35 public $deleted_by; // int(11) not_null
36 public $deleted_dt; // datetime(19) binary
39 public $name_facebook; // VARCHAR(128) NULL;
40 public $url_blog; // VARCHAR(256) NULL ;
41 public $url_twitter; // VARCHAR(256) NULL ;
42 public $url_linkedin; // VARCHAR(256) NULL ;
44 public $phone_mobile; // varchar(32) NOT NULL DEFAULT '';
45 public $phone_direct; // varchar(32) NOT NULL DEFAULT '';
47 /* the code above is auto generated do not remove the tag below */
52 $p = DB_DataObject::Factory('Person');
53 $p->get($this->owner_id);
62 * FIXME !!!! -- USE Pman_Core_Mailer !!!!!
68 function buildMail($templateFile, $args)
71 $args = (array) $args;
72 $content = clone($this);
74 foreach((array)$args as $k=>$v) {
78 $ff = HTML_FlexyFramework::get();
81 //?? is this really the place for this???
84 empty($args['no_auth']) &&
85 !in_array($templateFile, array(
86 // templates that can be sent without authentication.
92 $content->authUser = $this->getAuthUser();
93 if (!$content->authUser) {
94 return PEAR::raiseError("Not authenticated");
98 // should handle x-forwarded...
100 $content->HTTP_HOST = isset($_SERVER["HTTP_HOST"]) ?
101 $_SERVER["HTTP_HOST"] :
102 (isset($ff->HTTP_HOST) ? $ff->HTTP_HOST : 'localhost');
104 /* use the regex compiler, as it doesnt parse <tags */
107 'compiler' => 'Flexy',
109 'filters' => array('SimpleTags','Mail'),
115 if (!empty($args['templateDir'])) {
116 $tops['templateDir'] = $args['templateDir'];
121 require_once 'HTML/Template/Flexy.php';
122 $template = new HTML_Template_Flexy( $tops );
123 $template->compile("mail/$templateFile.txt");
125 /* use variables from this object to ouput data. */
126 $mailtext = $template->bufferedOutputObject($content);
129 // if a html file with the same name exists, use that as the body
130 // I've no idea where this code went, it was here before..
131 if (false !== $template->resolvePath ( "mail/$templateFile.html" )) {
132 $tops['nonHTML'] = false;
133 $template = new HTML_Template_Flexy( $tops );
134 $template->compile("mail/$templateFile.html");
135 $htmlbody = $template->bufferedOutputObject($content);
141 //echo "<PRE>";print_R($mailtext);
142 //print_R($mailtext);exit;
143 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
144 require_once 'Mail/mimeDecode.php';
145 require_once 'Mail.php';
147 $decoder = new Mail_mimeDecode($mailtext);
148 $parts = $decoder->getSendArray();
150 if (PEAR::isError($parts)) {
152 //echo "PROBLEM: {$parts->message}";
155 list($recipents,$headers,$body) = $parts;
156 $recipents = array($this->email);
157 if (!empty($content->bcc) && is_array($content->bcc)) {
158 $recipents =array_merge($recipents, $content->bcc);
160 $headers['Date'] = date('r');
162 if ($htmlbody !== false) {
163 require_once 'Mail/mime.php';
164 $mime = new Mail_mime(array('eol' => "\n"));
165 $mime->setTXTBody($body);
166 $mime->setHTMLBody($htmlbody);
167 // I think there might be code in mediaoutreach toEmail somewhere
168 // h embeds images here..
169 $body = $mime->get();
170 $headers = $mime->headers($headers);
177 'recipients' => $recipents,
178 'headers' => $headers,
188 * - user must be authenticate or args[no_auth] = true
189 * or template = password_[reset|welcome]
192 function sendTemplate($templateFile, $args)
195 $ar = $this->buildMail($templateFile, $args);
198 //print_r($recipents);exit;
199 $mailOptions = PEAR::getStaticProperty('Mail','options');
200 $mail = Mail::factory("SMTP",$mailOptions);
202 if (PEAR::isError($mail)) {
205 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
206 $ret = $mail->send($ar['recipients'],$ar['headers'],$ar['body']);
207 error_reporting($oe);
216 function getEmailFrom()
218 return '"' . addslashes($this->name) . '" <' . $this->email . '>';
220 function toEventString()
222 return empty($this->name) ? $this->email : $this->name;
224 function verifyAuth()
226 $ff= HTML_FlexyFramework::get();
227 if (!empty($ff->Pman['auth_comptype']) && $ff->Pman['auth_comptype'] != $this->company()->comptype) {
228 $ff->page->jerr("Login not permited to outside companies");
235 // ---------------- authentication / passwords and keys stuff ----------------
238 $db = $this->getDatabaseConnection();
239 // we combine db + project names,
240 // otherwise if projects use different 'auth' objects
241 // then we get unserialize issues.
242 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
247 if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
249 $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
251 $u = DB_DataObject::factory('Person');
252 if ($u->get($a->id)) { //&& strlen($u->passwd)) {
258 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = '';
262 $u = DB_DataObject::factory('Person');
263 $ff = HTML_FlexyFramework::get();
264 if (!empty($ff->Pman['local_autoauth']) &&
265 (!empty($_SERVER['SERVER_ADDR'])) &&
266 ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
267 ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') &&
268 $u->get('email', $ff->Pman['local_autoauth'])
270 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($u);
275 $u = DB_DataObject::factory('Person');
277 if (!empty($_SERVER['PHP_AUTH_USER'])
279 !empty($_SERVER['PHP_AUTH_PW'])
281 $u->get('email', $_SERVER['PHP_AUTH_USER'])
283 $u->checkPassword($_SERVER['PHP_AUTH_PW'])
285 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($u);
289 if (!empty( $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
293 // not in session or not matched...
294 $u = DB_DataObject::factory('Person');
295 $u->whereAdd(' LENGTH(passwd) > 0');
297 $_SESSION[__CLASS__][$sesPrefix .'-empty'] = $n;
298 $error = PEAR::getStaticProperty('DB_DataObject','lastError');
300 die($error->toString()); // not really a good thing to do...
302 if (!$n){ // authenticated as there are no users in the system...
309 function getAuthUser()
311 if (!$this->isAuth()) {
314 $db = $this->getDatabaseConnection();
315 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
319 if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
320 $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
322 $u = DB_DataObject::factory('Person');
323 if ($u->get($a->id)) { /// && strlen($u->passwd)) {
329 if (empty( $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
330 $u = DB_DataObject::factory('Person');
331 $u->whereAdd(' LENGTH(passwd) > 0');
332 $_SESSION[__CLASS__][$sesPrefix .'-empty'] = $u->count();
336 if (empty( $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
338 // fake person - open system..
339 //$ce = DB_DataObject::factory('core_enum');
343 $u = DB_DataObject::factory('Person');
352 $this->isAuth(); // force session start..
354 $db = $this->getDatabaseConnection();
357 // open up iptables at login..
358 $dbname = $this->database();
359 touch( '/tmp/run_pman_admin_iptables-'.$dbname);
361 // refresh admin group if we are logged in as one..
362 //DB_DataObject::debugLevel(1);
363 $g = DB_DataObject::factory('Groups');
365 $g->get('name', 'Administrators');
366 $gm = DB_DataObject::Factory('group_members');
367 if (in_array($g->id,$gm->listGroupMembership($this))) {
368 // refresh admin groups.
369 $gr = DB_DataObject::Factory('group_rights');
370 $gr->applyDefs($g, 0);
373 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
374 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($this);
379 $this->isAuth(); // force session start..
380 $db = $this->getDatabaseConnection();
381 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
382 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
385 function genPassKey ($t)
387 return md5($this->email . $t. $this->passwd);
389 function simpleAuthKey($m = 0)
391 $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
393 return md5(implode(',' , array($month, $this->email , $this->passwd, $this->id)));
395 function checkPassword($val)
398 if (substr($this->passwd,0,1) == '$') {
399 return crypt($val,$this->passwd) == $this->passwd ;
401 // old style md5 passwords...- cant be used with courier....
402 return md5($val) == $this->passwd;
404 function setPassword($value)
407 while(strlen($salt)<9) {
408 $salt.=chr(rand(64,126));
409 //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
411 $this->passwd = crypt($value, '$1$'. $salt. '$');
416 function generatePassword() // genearte a password (add set 'rawPasswd' to it's value)
418 require_once 'Text/Password.php';
419 $this->rawPasswd = strtr(ucfirst(Text_Password::create(5)).ucfirst(Text_Password::create(5)), array(
420 "a"=>"4", "e"=>"3", "i"=>"1", "o"=>"0", "s"=>"5", "t"=>"7"));
421 $this->setPassword($this->rawPasswd);
422 return $this->rawPasswd;
427 $x = DB_DataObject::factory('Companies');
429 $x->get($this->company_id);
432 function loadCompany()
434 $this->company = $this->company();
439 return $this->active;
441 function authUserName($n) // set username prior to acheck user exists query.
444 $this->whereAdd('LENGTH(passwd) > 1');
449 if ($val == $this->lang) {
459 function authUserArray()
462 $aur = $this->toArray();
469 //DB_DataObject::debugLevel(1);
470 $c = DB_Dataobject::factory('Companies');
471 $im = DB_Dataobject::factory('Images');
472 $c->joinAdd($im, 'LEFT');
474 $c->selectAs($c, 'company_id_%s');
475 $c->selectAs($im, 'company_id_logo_id_%s');
476 $c->id = $this->company_id;
480 $aur = array_merge( $c->toArray(),$aur);
482 if (empty($c->company_id_logo_id_id)) {
484 $im = DB_Dataobject::factory('Images');
485 $im->ontable = 'Companies';
487 $im->imgtype = 'LOGO';
490 $im->selectAs($im, 'company_id_logo_id_%s');
491 if ($im->find(true)) {
493 foreach($im->toArray() as $k=>$v) {
500 $aur['perms'] = $this->getPerms();
501 $g = DB_DataObject::Factory('group_members');
502 $aur['groups'] = $g->listGroupMembership($this, 'name');
505 $aur['dailykey'] = '';
512 // ----------PERMS------ ----------------
515 //DB_DataObject::debugLevel(1);
516 // find out all the groups they are a member of.. + Default..
518 // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
520 $g = DB_DataObject::Factory('group_rights');
526 return $g->adminRights(); // system is not set up - so they get full rights.
528 //DB_DataObject::debugLevel(1);
529 $g = DB_DataObject::Factory('group_members');
530 $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
532 // add the current user to the admin group..
533 $g = DB_DataObject::Factory('Groups');
534 if ($g->get('name', 'Administrators')) {
535 $gm = DB_DataObject::Factory('group_members');
536 $gm->group_id = $g->id;
537 $gm->user_id = $this->id;
543 // ------ STANDARD PERMISSION HANDLING.
544 $isOwner = $this->company()->comptype == 'OWNER';
545 $g = DB_DataObject::Factory('group_members');
546 $grps = $g->listGroupMembership($this);
548 $isAdmin = $g->inAdmin;
549 //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
550 // the load all the perms for those groups, and add them all together..
551 // then load all those
552 $g = DB_DataObject::Factory('group_rights');
553 $ret = $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
554 //echo '<PRE>';print_r($ret);
560 *Basic group fetching - probably needs to filter by type eventually.
562 *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
565 function groups($what=false)
567 $g = DB_DataObject::Factory('group_members');
568 $grps = $g->listGroupMembership($this);
569 $g = DB_DataObject::Factory('Groups');
570 $g->whereAddIn('id', $grps, 'int');
571 return $g->fetchAll($what);
577 function hasPerm($name, $lvl)
579 static $pcache = array();
581 if (!isset($pcache[$this->id])) {
582 $pcache[$this->id] = $this->getPerms();
584 // echo "<PRE>";print_r($pcache[$au->id]);
585 // var_dump($pcache[$au->id]);
586 if (empty($pcache[$this->id][$name])) {
590 return strpos($pcache[$this->id][$name], $lvl) > -1;
594 // ------------ROO HOOKS------------------------------------
595 function applyFilters($q, $au, $roo)
597 //DB_DataObject::DebugLevel(1);
598 if (!empty($q['query']['person_not_internal'])) {
599 $this->whereAdd(" join_company_id_id.isOwner = 0 ");
603 if (!empty($q['query']['person_internal_only_all'])) {
606 // must be internal and not current user (need for distribution list)
607 // user has a projectdirectory entry and role is not blank.
608 //DB_DataObject::DebugLevel(1);
609 $pd = DB_DataObject::factory('ProjectDirectory');
610 $pd->whereAdd("role != ''");
612 $pd->selectAdd('distinct(person_id) as person_id');
613 $roled = $pd->fetchAll('person_id');
615 {$this->tableName()}.id IN (".implode(',', $roled) . ")
617 $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
620 // -- for distribution
621 if (!empty($q['query']['person_internal_only'])) {
622 // must be internal and not current user (need for distribution list)
623 $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
625 //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
626 // ".id != ".$au->id);
627 $this->whereAdd("Person.id != {$au->id}");
630 if (!empty($q['query']['comptype_or_company_id'])) {
631 // DB_DataObject::debugLevel(1);
632 $bits = explode(',', $q['query']['comptype_or_company_id']);
633 $id = (int) array_pop($bits);
634 $ct = $this->escape($bits[0]);
636 $this->whereAdd(" join_company_id_id.comptype = '$ct' OR Person.company_id = $id");
642 if (!empty($q['query']['person_inactive'])) {
643 // DB_Dataobject::debugLevel(1);
646 $tn_p = $this->tableName();
647 $tn_gm = DB_DataObject::Factory('group_members')->tableName();
648 $tn_g = DB_DataObject::Factory('Groups')->tableName();
650 ///---------------- Group views --------
651 if (!empty($q['query']['in_group'])) {
652 // DB_DataObject::debugLevel(1);
653 $ing = (int) $q['query']['in_group'];
654 if ($q['query']['in_group'] == -1) {
656 // list all staff who are not in a group.
657 $this->whereAdd("Person.id NOT IN (
658 SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
659 $tn_g ON $tn_g.id = $tn_gm.group_id
660 WHERE $tn_g.type = ".$q['query']['type']."
666 $this->whereAdd("$tn_p.id IN (
667 SELECT distinct(user_id) FROM $tn_gm
668 WHERE group_id = $ing
674 if (!empty($q['query']['not_in_directory'])) {
675 // it's a Person list..
676 // DB_DATaobjecT::debugLevel(1);
678 // specific to project directory which is single comp. login
680 $owncomp = DB_DataObject::Factory('Companies');
681 $owncomp->get('comptype', 'OWNER');
682 if ($q['company_id'] == $owncomp->id) {
688 if ( $q['query']['not_in_directory'] > -1) {
689 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
690 // can list current - so that it does not break!!!
691 $this->whereAdd("$tn_p.id NOT IN
692 ( SELECT distinct person_id FROM $tn_pd WHERE
693 project_id = " . $q['query']['not_in_directory'] . " AND
694 company_id = " . $this->company_id . ')');
698 if (!empty($q['query']['role'])) {
699 // it's a Person list..
700 // DB_DATaobjecT::debugLevel(1);
702 // specific to project directory which is single comp. login
704 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
705 // can list current - so that it does not break!!!
706 $this->whereAdd("$tn_p.id IN
707 ( SELECT distinct person_id FROM $tn_pd WHERE
708 role = '". $this->escape($q['query']['role']) ."'
714 if (!empty($q['query']['project_member_of'])) {
715 // this is also a flag to return if they are a member..
716 //DB_DataObject::debugLevel(1);
717 $do = DB_DataObject::factory('ProjectDirectory');
718 $do->project_id = $q['query']['project_member_of'];
719 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
720 $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
721 $this->selectAdd("IF($tn_pd.id IS NULL, 0, $tn_pd.id ) as is_member");
724 if (!empty($q['query']['project_member_filter'])) {
725 $this->having('is_member !=0');
731 if (!empty($q['query']['search'])) {
732 $s = $this->escape($q['query']['search']);
734 $tn_p.name LIKE '%$s%' OR
735 $tn_p.email LIKE '%$s%' OR
736 $tn_p.role LIKE '%$s%' OR
737 $tn_p.phone LIKE '%$s%' OR
738 $tn_p.remarks LIKE '%$s%'
745 function setFromRoo($ar, $roo)
748 if (!empty($ar['passwd1'])) {
749 $this->setPassword($ar['passwd1']);
754 ($this->email == $roo->old->email)&&
755 ($this->company_id == $roo->old->company_id)
759 if (empty($this->email)) {
762 $xx = DB_Dataobject::factory('Person');
764 'email' => $this->email,
765 // 'company_id' => $x->company_id
769 return "Duplicate Email found";
775 * before Delete - delete significant dependancies..
776 * this is called after checkPerm..
779 function beforeDelete()
782 $e = DB_DataObject::Factory('Events');
783 $e->whereAdd('person_id = ' . $this->id);
792 * Check if the a user has access to modify this item.
793 * @param String $lvl Level (eg. Core.Projects)
794 * @param Pman_Core_DataObjects_Person $au The authenticated user.
795 * @param boolean $changes alllow changes???
797 * @return false if no access..
799 function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
802 // do we have an empty system..
803 if ($au && $au->id == -1) {
807 // determine if it's staff!!!
809 if ($au->company()->comptype != 'OWNER') {
811 // - can not change company!!!
813 isset($changes['company_id']) &&
814 $changes['company_id'] != $au->company_id) {
817 // can only set new emails..
819 !empty($this->email) &&
820 isset($changes['email']) &&
821 $changes['email'] != $this->email) {
825 // edit self... - what about other staff members...
827 return $this->company_id == $au->company_id;
831 // yes, only owner company can mess with this...
832 $owncomp = DB_DataObject::Factory('Companies');
833 $owncomp->get('comptype', 'OWNER');
835 $isStaff = ($this->company_id == $owncomp->id);
839 // extra case change passwod?
840 case 'P': //??? password
841 // standard perms -- for editing + if the user is dowing them selves..
842 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
843 return $ret || $au->id == $this->id;
846 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
851 function onInsert($req, $roo)
854 $p = DB_DataObject::factory('person');
855 if ($roo->authUser->id < 0 && $p->count() == 1) {
856 // this seems a bit risky...
858 $g = DB_DataObject::factory('Groups');
862 $g->get('name', 'Administrators');
864 $p = DB_DataObject::factory('group_members');
865 $p->group_id = $g->id;
866 $p->user_id = $this->id;
869 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
873 if (!empty($req['project_id_addto'])) {
874 $pd = DB_DataObject::factory('ProjectDirectory');
875 $pd->project_id = $req['project_id_addto'];
876 $pd->person_id = $this->id;
878 $pd->office_id = $this->office_id;
879 $pd->company_id = $this->company_id;
885 function importFromArray($roo, $persons, $prefix)
887 foreach($persons as $person){
888 $p = DB_DataObject::factory('person');
889 if($p->get('name', $person['name'])){
892 $p->setFrom($person);
894 $companies = DB_DataObject::factory('companies');
895 if(!$companies->get('comptype', 'OWNER')){
896 $roo->jerr("Missing OWNER companies!");
898 $p->company_id = $companies->pid();
899 // strip the 'spaces etc.. make lowercase..
900 $name = strtolower(str_replace(' ', '', $person['name']));
901 $p->setPassword("$prefix$name");
904 // if $person->groups is set.. then
905 // add this person to that group eg. groups : [ 'Administrator' ]
906 if(!empty($person['groups'])){
907 $groups = DB_DataObject::factory('groups');
908 if(!$groups->get('name', $person['groups'])){
909 $roo->jerr("Missing groups : {$person['groups']}");
911 $gm = DB_DataObject::factory('group_members');
912 $gm->change($p, $groups, true);
915 $p->onInsert(array(), $roo);