3 * Table Definition for Person
5 class_exists('DB_DataObject') ? '' : require_once 'DB/DataObject.php';
8 class Pman_Core_DataObjects_Core_person extends DB_DataObject
11 /* the code below is auto generated do not remove the above tag */
13 public $__table = 'core_person'; // table name
14 public $id; // int(11) not_null primary_key auto_increment
15 public $email; // string(128) not_null
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
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)
36 public $active; // int(11) not_null
37 public $deleted_by; // int(11) not_null
38 public $deleted_dt; // datetime(19) binary
41 public $name_facebook; // VARCHAR(128) NULL;
42 public $url_blog; // VARCHAR(256) NULL ;
43 public $url_twitter; // VARCHAR(256) NULL ;
44 public $url_linkedin; // VARCHAR(256) NULL ;
45 public $linkedin_id; // VARCHAR(256) NULL ;
47 public $phone_mobile; // varchar(32) NOT NULL DEFAULT '';
48 public $phone_direct; // varchar(32) NOT NULL DEFAULT '';
49 public $countries; // VARCHAR(128) NULL;
51 /* the code above is auto generated do not remove the tag below */
56 $p = DB_DataObject::Factory($this->tableName());
57 $p->get($this->owner_id);
66 * FIXME !!!! -- USE Pman_Core_Mailer !!!!!
72 function buildMail($templateFile, $args)
75 $args = (array) $args;
76 $content = clone($this);
78 foreach((array)$args as $k=>$v) {
82 $ff = HTML_FlexyFramework::get();
85 //?? is this really the place for this???
88 empty($args['no_auth']) &&
89 !in_array($templateFile, array(
90 // templates that can be sent without authentication.
96 $content->authUser = $this->getAuthUser();
97 if (!$content->authUser) {
98 return PEAR::raiseError("Not authenticated");
102 // should handle x-forwarded...
104 $content->HTTP_HOST = isset($_SERVER["HTTP_HOST"]) ?
105 $_SERVER["HTTP_HOST"] :
106 (isset($ff->HTTP_HOST) ? $ff->HTTP_HOST : 'localhost');
108 /* use the regex compiler, as it doesnt parse <tags */
111 'compiler' => 'Flexy',
113 'filters' => array('SimpleTags','Mail'),
119 if (!empty($args['templateDir'])) {
120 $tops['templateDir'] = $args['templateDir'];
125 require_once 'HTML/Template/Flexy.php';
126 $template = new HTML_Template_Flexy( $tops );
127 $template->compile("mail/$templateFile.txt");
129 /* use variables from this object to ouput data. */
130 $mailtext = $template->bufferedOutputObject($content);
133 // if a html file with the same name exists, use that as the body
134 // I've no idea where this code went, it was here before..
135 if (false !== $template->resolvePath ( "mail/$templateFile.html" )) {
136 $tops['nonHTML'] = false;
137 $template = new HTML_Template_Flexy( $tops );
138 $template->compile("mail/$templateFile.html");
139 $htmlbody = $template->bufferedOutputObject($content);
145 //echo "<PRE>";print_R($mailtext);
146 //print_R($mailtext);exit;
147 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
148 require_once 'Mail/mimeDecode.php';
149 require_once 'Mail.php';
151 $decoder = new Mail_mimeDecode($mailtext);
152 $parts = $decoder->getSendArray();
154 if (is_a($parts,'PEAR_Error')) {
156 //echo "PROBLEM: {$parts->message}";
159 list($recipents,$headers,$body) = $parts;
160 $recipents = array($this->email);
161 if (!empty($content->bcc) && is_array($content->bcc)) {
162 $recipents =array_merge($recipents, $content->bcc);
164 $headers['Date'] = date('r');
166 if ($htmlbody !== false) {
167 require_once 'Mail/mime.php';
168 $mime = new Mail_mime(array('eol' => "\n"));
169 $mime->setTXTBody($body);
170 $mime->setHTMLBody($htmlbody);
171 // I think there might be code in mediaoutreach toEmail somewhere
172 // h embeds images here..
173 $body = $mime->get();
174 $headers = $mime->headers($headers);
178 'recipients' => $recipents,
179 'headers' => $headers,
187 * - user must be authenticate or args[no_auth] = true
188 * or template = password_[reset|welcome]
191 function sendTemplate($templateFile, $args)
193 $ar = $this->buildMail($templateFile, $args);
195 //print_r($recipents);exit;
196 $mailOptions = PEAR::getStaticProperty('Mail','options');
197 $mail = Mail::factory("SMTP",$mailOptions);
199 if (PEAR::isError($mail)) {
202 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
203 $ret = $mail->send($ar['recipients'],$ar['headers'],$ar['body']);
204 error_reporting($oe);
212 function getEmailFrom()
214 if (empty($this->name)) {
218 return '"' . addslashes($this->name) . '" <' . $this->email . '>';
221 function toEventString()
223 return empty($this->name) ? $this->email : $this->name;
226 function verifyAuth()
228 $ff= HTML_FlexyFramework::get();
229 if (!empty($ff->Pman['auth_comptype']) &&
230 (!$this->company_id || ($ff->Pman['auth_comptype'] != $this->company()->comptype))
233 $sesPrefix = $this->sesPrefix();
235 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = "";
239 //$ff->page->jerr("Login not permited to outside companies");
246 // ---------------- authentication / passwords and keys stuff ----------------
251 $ff= HTML_FlexyFramework::get();
253 $sesPrefix = $this->sesPrefix();
255 if (!empty($_SESSION[get_class($this)][$sesPrefix .'-auth'])) {
257 $a = unserialize($_SESSION[get_class($this)][$sesPrefix .'-auth']);
259 $u = DB_DataObject::factory($this->tableName());
260 if ($a->id && $u->get($a->id)) { //&& strlen($u->passwd)) {
262 return $u->verifyAuth(); // got authentication...
267 unset($_SESSION[get_class($this)][$sesPrefix .'-auth']);
268 unset($_SESSION[get_class($this)][$sesPrefix .'-timeout']);
269 setcookie('Pman.timeout', -1, time() + (30*60), '/');
274 $u = DB_DataObject::factory($this->tableName());
276 if (!empty($_SERVER['PHP_AUTH_USER'])
278 !empty($_SERVER['PHP_AUTH_PW'])
280 $u->get('email', $_SERVER['PHP_AUTH_USER'])
282 $u->checkPassword($_SERVER['PHP_AUTH_PW'])
284 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize($u);
288 if (!$this->canInitializeSystem()) {
289 // die("can not init");
294 $auto_auth_allow = false;
295 if (!empty($ff->Pman['local_autoauth']) && $ff->Pman['local_autoauth'] === true) {
296 $auto_auth_allow = true;
299 (!empty($_SERVER['SERVER_ADDR'])) &&
301 $_SERVER['SERVER_ADDR'] == '127.0.0.1' &&
302 $_SERVER['REMOTE_ADDR'] == '127.0.0.1'
306 $_SERVER['SERVER_ADDR'] == '::1' &&
307 $_SERVER['REMOTE_ADDR'] == '::1'
311 $auto_auth_allow = true;
315 if (empty($_SERVER['PATH_INFO']) || $_SERVER['PATH_INFO'] == '/Login') {
316 $auto_auth_allow = false;
318 //var_dump($auto_auth_allow);
320 $default_admin = false;
321 if ($auto_auth_allow) {
322 $group = DB_DataObject::factory('core_group');
323 $group->get('name', 'Administrators');
325 $member = DB_DataObject::factory('core_group_member');
327 $member->group_id = $group->id;
329 join_user_id_id.id IS NOT NULL
331 if($member->find(true)){
332 $default_admin = DB_DataObject::factory($this->tableName());
333 if(!$default_admin->get($member->user_id)){
334 $default_admin = false;
339 //var_dump($ff->Pman['local_autoauth']); var_dump($_SERVER); exit;
340 $u = DB_DataObject::factory($this->tableName());
341 $ff = HTML_FlexyFramework::get();
343 if ($auto_auth_allow &&
344 ($default_admin || $u->get('email', $ff->Pman['local_autoauth']))
347 $user = $default_admin ? $default_admin->toArray() : $u->toArray();
349 //$_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object) $user);
353 //var_dump(session_id());
354 //var_dump($_SESSION[__CLASS__]);
356 //if (!empty( $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
359 //die("got this far?");
360 // not in session or not matched...
361 $u = DB_DataObject::factory($this->tableName());
362 $u->whereAdd(' LENGTH(passwd) > 0');
364 $_SESSION[get_class($this)][$sesPrefix .'-empty'] = $n;
365 if (class_exists('PEAR')) {
366 $error = PEAR::getStaticProperty('DB_DataObject','lastError');
368 die($error->toString()); // not really a good thing to do...
371 if (!$n){ // authenticated as there are no users in the system...
378 function canInitializeSystem()
381 return !strcasecmp(get_class($this) , __CLASS__);
384 function getAuthUser()
386 if (!$this->isAuth()) {
390 $ff= HTML_FlexyFramework::get();
392 $sesPrefix = $this->sesPrefix();
394 //var_dump(array(get_class($this),$sesPrefix .'-auth'));
396 if (!empty($_SESSION[get_class($this)][$sesPrefix .'-auth'])) {
397 $a = unserialize($_SESSION[get_class($this)][$sesPrefix .'-auth']);
399 $u = DB_DataObject::factory($this->tableName()); // allow extending this ...
401 if ($u->get($a->id)) { /// && strlen($u->passwd)) { // should work out the pid .. really..
403 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = time() + (30*60); // eg. 30 minutes
404 setcookie('Pman.timeout', time() + (30*60), time() + (30*60), '/');
410 unset($_SESSION[get_class($this)][$sesPrefix .'-auth']);
411 unset($_SESSION[get_class($this)][$sesPrefix .'-timeout']);
412 setcookie('Pman.timeout', -1, time() + (30*60), '/');
418 if (!$this->canInitializeSystem()) {
424 if (empty( $_SESSION[get_class($this)][$sesPrefix .'-empty'] )) {
425 $u = DB_DataObject::factory($this->tableName());
426 $u->whereAdd(' LENGTH(passwd) > 0');
427 $_SESSION[get_class($this)][$sesPrefix .'-empty'] = $u->count();
432 isset( $_SESSION[get_class($this)][$sesPrefix .'-empty'] ) &&
433 $_SESSION[get_class($this)][$sesPrefix .'-empty'] < 1
436 // fake person - open system..
437 //$ce = DB_DataObject::factory('core_enum');
441 $u = DB_DataObject::factory($this->tableName());
444 // if a company has been created fill that in in company_id_id
445 $c = DB_DAtaObject::factory('core_company')->lookupOwner();
447 $u->company_id_id = $c->pid();
448 $u->company_id = $c->pid();
458 $this->isAuth(); // force session start..
459 if (!$this->verifyAuth()) { // check for company valid..
463 // open up iptables at login..
464 $dbname = $this->databaseNickname();
465 touch( '/tmp/run_pman_admin_iptables-'.$dbname);
467 // refresh admin group if we are logged in as one..
468 //DB_DataObject::debugLevel(1);
469 $g = DB_DataObject::factory('core_group');
471 $g->get('name', 'Administrators');
472 $gm = DB_DataObject::Factory('core_group_member');
473 if (in_array($g->id,$gm->listGroupMembership($this))) {
474 // refresh admin groups.
475 $gr = DB_DataObject::Factory('core_group_right');
476 $gr->applyDefs($g, 0);
479 $sesPrefix = $this->sesPrefix();
481 // we should not store the whole data in the session - otherwise it get's huge.
482 $p = DB_DAtaObject::Factory($this->tableName());
483 $p->get($this->pid());
487 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = time() + (30*60); // eg. 30 minutes
488 setcookie('Pman.timeout', time() + (30*60), time() + (30*60), '/');
490 //var_dump(array(get_class($this),$sesPrefix .'-auth'));
491 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object)$d);
492 // ensure it's written so that ajax calls can fetch it..
499 $this->isAuth(); // force session start..
501 $sesPrefix = $this->sesPrefix();
503 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = -1;
505 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = "";
508 function genPassKey ($t)
510 return md5($this->email . $t. $this->passwd);
512 function simpleAuthKey($m = 0)
514 $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
516 return md5(implode(',' , array($month, $this->email , $this->passwd, $this->id)));
519 function checkTwoFactorAuthentication($val)
523 // also used in login
524 require_once 'System.php';
528 empty($this->oath_key)
533 $oathtool = System::which('oathtool');
539 $cmd = "{$oathtool} --totp --base32 " . escapeshellarg($this->oath_key);
541 $password = exec($cmd);
543 return ($password == $val) ? true : false;
546 function checkPassword($val)
548 if (substr($this->passwd,0,1) == '$') {
549 if (function_exists('pasword_verify')) {
550 return password_verify($val, $this->passwd);
552 return crypt($val,$this->passwd) == $this->passwd ;
554 // old style md5 passwords...- cant be used with courier....
555 return md5($val) == $this->passwd;
558 function setPassword($value)
560 if (function_exists('pasword_hash')) {
561 return password_hash($value);
565 while(strlen($salt)<9) {
566 $salt.=chr(rand(64,126));
567 //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
569 $this->passwd = crypt($value, '$1$'. $salt. '$');
574 function generatePassword($length = 5) // genearte a password (add set 'rawPasswd' to it's value)
576 require_once 'Text/Password.php';
577 $this->rawPasswd = strtr(ucfirst(Text_Password::create($length)).ucfirst(Text_Password::create($length)), array(
578 "a"=>"4", "e"=>"3", "i"=>"1", "o"=>"0", "s"=>"5", "t"=>"7"));
579 $this->setPassword($this->rawPasswd);
580 return $this->rawPasswd;
585 $x = DB_DataObject::factory('core_company');
587 $x->get($this->company_id);
590 function loadCompany()
592 $this->company = $this->company();
597 return $this->active;
599 function authUserName($n) // set username prior to acheck user exists query.
602 $this->whereAdd('LENGTH(passwd) > 1');
607 if (!func_num_args()) {
610 $val = array_shift(func_get_args());
611 if ($val == $this->lang) {
621 function authUserArray()
624 $aur = $this->toArray();
631 //DB_DataObject::debugLevel(1);
632 $c = DB_Dataobject::factory('core_company');
633 $im = DB_Dataobject::factory('Images');
634 $c->joinAdd($im, 'LEFT');
636 $c->selectAs($c, 'company_id_%s');
637 $c->selectAs($im, 'company_id_logo_id_%s');
638 $c->id = $this->company_id;
642 $aur = array_merge( $c->toArray(),$aur);
644 if (empty($c->company_id_logo_id_id)) {
646 $im = DB_Dataobject::factory('Images');
647 $im->ontable = DB_DataObject::factory('core_company')->tableName();
649 $im->imgtype = 'LOGO';
652 $im->selectAs($im, 'company_id_logo_id_%s');
653 if ($im->find(true)) {
655 foreach($im->toArray() as $k=>$v) {
656 if (!preg_match('/^company_id_logo_id_/', $k)) {
665 $aur['perms'] = $this->getPerms();
666 $g = DB_DataObject::Factory('core_group_member');
667 $aur['groups'] = $g->listGroupMembership($this, 'name');
670 $aur['dailykey'] = '';
671 $aur['oath_key'] = '';
673 $aur['oath_key_enable'] = !empty($this->oath_key);
674 $aur['require_oath'] = 1;
676 $s = DB_DataObject::Factory('core_setting');
677 $oath_require = $s->lookup('core', 'two_factor_authentication_requirement');
678 $aur['require_oath'] = $oath_require ? $oath_require->val : 0;
683 // ----------PERMS------ ----------------
686 //DB_DataObject::debugLevel(1);
687 // find out all the groups they are a member of.. + Default..
689 // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
691 $g = DB_DataObject::Factory('core_group_right');
697 return $g->adminRights(); // system is not set up - so they get full rights.
699 //DB_DataObject::debugLevel(1);
700 $g = DB_DataObject::Factory('core_group_member');
701 $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
703 // add the current user to the admin group..
704 $g = DB_DataObject::Factory('core_group');
705 if ($g->get('name', 'Administrators')) {
706 $gm = DB_DataObject::Factory('core_group_member');
707 $gm->group_id = $g->id;
708 $gm->user_id = $this->id;
714 // ------ STANDARD PERMISSION HANDLING.
715 $isOwner = $this->company()->comptype == 'OWNER';
716 $g = DB_DataObject::Factory('core_group_member');
717 $grps = $g->listGroupMembership($this);
719 $isAdmin = $g->inAdmin; //??? what???
720 //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
721 // the load all the perms for those groups, and add them all together..
722 // then load all those
723 $g = DB_DataObject::Factory('core_group_right');
724 $ret = $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
725 //echo '<PRE>';print_r($ret);
731 *Basic group fetching - probably needs to filter by type eventually.
733 *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
736 function groups($what=false)
738 $g = DB_DataObject::Factory('core_group_member');
739 $grps = $g->listGroupMembership($this);
740 $g = DB_DataObject::Factory('core_group');
741 $g->whereAddIn('id', $grps, 'int');
742 return $g->fetchAll($what);
748 function hasPerm($name, $lvl)
750 static $pcache = array();
752 if (!isset($pcache[$this->id])) {
753 $pcache[$this->id] = $this->getPerms();
756 // echo "<PRE>";print_r($pcache[$au->id]);
757 // var_dump($pcache[$au->id]);
758 if (empty($pcache[$this->id][$name])) {
762 return strpos($pcache[$this->id][$name], $lvl) > -1;
766 // ------------ROO HOOKS------------------------------------
767 function applyFilters($q, $au, $roo)
769 //DB_DataObject::DebugLevel(1);
770 if(!empty($q['_to_qr_code'])){
771 $person = DB_DataObject::factory('Core_person');
772 $person->id = $q['id'];
774 if(!$person->find(true)) {
775 $roo->jerr('_invalid_person');
778 $hash = $this->generateOathKey();
780 $_SESSION[__CLASS__] =
781 isset($_SESSION[__CLASS__]) ?
782 $_SESSION[__CLASS__] : array();
783 $_SESSION[__CLASS__]['oath'] =
784 isset($_SESSION[__CLASS__]['oath']) ?
785 $_SESSION[__CLASS__]['oath'] : array();
787 $_SESSION[__CLASS__]['oath'][$person->id] = $hash;
789 $qrcode = $person->generateQRCode($hash);
792 $roo->jerr('Fail to generate QR Code');
798 if(!empty($q['two_factor_auth_code'])) {
799 $person = DB_DataObject::factory('core_person');
800 $person->get($q['id']);
802 $person->oath_key = $_SESSION[__CLASS__]['oath'][$person->id];
804 if($person->checkTwoFactorAuthentication($q['two_factor_auth_code'])) {
806 unset($_SESSION[__CLASS__]['oath'][$person->id]);
810 $roo->jerr('_invalid_auth_code');
813 if(!empty($q['oath_key_disable'])) {
814 $person = DB_DataObject::factory('core_person');
815 $person->get($q['id']);
819 $person->oath_key = '';
825 if (!empty($q['query']['is_owner'])) {
826 $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
829 if (!empty($q['query']['person_not_internal'])) {
830 $this->whereAdd(" join_company_id_id.isOwner = 0 ");
833 if (!empty($q['query']['person_internal_only_all'])) {
836 // must be internal and not current user (need for distribution list)
837 // user has a projectdirectory entry and role is not blank.
838 //DB_DataObject::DebugLevel(1);
839 $pd = DB_DataObject::factory('ProjectDirectory');
840 $pd->whereAdd("role != ''");
842 $pd->selectAdd('distinct(person_id) as person_id');
843 $roled = $pd->fetchAll('person_id');
845 {$this->tableName()}.id IN (".implode(',', $roled) . ")
847 $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
850 // -- for distribution
851 if (!empty($q['query']['person_internal_only'])) {
852 // must be internal and not current user (need for distribution list)
853 $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
855 //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
856 // ".id != ".$au->id);
857 $this->whereAdd("{$this->tableName()}.id != {$au->id}");
860 if (!empty($q['query']['comptype_or_company_id'])) {
861 // DB_DataObject::debugLevel(1);
862 $bits = explode(',', $q['query']['comptype_or_company_id']);
863 $id = (int) array_pop($bits);
864 $ct = $this->escape($bits[0]);
866 $this->whereAdd(" join_company_id_id.comptype = '$ct' OR {$this->tableName()}.company_id = $id");
872 if (!empty($q['query']['person_inactive'])) {
873 // DB_Dataobject::debugLevel(1);
876 $tn_p = $this->tableName();
877 $tn_gm = DB_DataObject::Factory('core_group_member')->tableName();
878 $tn_g = DB_DataObject::Factory('core_group')->tableName();
880 ///---------------- Group views --------
881 if (!empty($q['query']['in_group'])) {
882 // DB_DataObject::debugLevel(1);
883 $ing = (int) $q['query']['in_group'];
884 if ($q['query']['in_group'] == -1) {
886 // list all staff who are not in a group.
887 $this->whereAdd("{$this->tableName()}.id NOT IN (
888 SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
889 $tn_g ON $tn_g.id = $tn_gm.group_id)");
893 $this->whereAdd("$tn_p.id IN (
894 SELECT distinct(user_id) FROM $tn_gm
895 WHERE group_id = $ing
901 if(!empty($q['in_group_name'])){
903 $v = $this->escape($q['in_group_name']);
908 DISTINCT(user_id) FROM $tn_gm
912 $tn_g.id = $tn_gm.group_id
919 // #2307 Search Country!!
920 if (!empty($q['query']['in_country'])) {
921 // DB_DataObject::debugLevel(1);
922 $inc = $q['query']['in_country'];
923 $this->whereAdd("$tn_p.countries LIKE '%{$inc}%'");
926 if (!empty($q['query']['not_in_directory'])) {
927 // it's a Person list..
928 // DB_DATaobjecT::debugLevel(1);
930 // specific to project directory which is single comp. login
932 $owncomp = DB_DataObject::Factory('core_company');
933 $owncomp->get('comptype', 'OWNER');
934 if ($q['company_id'] == $owncomp->id) {
940 if ( $q['query']['not_in_directory'] > -1) {
941 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
942 // can list current - so that it does not break!!!
943 $this->whereAdd("$tn_p.id NOT IN
944 ( SELECT distinct person_id FROM $tn_pd WHERE
945 project_id = " . $q['query']['not_in_directory'] . " AND
946 company_id = " . $this->company_id . ')');
950 if (!empty($q['query']['role'])) {
951 // it's a Person list..
952 // DB_DATaobjecT::debugLevel(1);
954 // specific to project directory which is single comp. login
956 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
957 // can list current - so that it does not break!!!
958 $this->whereAdd("$tn_p.id IN
959 ( SELECT distinct person_id FROM $tn_pd WHERE
960 role = '". $this->escape($q['query']['role']) ."'
966 if (!empty($q['query']['project_member_of'])) {
967 // this is also a flag to return if they are a member..
968 //DB_DataObject::debugLevel(1);
969 $do = DB_DataObject::factory('ProjectDirectory');
970 $do->project_id = $q['query']['project_member_of'];
971 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
972 $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
973 $this->selectAdd("IF($tn_pd.id IS NULL, 0, $tn_pd.id ) as is_member");
976 if (!empty($q['query']['project_member_filter'])) {
977 $this->having('is_member !=0');
983 if(!empty($q['query']['name'])){
985 {$this->tableName()}.name LIKE '%{$this->escape($q['query']['name'])}%'
988 if(!empty($q['query']['name_starts'])){
990 {$this->tableName()}.name LIKE '{$this->escape($q['query']['name_starts'])}%'
994 if (!empty($q['query']['search'])) {
996 // use our magic search builder...
998 require_once 'Text/SearchParser.php';
999 $x = new Text_SearchParser($q['query']['search']);
1007 "join_company_id_id.name"
1009 $tbcols = $this->table();
1010 foreach(array('firstname','lastname') as $k) {
1011 if (isset($tbcols[$k])) {
1012 $props[] = "{$tn_p}.{$k}";
1019 $str = $x->toSQL(array(
1020 'default' => $props,
1022 'company' => 'join_company_id_id.name',
1023 //'country' => 'Clipping.country',
1024 // 'media' => 'Clipping.media_name',
1026 'escape' => array($this->getDatabaseConnection(), 'escapeSimple'), /// pear db or mdb object..
1031 $this->whereAdd($str); /*
1032 $tn_p.name LIKE '%$s%' OR
1033 $tn_p.email LIKE '%$s%' OR
1034 $tn_p.role LIKE '%$s%' OR
1035 $tn_p.phone LIKE '%$s%' OR
1036 $tn_p.remarks LIKE '%$s%'
1041 // project directory rules -- this may distrupt things.
1042 $p = DB_DataObject::factory('ProjectDirectory');
1043 // if project directories are set up, then we can apply project query rules..
1046 $pids = $p->projects($au);
1047 if (isset($q['query']['project_id'])) {
1048 $pid = (int)$q['query']['project_id'];
1049 if (!in_array($pid, $pids)) {
1050 $roo->jerr("Project not in users valid projects");
1052 $pids = array($pid);
1055 //if (empty($q['_anyrole'])) { // should be project_directry_role
1056 // $p->whereAdd("{$p->tableName()}.role != ''");
1058 if (!empty($q['query']['role'])) { // should be project_directry_role
1059 $role = $this->escape($q['query']['role']);
1061 $p->whereAdd("{$p->tableName()}.role LIKE '%{$role}%'");
1065 if (!$roo->hasPerm('Core.Projects_All', 'S')) {
1066 $peps = $p->people($pids);
1067 $this->whereAddIn("{$tn}.id", $peps, 'int');
1071 // fixme - this needs a more generic fix - it was from the mtrack_person code...
1072 if (isset($q['query']['ticket_id'])) {
1073 // find out what state the ticket is in.
1074 $t = DB_DataObject::Factory('mtrack_ticket');
1076 $t->get($q['query']['ticket_id']);
1078 if (!$this->checkPerm('S', $au)) {
1079 $roo->jerr("permssion denied to query state of ticket");
1082 $p = DB_DataObject::factory('ProjectDirectory');
1083 $pids = array($t->project_id);
1085 $peps = $p->people($pids);
1087 $this->whereAddIn($this->tableName().'.id', $peps, 'int');
1089 //$this->whereAdd('join_prole != ''");
1094 * Seems we never expose oath_key / passwd, so...
1097 if($this->tableName() == 'core_person'){
1098 $this->_extra_cols = array('length_passwd', 'length_oath_key');
1101 LENGTH({$this->tableName()}.passwd) AS length_passwd,
1102 LENGTH({$this->tableName()}.oath_key) AS length_oath_key
1109 function setFromRoo($ar, $roo)
1111 $this->setFrom($ar);
1113 if(!empty($ar['_enable_oath_key'])){
1114 $oath_key = $this->generateOathKey();
1117 if (!empty($ar['passwd1'])) {
1118 $this->setPassword($ar['passwd1']);
1122 ($this->email == $roo->old->email)&&
1123 ($this->company_id == $roo->old->company_id)
1127 if (empty($this->email)) {
1130 // this only applies to our owner company..
1131 $c = $this->company();
1132 if (empty($c->comptype_name) || $c->comptype_name != 'OWNER') {
1137 $xx = DB_Dataobject::factory($this->tableName());
1139 'email' => $this->email,
1140 // 'company_id' => $x->company_id
1144 return "Duplicate Email found";
1151 * before Delete - delete significant dependancies..
1152 * this is called after checkPerm..
1155 function beforeDelete($dependants_array, $roo)
1157 //delete group membership except for admin group..
1158 // if they are a member of admin group do not delete anything.
1159 $default_admin = false;
1161 $e = DB_DataObject::Factory('Events');
1162 $e->whereAdd('person_id = ' . $this->id);
1164 $g = DB_DataObject::Factory('core_group');
1165 $g->get('name', 'Administrators'); // select * from core_group where name = 'Administrators'
1167 $p = DB_DataObject::Factory('core_group_member');
1169 'user_id' => $this->id,
1170 'group_id' => $g->id
1174 $roo->jerr("Please remove this user from the Administrator group before deleting");
1178 $p = DB_DataObject::Factory('core_group_member');
1179 $p->user_id = $this->id;
1180 $mem = $p->fetchAll(); // fetch all the rows and set the $mem variable to the rows data, just like mysqli_fetch_assoc
1181 $e->logDeletedRecord($mem);
1183 foreach($mem as $p) {
1187 $e = DB_DataObject::Factory('Events');
1188 $e->person_id = $this->id;
1189 $eve = $e->fetchAll(); // fetch all the rows and set the $mem variable to the rows data, just like mysqli_fetch_assoc
1191 $e->logDeletedRecord($eve);
1192 foreach($eve as $e) {
1203 * Check if the a user has access to modify this item.
1204 * @param String $lvl Level (eg. Core.Projects)
1205 * @param Pman_Core_DataObjects_Person $au The authenticated user.
1206 * @param boolean $changes alllow changes???
1208 * @return false if no access..
1210 function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
1213 // do we have an empty system..
1214 if ($au && $au->id == -1) {
1217 // if not authenticated... do not allow in???
1222 // determine if it's staff!!!
1223 $owncomp = DB_DataObject::Factory('core_company');
1224 $owncomp->get('comptype', 'OWNER');
1225 $isStaff = ($au->company_id == $owncomp->id);
1230 // - can not change company!!!
1232 isset($changes['company_id']) &&
1233 $changes['company_id'] != $au->company_id) {
1236 // can only set new emails..
1238 !empty($this->email) &&
1239 isset($changes['email']) &&
1240 $changes['email'] != $this->email) {
1245 // mtrack had the idea that all 'S' should be allowed.. - but filtered later..
1246 // ???? do we want this?
1248 // edit self... - what about other staff members...
1250 //return $this->company_id == $au->company_id;
1254 // yes, only owner company can mess with this...
1260 // extra case change passwod?
1261 case 'P': //??? password
1262 // standard perms -- for editing + if the user is dowing them selves..
1263 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
1264 return $ret || $au->id == $this->id;
1267 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
1273 function beforeInsert($req, $roo)
1275 $p = DB_DataObject::factory('core_person');
1276 if ($roo->authUser->id > -1 || $p->count() > 1) {
1279 $c = DB_DataObject::Factory('core_company');
1282 if (!$tc || $tc> 1) {
1283 $roo->jerr("can not create initial user as multiple companies already exist");
1286 $this->company_id = $c->id;
1287 $this->email = trim($this->email);
1291 function onInsert($req, $roo)
1294 $p = DB_DataObject::factory('core_person');
1295 if ($roo->authUser->id < 0 && $p->count() == 1) {
1296 // this seems a bit risky...
1298 $g = DB_DataObject::factory('core_group');
1302 $g->get('name', 'Administrators');
1304 $p = DB_DataObject::factory('core_group_member');
1305 $p->group_id = $g->id;
1306 $p->user_id = $this->id;
1309 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
1313 if (!empty($req['project_id_addto'])) {
1314 $pd = DB_DataObject::factory('ProjectDirectory');
1315 $pd->project_id = $req['project_id_addto'];
1316 $pd->person_id = $this->id;
1318 $pd->office_id = $this->office_id;
1319 $pd->company_id = $this->company_id;
1325 function importFromArray($roo, $persons, $opts)
1327 if (empty($opts['prefix'])) {
1328 $roo->jerr("opts[prefix] is empty - you can not just create passwords based on the user names");
1331 if (!is_array($persons) || empty($persons)) {
1332 $roo->jerr("error in the person data. - empty on not valid");
1334 DB_DataObject::factory('core_group')->initGroups();
1336 foreach($persons as $person){
1337 $p = DB_DataObject::factory('core_person');
1338 if($p->get('name', $person['name'])){
1341 $p->setFrom($person);
1343 $companies = DB_DataObject::factory('core_company');
1344 if(!$companies->get('comptype', 'OWNER')){
1345 $roo->jerr("Missing OWNER companies!");
1347 $p->company_id = $companies->pid();
1348 // strip the 'spaces etc.. make lowercase..
1349 $name = strtolower(str_replace(' ', '', $person['name']));
1350 $p->setPassword("{$opts['prefix']}{$name}");
1353 // if $person->groups is set.. then
1354 // add this person to that group eg. groups : [ 'Administrator' ]
1355 if(!empty($person['groups'])){
1356 $groups = DB_DataObject::factory('core_group');
1357 if(!$groups->get('name', $person['groups'])){
1358 $roo->jerr("Missing groups : {$person['groups']}");
1360 $gm = DB_DataObject::factory('core_group_member');
1361 $gm->change($p, $groups, true);
1364 $p->onInsert(array(), $roo);
1368 // this is for the To: "{getEmailName()}" <email@address>
1369 // not good for Dear XXXX, - use {person.firstname} for that.
1370 function getEmailName()
1374 if(!empty($this->honor)){
1375 array_push($name, $this->honor);
1378 if(!empty($this->name)){
1379 array_push($name, $this->name);
1381 return implode(' ', $name);
1384 if(!empty($this->firstname) || !empty($this->lastname)){
1385 array_push($name, $this->firstname);
1386 array_push($name, $this->lastname);
1388 $name = array_filter($name);
1390 return implode(' ', $name);
1393 return $this->email;
1396 function sesPrefix()
1398 $ff= HTML_FlexyFramework::get();
1400 $appname = empty($ff->appNameShort) ? $ff->project : $ff->project . '-' . $ff->appNameShort;
1402 $dname = method_exists($this, 'getDatabaseConnection') ? $this->getDatabaseConnection()->dsn['database'] : $this->databaseNickname();
1404 $sesPrefix = $appname.'-' .get_class($this) .'-' . $dname;
1409 function loginPublic()
1411 $this->isAuth(); // force session start..
1413 $db = $this->getDatabaseConnection();
1415 $ff = HTML_FlexyFramework::get();
1417 if(empty($ff->Pman) || empty($ff->Pman['login_public'])){
1421 $sesPrefix = $ff->Pman['login_public'] . '-' .get_class($this) .'-'.$db->dsn['database'] ;
1423 $p = DB_DAtaObject::Factory($this->tableName());
1424 $p->get($this->pid());
1426 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object)$p->toArray());
1431 function beforeUpdate($old, $q, $roo)
1433 $this->email = trim($this->email);
1436 function generateOathKey()
1438 require 'Base32.php';
1440 $base32 = new Base32();
1442 return $base32->base32_encode(bin2hex(openssl_random_pseudo_bytes(10)));
1445 function generateQRCode($hash)
1448 empty($this->email) &&
1454 $issuer = (empty($this->name)) ?
1455 rawurlencode('ROOJS') : rawurlencode($this->name);
1457 $uri = "otpauth://totp/{$issuer}:{$this->email}?secret={$hash}&issuer={$issuer}&algorithm=SHA1&digits=6&period=30";
1459 require_once 'Image/QRCode.php';
1461 $qrcode = new Image_QRCode();
1463 $image = $qrcode->makeCode($uri, array(
1464 'output_type' => 'return'
1469 $base64 = base64_encode(ob_get_contents());
1472 return "data:image/png;base64,{$base64}";