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 */
54 function applyFilters($q, $au, $roo)
56 $cg = DB_DataObject::Factory('core_group')->tableName();
57 $cgm = DB_DataObject::Factory('core_group_member')->tableName();
61 SELECT GROUP_CONCAT(CONCAT_WS('\"', ${cgm}.group_id, '\"'))
67 {$this->tableName()}.id = {$cgm}.user_id
70 ) AS group_membership_list
79 $p = DB_DataObject::Factory($this->tableName());
80 $p->get($this->owner_id);
89 * FIXME !!!! -- USE Pman_Core_Mailer !!!!!
95 function buildMail($templateFile, $args)
98 $args = (array) $args;
99 $content = clone($this);
101 foreach((array)$args as $k=>$v) {
105 $ff = HTML_FlexyFramework::get();
108 //?? is this really the place for this???
111 empty($args['no_auth']) &&
112 !in_array($templateFile, array(
113 // templates that can be sent without authentication.
119 $content->authUser = $this->getAuthUser();
120 if (!$content->authUser) {
121 return PEAR::raiseError("Not authenticated");
125 // should handle x-forwarded...
127 $content->HTTP_HOST = isset($_SERVER["HTTP_HOST"]) ?
128 $_SERVER["HTTP_HOST"] :
129 (isset($ff->HTTP_HOST) ? $ff->HTTP_HOST : 'localhost');
131 /* use the regex compiler, as it doesnt parse <tags */
134 'compiler' => 'Flexy',
136 'filters' => array('SimpleTags','Mail'),
142 if (!empty($args['templateDir'])) {
143 $tops['templateDir'] = $args['templateDir'];
148 require_once 'HTML/Template/Flexy.php';
149 $template = new HTML_Template_Flexy( $tops );
150 $template->compile("mail/$templateFile.txt");
152 /* use variables from this object to ouput data. */
153 $mailtext = $template->bufferedOutputObject($content);
156 // if a html file with the same name exists, use that as the body
157 // I've no idea where this code went, it was here before..
158 if (false !== $template->resolvePath ( "mail/$templateFile.html" )) {
159 $tops['nonHTML'] = false;
160 $template = new HTML_Template_Flexy( $tops );
161 $template->compile("mail/$templateFile.html");
162 $htmlbody = $template->bufferedOutputObject($content);
168 //echo "<PRE>";print_R($mailtext);
169 //print_R($mailtext);exit;
170 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
171 require_once 'Mail/mimeDecode.php';
172 require_once 'Mail.php';
174 $decoder = new Mail_mimeDecode($mailtext);
175 $parts = $decoder->getSendArray();
177 if (is_a($parts,'PEAR_Error')) {
179 //echo "PROBLEM: {$parts->message}";
182 list($recipents,$headers,$body) = $parts;
183 $recipents = array($this->email);
184 if (!empty($content->bcc) && is_array($content->bcc)) {
185 $recipents =array_merge($recipents, $content->bcc);
187 $headers['Date'] = date('r');
189 if ($htmlbody !== false) {
190 require_once 'Mail/mime.php';
191 $mime = new Mail_mime(array('eol' => "\n"));
192 $mime->setTXTBody($body);
193 $mime->setHTMLBody($htmlbody);
194 // I think there might be code in mediaoutreach toEmail somewhere
195 // h embeds images here..
196 $body = $mime->get();
197 $headers = $mime->headers($headers);
204 'recipients' => $recipents,
205 'headers' => $headers,
215 * - user must be authenticate or args[no_auth] = true
216 * or template = password_[reset|welcome]
219 function sendTemplate($templateFile, $args)
222 $ar = $this->buildMail($templateFile, $args);
225 //print_r($recipents);exit;
226 $mailOptions = PEAR::getStaticProperty('Mail','options');
227 $mail = Mail::factory("SMTP",$mailOptions);
229 if (PEAR::isError($mail)) {
232 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
233 $ret = $mail->send($ar['recipients'],$ar['headers'],$ar['body']);
234 error_reporting($oe);
243 function getEmailFrom()
245 if (empty($this->name)) {
249 return '"' . addslashes($this->name) . '" <' . $this->email . '>';
252 function toEventString()
254 return empty($this->name) ? $this->email : $this->name;
257 function verifyAuth()
259 $ff= HTML_FlexyFramework::get();
260 if (!empty($ff->Pman['auth_comptype']) &&
261 (!$this->company_id || ($ff->Pman['auth_comptype'] != $this->company()->comptype))
264 $sesPrefix = $this->sesPrefix();
266 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = "";
270 //$ff->page->jerr("Login not permited to outside companies");
277 // ---------------- authentication / passwords and keys stuff ----------------
282 $ff= HTML_FlexyFramework::get();
284 $sesPrefix = $this->sesPrefix();
286 if (!empty($_SESSION[get_class($this)][$sesPrefix .'-auth'])) {
288 $a = unserialize($_SESSION[get_class($this)][$sesPrefix .'-auth']);
290 $u = DB_DataObject::factory($this->tableName());
291 if ($a->id && $u->get($a->id)) { //&& strlen($u->passwd)) {
293 return $u->verifyAuth(); // got authentication...
298 unset($_SESSION[get_class($this)][$sesPrefix .'-auth']);
299 unset($_SESSION[get_class($this)][$sesPrefix .'-timeout']);
300 setcookie('Pman.timeout', -1, time() + (30*60), '/');
305 $u = DB_DataObject::factory($this->tableName());
307 if (!empty($_SERVER['PHP_AUTH_USER'])
309 !empty($_SERVER['PHP_AUTH_PW'])
311 $u->get('email', $_SERVER['PHP_AUTH_USER'])
313 $u->checkPassword($_SERVER['PHP_AUTH_PW'])
315 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize($u);
319 if (!$this->canInitializeSystem()) {
320 // die("can not init");
326 $default_admin = false;
327 if (!empty($ff->Pman['local_autoauth']) &&
328 ($ff->Pman['local_autoauth'] === true) &&
329 (!empty($_SERVER['SERVER_ADDR'])) &&
332 $_SERVER['SERVER_ADDR'] == '127.0.0.1' &&
333 $_SERVER['REMOTE_ADDR'] == '127.0.0.1'
337 $_SERVER['SERVER_ADDR'] == '::1' &&
338 $_SERVER['REMOTE_ADDR'] == '::1'
342 $group = DB_DataObject::factory('core_group');
343 $group->get('name', 'Administrators');
345 $member = DB_DataObject::factory('core_group_member');
347 $member->group_id = $group->id;
349 join_user_id_id.id IS NOT NULL
351 if($member->find(true)){
352 $default_admin = DB_DataObject::factory($this->tableName());
353 if(!$default_admin->get($member->user_id)){
354 $default_admin = false;
359 //var_dump($ff->Pman['local_autoauth']); var_dump($_SERVER); exit;
360 $u = DB_DataObject::factory($this->tableName());
361 $ff = HTML_FlexyFramework::get();
363 if (!empty($ff->Pman['local_autoauth']) &&
364 (!empty($_SERVER['SERVER_ADDR'])) &&
367 $_SERVER['SERVER_ADDR'] == '127.0.0.1' &&
368 $_SERVER['REMOTE_ADDR'] == '127.0.0.1'
372 $_SERVER['SERVER_ADDR'] == '::1' &&
373 $_SERVER['REMOTE_ADDR'] == '::1'
376 ($default_admin || $u->get('email', $ff->Pman['local_autoauth']))
379 $user = $default_admin ? $default_admin->toArray() : $u->toArray();
381 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object) $user);
385 //var_dump(session_id());
386 //var_dump($_SESSION[__CLASS__]);
388 //if (!empty( $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
391 //die("got this far?");
392 // not in session or not matched...
393 $u = DB_DataObject::factory($this->tableName());
394 $u->whereAdd(' LENGTH(passwd) > 0');
396 $_SESSION[get_class($this)][$sesPrefix .'-empty'] = $n;
397 if (class_exists('PEAR')) {
398 $error = PEAR::getStaticProperty('DB_DataObject','lastError');
400 die($error->toString()); // not really a good thing to do...
403 if (!$n){ // authenticated as there are no users in the system...
411 function canInitializeSystem()
414 return !strcasecmp(get_class($this) , __CLASS__);
417 function getAuthUser()
419 if (!$this->isAuth()) {
423 $ff= HTML_FlexyFramework::get();
425 $sesPrefix = $this->sesPrefix();
427 //var_dump(array(get_class($this),$sesPrefix .'-auth'));
429 if (!empty($_SESSION[get_class($this)][$sesPrefix .'-auth'])) {
430 $a = unserialize($_SESSION[get_class($this)][$sesPrefix .'-auth']);
432 $u = DB_DataObject::factory($this->tableName()); // allow extending this ...
434 if ($u->get($a->id)) { /// && strlen($u->passwd)) { // should work out the pid .. really..
436 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = time() + (30*60); // eg. 30 minutes
437 setcookie('Pman.timeout', time() + (30*60), time() + (30*60), '/');
443 unset($_SESSION[get_class($this)][$sesPrefix .'-auth']);
444 unset($_SESSION[get_class($this)][$sesPrefix .'-timeout']);
445 setcookie('Pman.timeout', -1, time() + (30*60), '/');
451 if (!$this->canInitializeSystem()) {
457 if (empty( $_SESSION[get_class($this)][$sesPrefix .'-empty'] )) {
458 $u = DB_DataObject::factory($this->tableName());
459 $u->whereAdd(' LENGTH(passwd) > 0');
460 $_SESSION[get_class($this)][$sesPrefix .'-empty'] = $u->count();
464 if (isset( $_SESSION[get_class($this)][$sesPrefix .'-empty'] ) && $_SESSION[get_class($this)][$sesPrefix .'-empty'] < 1) {
466 // fake person - open system..
467 //$ce = DB_DataObject::factory('core_enum');
471 $u = DB_DataObject::factory($this->tableName());
474 // if a company has been created fill that in in company_id_id
475 $c = DB_DAtaObject::factory('core_company')->lookupOwner();
477 $u->company_id_id = $c->pid();
478 $u->company_id = $c->pid();
488 $this->isAuth(); // force session start..
489 if (!$this->verifyAuth()) { // check for company valid..
493 // open up iptables at login..
494 $dbname = $this->databaseNickname();
495 touch( '/tmp/run_pman_admin_iptables-'.$dbname);
497 // refresh admin group if we are logged in as one..
498 //DB_DataObject::debugLevel(1);
499 $g = DB_DataObject::factory('core_group');
501 $g->get('name', 'Administrators');
502 $gm = DB_DataObject::Factory('core_group_member');
503 if (in_array($g->id,$gm->listGroupMembership($this))) {
504 // refresh admin groups.
505 $gr = DB_DataObject::Factory('core_group_right');
506 $gr->applyDefs($g, 0);
509 $sesPrefix = $this->sesPrefix();
511 // we should not store the whole data in the session - otherwise it get's huge.
512 $p = DB_DAtaObject::Factory($this->tableName());
513 $p->get($this->pid());
517 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = time() + (30*60); // eg. 30 minutes
518 setcookie('Pman.timeout', time() + (30*60), time() + (30*60), '/');
520 //var_dump(array(get_class($this),$sesPrefix .'-auth'));
521 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object)$d);
522 // ensure it's written so that ajax calls can fetch it..
529 $this->isAuth(); // force session start..
531 $sesPrefix = $this->sesPrefix();
533 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = -1;
535 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = "";
538 function genPassKey ($t)
540 return md5($this->email . $t. $this->passwd);
542 function simpleAuthKey($m = 0)
544 $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
546 return md5(implode(',' , array($month, $this->email , $this->passwd, $this->id)));
549 function checkTwoFactorAuthentication($val)
551 require_once 'System.php';
553 $oathtool = System::which('oathtool');
559 $cmd = "{$oathtool} --totp --base32 {$this->oath_key}";
561 $password = exec($cmd);
563 return ($password == $val) ? true : false;
566 function checkPassword($val)
568 if (substr($this->passwd,0,1) == '$') {
569 if (function_exists('pasword_verify')) {
570 return password_verify($val, $this->passwd);
572 return crypt($val,$this->passwd) == $this->passwd ;
574 // old style md5 passwords...- cant be used with courier....
575 return md5($val) == $this->passwd;
578 function setPassword($value)
580 if (function_exists('pasword_hash')) {
581 return password_hash($value);
585 while(strlen($salt)<9) {
586 $salt.=chr(rand(64,126));
587 //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
589 $this->passwd = crypt($value, '$1$'. $salt. '$');
594 function generatePassword($length = 5) // genearte a password (add set 'rawPasswd' to it's value)
596 require_once 'Text/Password.php';
597 $this->rawPasswd = strtr(ucfirst(Text_Password::create($length)).ucfirst(Text_Password::create($length)), array(
598 "a"=>"4", "e"=>"3", "i"=>"1", "o"=>"0", "s"=>"5", "t"=>"7"));
599 $this->setPassword($this->rawPasswd);
600 return $this->rawPasswd;
605 $x = DB_DataObject::factory('core_company');
607 $x->get($this->company_id);
610 function loadCompany()
612 $this->company = $this->company();
617 return $this->active;
619 function authUserName($n) // set username prior to acheck user exists query.
622 $this->whereAdd('LENGTH(passwd) > 1');
627 if (!func_num_args()) {
630 $val = array_shift(func_get_args());
631 if ($val == $this->lang) {
641 function authUserArray()
644 $aur = $this->toArray();
651 //DB_DataObject::debugLevel(1);
652 $c = DB_Dataobject::factory('core_company');
653 $im = DB_Dataobject::factory('Images');
654 $c->joinAdd($im, 'LEFT');
656 $c->selectAs($c, 'company_id_%s');
657 $c->selectAs($im, 'company_id_logo_id_%s');
658 $c->id = $this->company_id;
662 $aur = array_merge( $c->toArray(),$aur);
664 if (empty($c->company_id_logo_id_id)) {
666 $im = DB_Dataobject::factory('Images');
667 $im->ontable = DB_DataObject::factory('core_company')->tableName();
669 $im->imgtype = 'LOGO';
672 $im->selectAs($im, 'company_id_logo_id_%s');
673 if ($im->find(true)) {
675 foreach($im->toArray() as $k=>$v) {
676 if (!preg_match('/^company_id_logo_id_/', $k)) {
685 $aur['perms'] = $this->getPerms();
686 $g = DB_DataObject::Factory('core_group_member');
687 $aur['groups'] = $g->listGroupMembership($this, 'name');
690 $aur['dailykey'] = '';
691 $aur['oath_key'] = '';
697 // ----------PERMS------ ----------------
700 //DB_DataObject::debugLevel(1);
701 // find out all the groups they are a member of.. + Default..
703 // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
705 $g = DB_DataObject::Factory('core_group_right');
711 return $g->adminRights(); // system is not set up - so they get full rights.
713 //DB_DataObject::debugLevel(1);
714 $g = DB_DataObject::Factory('core_group_member');
715 $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
717 // add the current user to the admin group..
718 $g = DB_DataObject::Factory('core_group');
719 if ($g->get('name', 'Administrators')) {
720 $gm = DB_DataObject::Factory('core_group_member');
721 $gm->group_id = $g->id;
722 $gm->user_id = $this->id;
728 // ------ STANDARD PERMISSION HANDLING.
729 $isOwner = $this->company()->comptype == 'OWNER';
730 $g = DB_DataObject::Factory('core_group_member');
731 $grps = $g->listGroupMembership($this);
733 $isAdmin = $g->inAdmin; //??? what???
734 //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
735 // the load all the perms for those groups, and add them all together..
736 // then load all those
737 $g = DB_DataObject::Factory('core_group_right');
738 $ret = $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
739 //echo '<PRE>';print_r($ret);
745 *Basic group fetching - probably needs to filter by type eventually.
747 *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
750 function groups($what=false)
752 $g = DB_DataObject::Factory('core_group_member');
753 $grps = $g->listGroupMembership($this);
754 $g = DB_DataObject::Factory('core_group');
755 $g->whereAddIn('id', $grps, 'int');
756 return $g->fetchAll($what);
762 function hasPerm($name, $lvl)
764 static $pcache = array();
766 if (!isset($pcache[$this->id])) {
767 $pcache[$this->id] = $this->getPerms();
770 // echo "<PRE>";print_r($pcache[$au->id]);
771 // var_dump($pcache[$au->id]);
772 if (empty($pcache[$this->id][$name])) {
776 return strpos($pcache[$this->id][$name], $lvl) > -1;
780 // ------------ROO HOOKS------------------------------------
781 function applyFilters($q, $au, $roo)
783 //DB_DataObject::DebugLevel(1);
785 if (!empty($q['query']['is_owner'])) {
786 $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
789 if (!empty($q['query']['person_not_internal'])) {
790 $this->whereAdd(" join_company_id_id.isOwner = 0 ");
793 if (!empty($q['query']['person_internal_only_all'])) {
796 // must be internal and not current user (need for distribution list)
797 // user has a projectdirectory entry and role is not blank.
798 //DB_DataObject::DebugLevel(1);
799 $pd = DB_DataObject::factory('ProjectDirectory');
800 $pd->whereAdd("role != ''");
802 $pd->selectAdd('distinct(person_id) as person_id');
803 $roled = $pd->fetchAll('person_id');
805 {$this->tableName()}.id IN (".implode(',', $roled) . ")
807 $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
810 // -- for distribution
811 if (!empty($q['query']['person_internal_only'])) {
812 // must be internal and not current user (need for distribution list)
813 $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
815 //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
816 // ".id != ".$au->id);
817 $this->whereAdd("{$this->tableName()}.id != {$au->id}");
820 if (!empty($q['query']['comptype_or_company_id'])) {
821 // DB_DataObject::debugLevel(1);
822 $bits = explode(',', $q['query']['comptype_or_company_id']);
823 $id = (int) array_pop($bits);
824 $ct = $this->escape($bits[0]);
826 $this->whereAdd(" join_company_id_id.comptype = '$ct' OR {$this->tableName()}.company_id = $id");
832 if (!empty($q['query']['person_inactive'])) {
833 // DB_Dataobject::debugLevel(1);
836 $tn_p = $this->tableName();
837 $tn_gm = DB_DataObject::Factory('core_group_member')->tableName();
838 $tn_g = DB_DataObject::Factory('core_group')->tableName();
840 ///---------------- Group views --------
841 if (!empty($q['query']['in_group'])) {
842 // DB_DataObject::debugLevel(1);
843 $ing = (int) $q['query']['in_group'];
844 if ($q['query']['in_group'] == -1) {
846 // list all staff who are not in a group.
847 $this->whereAdd("{$this->tableName()}.id NOT IN (
848 SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
849 $tn_g ON $tn_g.id = $tn_gm.group_id
850 WHERE $tn_g.type = ".$q['query']['type']."
856 $this->whereAdd("$tn_p.id IN (
857 SELECT distinct(user_id) FROM $tn_gm
858 WHERE group_id = $ing
864 if(!empty($q['in_group_name'])){
866 $v = $this->escape($q['in_group_name']);
871 DISTINCT(user_id) FROM $tn_gm
875 $tn_g.id = $tn_gm.group_id
882 // #2307 Search Country!!
883 if (!empty($q['query']['in_country'])) {
884 // DB_DataObject::debugLevel(1);
885 $inc = $q['query']['in_country'];
886 $this->whereAdd("$tn_p.countries LIKE '%{$inc}%'");
889 if (!empty($q['query']['not_in_directory'])) {
890 // it's a Person list..
891 // DB_DATaobjecT::debugLevel(1);
893 // specific to project directory which is single comp. login
895 $owncomp = DB_DataObject::Factory('core_company');
896 $owncomp->get('comptype', 'OWNER');
897 if ($q['company_id'] == $owncomp->id) {
903 if ( $q['query']['not_in_directory'] > -1) {
904 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
905 // can list current - so that it does not break!!!
906 $this->whereAdd("$tn_p.id NOT IN
907 ( SELECT distinct person_id FROM $tn_pd WHERE
908 project_id = " . $q['query']['not_in_directory'] . " AND
909 company_id = " . $this->company_id . ')');
913 if (!empty($q['query']['role'])) {
914 // it's a Person list..
915 // DB_DATaobjecT::debugLevel(1);
917 // specific to project directory which is single comp. login
919 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
920 // can list current - so that it does not break!!!
921 $this->whereAdd("$tn_p.id IN
922 ( SELECT distinct person_id FROM $tn_pd WHERE
923 role = '". $this->escape($q['query']['role']) ."'
929 if (!empty($q['query']['project_member_of'])) {
930 // this is also a flag to return if they are a member..
931 //DB_DataObject::debugLevel(1);
932 $do = DB_DataObject::factory('ProjectDirectory');
933 $do->project_id = $q['query']['project_member_of'];
934 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
935 $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
936 $this->selectAdd("IF($tn_pd.id IS NULL, 0, $tn_pd.id ) as is_member");
939 if (!empty($q['query']['project_member_filter'])) {
940 $this->having('is_member !=0');
946 if(!empty($q['query']['name'])){
948 {$this->tableName()}.name LIKE '%{$this->escape($q['query']['name'])}%'
951 if(!empty($q['query']['name_starts'])){
953 {$this->tableName()}.name LIKE '{$this->escape($q['query']['name_starts'])}%'
957 if (!empty($q['query']['search'])) {
959 // use our magic search builder...
961 require_once 'Text/SearchParser.php';
962 $x = new Text_SearchParser($q['query']['search']);
970 "join_company_id_id.name"
972 $tbcols = $this->table();
973 foreach(array('firstname','lastname') as $k) {
974 if (isset($tbcols[$k])) {
975 $props[] = "{$tn_p}.{$k}";
982 $str = $x->toSQL(array(
985 'company' => 'join_company_id_id.name',
986 //'country' => 'Clipping.country',
987 // 'media' => 'Clipping.media_name',
989 'escape' => array($this->getDatabaseConnection(), 'escapeSimple'), /// pear db or mdb object..
994 $this->whereAdd($str); /*
995 $tn_p.name LIKE '%$s%' OR
996 $tn_p.email LIKE '%$s%' OR
997 $tn_p.role LIKE '%$s%' OR
998 $tn_p.phone LIKE '%$s%' OR
999 $tn_p.remarks LIKE '%$s%'
1004 // project directory rules -- this may distrupt things.
1005 $p = DB_DataObject::factory('ProjectDirectory');
1006 // if project directories are set up, then we can apply project query rules..
1009 $pids = $p->projects($au);
1010 if (isset($q['query']['project_id'])) {
1011 $pid = (int)$q['query']['project_id'];
1012 if (!in_array($pid, $pids)) {
1013 $roo->jerr("Project not in users valid projects");
1015 $pids = array($pid);
1018 //if (empty($q['_anyrole'])) { // should be project_directry_role
1019 // $p->whereAdd("{$p->tableName()}.role != ''");
1021 if (!empty($q['query']['role'])) { // should be project_directry_role
1022 $role = $this->escape($q['query']['role']);
1024 $p->whereAdd("{$p->tableName()}.role LIKE '%{$role}%'");
1028 if (!$roo->hasPerm('Core.Projects_All', 'S')) {
1029 $peps = $p->people($pids);
1030 $this->whereAddIn("{$tn}.id", $peps, 'int');
1034 // fixme - this needs a more generic fix - it was from the mtrack_person code...
1035 if (isset($q['query']['ticket_id'])) {
1036 // find out what state the ticket is in.
1037 $t = DB_DataObject::Factory('mtrack_ticket');
1039 $t->get($q['query']['ticket_id']);
1041 if (!$this->checkPerm('S', $au)) {
1042 $roo->jerr("permssion denied to query state of ticket");
1045 $p = DB_DataObject::factory('ProjectDirectory');
1046 $pids = array($t->project_id);
1048 $peps = $p->people($pids);
1050 $this->whereAddIn($this->tableName().'.id', $peps, 'int');
1052 //$this->whereAdd('join_prole != ''");
1057 * Seems we never expose oath_key / passwd, so...
1060 if($this->tableName() == 'core_person'){
1061 $this->_extra_cols = array('length_passwd', 'length_oath_key');
1064 LENGTH({$this->tableName()}.passwd) AS length_passwd,
1065 LENGTH({$this->tableName()}.oath_key) AS length_oath_key
1072 function setFromRoo($ar, $roo)
1074 $this->setFrom($ar);
1076 if(!empty($ar['_enable_oath_key'])){
1077 $this->generateOathKey();
1080 if (!empty($ar['passwd1'])) {
1081 $this->setPassword($ar['passwd1']);
1085 ($this->email == $roo->old->email)&&
1086 ($this->company_id == $roo->old->company_id)
1090 if (empty($this->email)) {
1093 // this only applies to our owner company..
1094 $c = $this->company();
1095 if (empty($c->comptype_name) || $c->comptype_name != 'OWNER') {
1100 $xx = DB_Dataobject::factory($this->tableName());
1102 'email' => $this->email,
1103 // 'company_id' => $x->company_id
1107 return "Duplicate Email found";
1114 * before Delete - delete significant dependancies..
1115 * this is called after checkPerm..
1118 function beforeDelete($dependants_array, $roo)
1120 //delete group membership except for admin group..
1121 // if they are a member of admin group do not delete anything.
1122 $default_admin = false;
1124 $e = DB_DataObject::Factory('Events');
1125 $e->whereAdd('person_id = ' . $this->id);
1127 $g = DB_DataObject::Factory('core_group');
1128 $g->get('name', 'Administrators'); // select * from core_group where name = 'Administrators'
1130 $p = DB_DataObject::Factory('core_group_member');
1132 'user_id' => $this->id,
1133 'group_id' => $g->id
1137 $roo->jerr("Please remove this user from the Administrator group before deleting");
1141 $p = DB_DataObject::Factory('core_group_member');
1142 $p->user_id = $this->id;
1143 $mem = $p->fetchAll(); // fetch all the rows and set the $mem variable to the rows data, just like mysqli_fetch_assoc
1145 $e->logDeletedRecord($p);
1147 foreach($mem as $p) {
1151 $e = DB_DataObject::Factory('events');
1152 $e->person_id = $this->id;
1153 $eve = $e->fetchAll(); // fetch all the rows and set the $mem variable to the rows data, just like mysqli_fetch_assoc
1155 foreach($eve as $e) {
1167 * Check if the a user has access to modify this item.
1168 * @param String $lvl Level (eg. Core.Projects)
1169 * @param Pman_Core_DataObjects_Person $au The authenticated user.
1170 * @param boolean $changes alllow changes???
1172 * @return false if no access..
1174 function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
1177 // do we have an empty system..
1178 if ($au && $au->id == -1) {
1181 // if not authenticated... do not allow in???
1186 // determine if it's staff!!!
1187 $owncomp = DB_DataObject::Factory('core_company');
1188 $owncomp->get('comptype', 'OWNER');
1189 $isStaff = ($au->company_id == $owncomp->id);
1194 // - can not change company!!!
1196 isset($changes['company_id']) &&
1197 $changes['company_id'] != $au->company_id) {
1200 // can only set new emails..
1202 !empty($this->email) &&
1203 isset($changes['email']) &&
1204 $changes['email'] != $this->email) {
1209 // mtrack had the idea that all 'S' should be allowed.. - but filtered later..
1210 // ???? do we want this?
1212 // edit self... - what about other staff members...
1214 //return $this->company_id == $au->company_id;
1218 // yes, only owner company can mess with this...
1224 // extra case change passwod?
1225 case 'P': //??? password
1226 // standard perms -- for editing + if the user is dowing them selves..
1227 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
1228 return $ret || $au->id == $this->id;
1231 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
1237 function beforeInsert($req, $roo)
1239 $p = DB_DataObject::factory('core_person');
1240 if ($roo->authUser->id > -1 || $p->count() > 1) {
1243 $c = DB_DataObject::Factory('core_company');
1246 if (!$tc || $tc> 1) {
1247 $roo->jerr("can not create initial user as multiple companies already exist");
1250 $this->company_id = $c->id;
1254 function onInsert($req, $roo)
1257 $p = DB_DataObject::factory('core_person');
1258 if ($roo->authUser->id < 0 && $p->count() == 1) {
1259 // this seems a bit risky...
1261 $g = DB_DataObject::factory('core_group');
1265 $g->get('name', 'Administrators');
1267 $p = DB_DataObject::factory('core_group_member');
1268 $p->group_id = $g->id;
1269 $p->user_id = $this->id;
1272 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
1276 if (!empty($req['project_id_addto'])) {
1277 $pd = DB_DataObject::factory('ProjectDirectory');
1278 $pd->project_id = $req['project_id_addto'];
1279 $pd->person_id = $this->id;
1281 $pd->office_id = $this->office_id;
1282 $pd->company_id = $this->company_id;
1288 function importFromArray($roo, $persons, $opts)
1290 if (empty($opts['prefix'])) {
1291 $roo->jerr("opts[prefix] is empty - you can not just create passwords based on the user names");
1294 if (!is_array($persons) || empty($persons)) {
1295 $roo->jerr("error in the person data. - empty on not valid");
1297 DB_DataObject::factory('core_group')->initGroups();
1299 foreach($persons as $person){
1300 $p = DB_DataObject::factory('core_person');
1301 if($p->get('name', $person['name'])){
1304 $p->setFrom($person);
1306 $companies = DB_DataObject::factory('core_company');
1307 if(!$companies->get('comptype', 'OWNER')){
1308 $roo->jerr("Missing OWNER companies!");
1310 $p->company_id = $companies->pid();
1311 // strip the 'spaces etc.. make lowercase..
1312 $name = strtolower(str_replace(' ', '', $person['name']));
1313 $p->setPassword("{$opts['prefix']}{$name}");
1316 // if $person->groups is set.. then
1317 // add this person to that group eg. groups : [ 'Administrator' ]
1318 if(!empty($person['groups'])){
1319 $groups = DB_DataObject::factory('core_group');
1320 if(!$groups->get('name', $person['groups'])){
1321 $roo->jerr("Missing groups : {$person['groups']}");
1323 $gm = DB_DataObject::factory('core_group_member');
1324 $gm->change($p, $groups, true);
1327 $p->onInsert(array(), $roo);
1331 // this is for the To: "{getEmailName()}" <email@address>
1332 // not good for Dear XXXX, - use {person.firstname} for that.
1333 function getEmailName()
1337 if(!empty($this->honor)){
1338 array_push($name, $this->honor);
1341 if(!empty($this->name)){
1342 array_push($name, $this->name);
1344 return implode(' ', $name);
1347 if(!empty($this->firstname) || !empty($this->lastname)){
1348 array_push($name, $this->firstname);
1349 array_push($name, $this->lastname);
1351 $name = array_filter($name);
1353 return implode(' ', $name);
1356 return $this->email;
1359 function sesPrefix()
1361 $ff= HTML_FlexyFramework::get();
1363 $appname = empty($ff->appNameShort) ? $ff->project : $ff->project . '-' . $ff->appNameShort;
1365 $dname = method_exists($this, 'getDatabaseConnection') ? $this->getDatabaseConnection()->dsn['database'] : $this->databaseNickname();
1367 $sesPrefix = $appname.'-' .get_class($this) .'-' . $dname;
1372 function loginPublic()
1374 $this->isAuth(); // force session start..
1376 $db = $this->getDatabaseConnection();
1378 $ff = HTML_FlexyFramework::get();
1380 if(empty($ff->Pman) || empty($ff->Pman['login_public'])){
1384 $sesPrefix = $ff->Pman['login_public'] . '-' .get_class($this) .'-'.$db->dsn['database'] ;
1386 $p = DB_DAtaObject::Factory($this->tableName());
1387 $p->get($this->pid());
1389 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object)$p->toArray());
1394 function beforeUpdate($old, $q, $roo)
1396 if(!empty($q['_generate_oath_key'])){
1398 $this->generateOathKey();
1403 if(!empty($q['_to_qr_code'])){
1404 $qrcode = $this->generateQRCode();
1407 $roo->jerr('Fail to generate QR Code');
1412 // handle group_id here..
1413 if(!empty($q['group_id'])){
1415 // insert data into core_person_member...
1421 function generateOathKey()
1423 $hex = bin2hex(openssl_random_pseudo_bytes(10));
1425 require 'Base32.php';
1427 $base32 = new Base32();
1429 $this->oath_key = $base32->base32_encode($hex);
1431 return $this->oath_key;
1435 function generateQRCode()
1437 if(empty($this->oath_key)){
1441 $issuer = (empty($this->name)) ? rawurlencode('ROOJS') : rawurlencode($this->name);
1443 $uri = "otpauth://totp/{$issuer}:{$this->email}?secret={$this->oath_key}&issuer={$issuer}&algorithm=SHA1&digits=6&period=30";
1445 require_once 'Image/QRCode.php';
1447 $qrcode = new Image_QRCode();
1449 $image = $qrcode->makeCode($uri, array(
1450 'output_type' => 'return'
1455 $base64 = base64_encode(ob_get_contents());
1458 return "data:image/png;base64,{$base64}";