DataObjects/Core_company.php
[Pman.Core] / DataObjects / Core_company.php
1 <?php
2 /**
3  * Table Definition for Companies
4  */
5 class_exists('DB_DataObject') ? '' : require_once 'DB/DataObject.php';
6
7 class Pman_Core_DataObjects_Core_Company extends DB_DataObject 
8 {
9     ###START_AUTOCODE
10     /* the code below is auto generated do not remove the above tag */
11
12     public $__table = 'core_company';                       // table name
13     public $code;                            // string(32)  not_null
14     public $name;                            // string(128)  
15     public $remarks;                         // blob(65535)  blobeforeDeleteb
16     public $owner_id;                        // int(11)  not_null
17     public $address;                         // blob(65535)  blob
18     public $tel;                             // string(32)  
19     public $fax;                             // string(32)  
20     public $email;                           // string(128)  
21     public $id;                              // int(11)  not_null primary_key auto_increment
22     public $isOwner;                         // int(11)  
23     public $logo_id;                         // int(11)  not_null
24     public $background_color;                // string(8)  not_null
25     public $comptype;                        // string(8)  not_null
26     public $url;                             // string(254)  not_null
27     public $main_office_id;                  // int(11)  not_null
28     public $created_by;                      // int(11)  not_null
29     public $created_dt;                      // datetime(19)  not_null binary
30     public $updated_by;                      // int(11)  not_null
31     public $updated_dt;                      // datetime(19)  not_null binary
32     public $passwd;                          // string(64)  not_null
33     public $dispatch_port;                   // string(255)  not_null
34     public $province;                        // string(255)  not_null
35     public $country;                         // string(4)  not_null
36     public $is_system;                       // int(2)
37     
38     /* the code above is auto generated do not remove the tag below */
39     ###END_AUTOCODE
40     
41     function applyFilters($q, $au, $roo)
42     {
43         
44         $tn = $this->tableName();
45         if (empty($q['_distinct']))  {
46             $this->selectAdd("i18n_translate('c' , {$tn}.country, 'en') as country_display_name ");
47         }
48       
49         $tn = $this->tableName();
50         //DB_DataObject::debugLevel(1);
51         $x = DB_DataObject::factory('core_company');
52         $x->comptype= 'OWNER';
53         $x->find(true);
54
55         if (!empty($q['query']['company_project_id'])) {
56             $add = '';
57             if (!empty($q['query']['company_include_self'])) {
58                 $add = " OR {$tn}.id = {$x->id}";
59             }
60             if (!empty($q['query']['company_not_self'])) {
61                 $add = " AND {$tn}.id != {$x->id}";
62             }
63             
64             $pids = array();
65             $pid = $q['query']['company_project_id'];
66             if (strpos($pid, ',')) {
67                 $bits = explode(',', $pid);
68                 foreach($bits as $b) {
69                     $pids[] = (int)$b;
70                 }
71             } else {
72                 $pids = array($pid);
73             }
74             
75             
76             $pids = implode(',', $pids);
77             $this->whereAdd("{$tn}.id IN (
78                 SELECT distinct(company_id) FROM ProjectDirectory where project_id IN ($pids)
79             ) $add" );
80              
81         }
82         if (!empty($q['query']['comptype'])) {
83            
84             $this->whereAddIn('comptype', explode(',', $q['query']['comptype']), 'string');
85             
86         }
87         
88         // depricated - should be moved to module specific (texon afair)
89         
90          if (!empty($q['query']['province'])) {
91              $prov = $this->escape($q['query']['province']);
92             $this->whereAdd("province LIKE '$prov%'");
93             
94             
95         }
96         // ADD comptype_display name.. = for combos..
97         $this->selectAdd("
98             (SELECT display_name
99                 FROM
100                     core_enum
101                 WHERE
102                     etype='comptype'
103                     AND
104                     name={$tn}.comptype
105                 LIMIT 1
106                 ) as comptype_display_name
107         ");
108         
109         if(!empty($q['query']['name']) || !empty($q['search']['name'])){
110             
111             $s = (!empty($q['query']['name'])) ? $this->escape($q['query']['name']) : $this->escape($q['search']['name']);
112             
113             $this->whereAdd("
114                 {$tn}.name LIKE '%$s%'
115             ");
116         }
117         
118         if(!empty($q['query']['name_starts']) || !empty($q['search']['name_starts'])){
119             
120             $s = (!empty($q['query']['name_starts'])) ? $this->escape($q['query']['name_starts']) : $this->escape($q['search']['name_starts']);
121             
122             $this->whereAdd("
123                 {$tn}.name LIKE '$s%'
124             ");
125         }
126     }
127     
128     function toEventString() {
129         return $this->name;
130     }
131     
132     // ---------- AUTHENTICATION
133     // not sure where authetnication via company is used?? posibly media-outreach
134     
135     function isAuth()
136     {
137         $db = $this->getDatabaseConnection();
138         $sesPrefix = $db->dsn['database'];
139         if  (empty($_SERVER['PHP_AUTH_USER'])) {
140             @session_start();
141         }
142         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
143             // in session...
144             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
145             $u = DB_DataObject::factory('core_company');
146             if ($u->get($a->id)) { //&& strlen($u->passwd)) {
147                 return true;
148             }
149             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = '';
150             
151         }
152         // not in session or not matched...
153         
154         
155         return false;
156         
157     }
158     function getAuthUser()
159     {
160         if (!$this->isAuth()) {
161             return false;
162         }
163         $db = $this->getDatabaseConnection();
164         $sesPrefix = $db->dsn['database'];
165         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
166             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
167             
168             $u = DB_DataObject::factory('core_company');
169             if ($u->get($a->id)) { /// && strlen($u->passwd)) {
170                 return clone($u);
171             }
172              
173         }
174         
175         
176         return false;
177     }     
178     function login()
179     {
180         $this->isAuth(); // force session start..
181          $db = $this->getDatabaseConnection();
182         $sesPrefix = $db->dsn['database'];
183         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($this);
184         
185     }
186     function logout()
187     {
188         $this->isAuth(); // force session start..
189         $db = $this->getDatabaseConnection();
190         $sesPrefix = $db->dsn['database'];
191         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
192         
193     }    
194     // ---------- AUTHENTICATION
195     function checkPassword($val)
196     {
197         //echo '<pre>'.$val .  print_R($this,true);
198         if (substr($this->passwd,0,1) == '$') {
199             return crypt($val,$this->passwd) == $this->passwd ;
200         }
201         // old style md5 passwords...- cant be used with courier....
202         return md5($val) == $this->passwd;
203     }
204     function setPassword($value) 
205     {
206         $salt='';
207         while(strlen($salt)<9) {
208             $salt.=chr(rand(64,126));
209             //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
210         }
211         $this->passwd = crypt($value, '$1$'. $salt. '$');
212        
213     }      
214     function onUpload($controller)
215     {
216         $image = DB_DataObject::factory('Images');
217         return $image->onUploadWithTbl($this, 'logo_id');
218          
219     }
220     function  onUpdate($old, $req,$roo) 
221     {
222         if (!empty($req['password1'])) {
223             $this->setPassword($req['password1']);
224             $this->update();
225         }
226     }
227     function onInsert($req, $roo)
228     {
229         if (!empty($this->logo_id)) { // update images table to sycn with this..
230             $img = DB_DataObject::factory('Images');
231             if ($img->get($this->logo_id) && ($img->onid != $this->id)) {
232                 $img->onid = $this->id;
233                 $img->update();
234             }
235         }
236         if (!empty($req['password1'])) {
237             $this->setPassword($req['password1']);
238             $this->update();
239         }
240         $img = DB_DataObject::factory('Images');
241         $img->onid= 0;
242         
243         $img->ontable = $this->tableName();
244         $img->imgtype = 'LOGO';
245         // should check uploader!!!
246         if ($img->find()) {
247             while($img->fetch()) {
248                 $ii = clone($img);
249                 $ii->onid = $this->id;
250                 $ii->update();
251                 $this->logo_id = $ii->id;
252             }
253             $this->update();
254         }
255         
256     }
257     
258     function beforeInsert($q, $roo)
259     {
260         // we still use comptype in some old systems...
261         
262         if(!empty($q['comptype']) && empty($q['comptype_id'])) {
263             $en = DB_DataObject::Factory('core_enum');
264             $en->setFrom(array(
265                 'etype' => 'COMPTYPE',
266                 'name' => $q['comptype'],
267                 'active' => 1
268             ));
269             if($en->find(true)) {
270                 $this->comptype_id = $en->id;
271             }
272         }
273         
274         if (!empty($q['comptype_id'])) {
275             $en = DB_DataObject::Factory('core_enum');
276             $en->get($q['comptype_id']);
277             $this->comptype = $en->name;
278         }
279         
280         if(!empty($q['_check_name'])){
281             if($this->checkName()){
282                 $roo->jok('OK');
283             }
284             
285             $roo->jerr('EXIST');
286         }
287     }
288     
289     function beforeUpdate($old, $q,$roo)
290     {
291         // we still use comptype in some old systems...
292         
293         if(!empty($q['comptype']) && empty($q['comptype_id'])) {
294             $en = DB_DataObject::Factory('core_enum');
295             $en->setFrom(array(
296                 'etype' => 'COMPTYPE',
297                 'name' => $q['comptype'],
298                 'active' => 1
299             ));
300             if($en->find(true)) {
301                 $this->comptype_id = $en->id;
302             }
303         }
304         
305         if (!empty($q['comptype_id'])) {
306             $en = DB_DataObject::Factory('core_enum');
307             $en->get($q['comptype_id']);
308             $this->comptype = $en->name;
309         }
310         
311         if(!empty($q['_flag_delete'])){
312             $this->deleted_dt = $this->sqlValue("NOW()");
313             $this->deleted_by = $roo->getAuthUser()->id;
314         }
315         
316         if(!empty($q['_flag_undelete'])){
317             $this->deleted_dt = "";
318             $this->deleted_by = 0;
319         }
320         if(!empty($q['_check_name'])){
321             if($this->checkName()){
322                 $roo->jok('OK');
323             }
324             
325             $roo->jerr('EXIST');
326         }
327         
328         if(!empty($q['_merge_id'])){
329             $this->merge($q['_merge_id'], $roo);
330         }
331         
332         if(!empty($this->is_system) && 
333             ($old->code != $this->code  ) // used to be not allowed to change name..
334         ){
335             $roo->jerr('This company is not allow to editing Ref. or Company Name...');
336         }
337     }
338     
339     function beforeDelete($req, $roo)
340     {
341         
342         // should check for members....
343         if(!empty($this->is_system) && 
344             ($old->code != $this->code || $old->name != $this->name)
345         ){
346             $roo->jerr('This company is not allow to delete');
347         }
348         
349         
350     }
351     function onDelete($req, $roo)
352     {   
353         $img = DB_DataObject::factory('Images');
354         $img->ontable = $this->tableName();
355         $img->onid = $this->id;
356         $img->find();
357         while ($img->fetch()) {
358             $img->beforeDelete(array(), $roo);
359             $img->delete();
360         }
361         return true;
362         
363          
364     }
365     /**
366      * check who is trying to access this. false == access denied..
367      */
368     function checkPerm($lvl, $au, $changes = false) 
369     {
370         
371         // do we have an empty system..
372         if ($au && $au->id == -1) {
373             return true;
374         }
375         
376         
377         
378         if ($au->company()->comptype != 'OWNER') {
379             
380             // hacking!
381             if ($changes && isset($changes['comptype']) && $changes['comptype'] != $this->comptype) {
382                 return false;
383             }
384             
385             return $this->id == $au->company_id;
386         }
387         
388         return $au->hasPerm("Core.Companies", $lvl);    
389     }
390     
391     function logoImageToHTML($size)
392     {
393         $i = DB_DataObject::factory('Images');
394         if (!$this->logo_id || !$i->get($this->logo_id)) {
395             return '';
396         }
397         return $i->toHTML($size);
398         
399     }
400      function firstImage($filter='image/%')
401     {
402         $i = DB_DataObject::factory('Images');
403         //DB_DataObject::debugLevel(1);
404         $im = $i->gather($this, $filter);
405         if (empty($im)) {
406             return false;
407         }
408         return $im[0];
409     }
410     
411     function firstImageTag($size =-1, $base="/Images/Thumb", $filter='image/%')
412     {
413         $fm = $this->firstImage($filter);
414          if (empty($fm)) {
415             return '';
416         }
417         return $fm->toHTML($size, $base);
418     }
419     
420     function toRooSingleArray($authUser, $request)
421     {
422         $ret = $this->toArray();
423        // DB_DataObject::debugLevel(1);
424         // get the comptype display
425         $e = DB_DataObject::Factory('core_enum')->lookupObject('COMPTYPE', $this->comptype);
426         
427         $ret['comptype_display'] = $ret['comptype'];
428         if ($e   && !empty($e->name_display)) {
429             $ret['comptype_display'] = $e->name_display;
430         }
431         
432         
433         return $ret;
434     }
435     
436     /**
437      * # 2028 
438      * create the suppliers...
439      * 
440      * @param object $roo
441      * @param array $data
442      * 
443      */
444     function initCompaniesArray($roo, $data)
445     {
446         $tn = $this->tableName();
447         
448         foreach($data as $d){
449             $com = DB_DataObject::factory($tn);
450             $com->setFrom($d);
451             if(!$com->find(true)){
452                 $com->created_dt = Date('Y-m-d H:i:s');
453                 $com->updated_dt = Date('Y-m-d H:i:s');
454                 $com->is_system = 1;// new column.. block the user changing the code and name..
455                 $com->insert();
456             }
457         }
458         
459         
460     }
461     
462     
463     function initCompanies($roo, $opts)
464     {
465         $companies = DB_DataObject::factory('core_company');
466         
467         $ctype = empty($opts['add-company-with-type']) ? 'OWNER' : $opts['add-company-with-type'];
468         
469         $enum = DB_DataObject::Factory('core_enum')->lookup('COMPTYPE', $ctype  );
470         
471         if (empty($enum)) {
472             $roo->jerr("invalid company type '$ctype'");
473         }
474         if ($ctype =='OWNER') {
475             $companies = DB_DataObject::factory('core_company');
476             $companies->comptype_id = $enum;
477             if ($companies->count()) {
478                 $roo->jerr("Owner  company already exists");
479             }
480         }
481         $companies = DB_DataObject::factory('core_company');
482         
483         // check that 
484         $companies->setFrom(array(
485             'name' => $opts['add-company'],
486             'comptype' => $ctype,
487             'comptype_id' => $enum,
488         ));
489         if ($companies->find(true)) {
490             $roo->jerr("company already exists");
491         }
492         $companies->setFrom(array(
493             'background_color' => '',
494             'created_dt' => $this->sqlValue('NOW()'),
495             'updated_dt' => $this->sqlValue('NOW()')
496         ));
497         
498         
499         $companies->insert();
500         $companies->onInsert(array(), $roo);
501     }
502     static function lookupOwner()
503     {
504         static $cache = false;
505         if ($cache !== false) {
506             return clone($cache); // no updating this object..
507         }
508         
509         $enum = DB_DataObject::Factory('core_enum')->lookup('COMPTYPE', 'OWNER'  );
510         $companies = DB_DataObject::factory('core_company');
511         $companies->comptype_id = $enum;
512         if ($companies->find(true)) {
513             $cache = clone($companies);
514             return $companies;
515         }
516         return false;
517     }
518     
519     function merge($merge_to, $roo)
520     {
521         $affects  = array();
522         
523         $all_links = $this->databaseLinks();
524         
525         foreach($all_links as $tbl => $links) {
526             foreach($links as $col => $totbl_col) {
527                 $to = explode(':', $totbl_col);
528                 if ($to[0] != $this->tableName()) {
529                     continue;
530                 }
531                 
532                 $affects[$tbl .'.' . $col] = true;
533             }
534         }
535         
536         foreach($affects as $k => $true) {
537             $ka = explode('.', $k);
538
539             $chk = DB_DataObject::factory($ka[0]);
540             
541             if (!is_a($chk,'DB_DataObject')) {
542                 $roo->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
543             }
544             
545             $chk->{$ka[1]} = $this->id;
546
547             foreach ($chk->fetchAll() as $c){
548                 $cc = clone ($c);
549                 $c->{$ka[1]} = $merge_to;
550                 $c->update($cc);
551             }
552         }
553         
554         $this->delete();
555         
556         $roo->jok('Merged');
557         
558     }
559     
560     function checkName()
561     {
562         $company = DB_DataObject::factory('core_company');
563         $company->setFrom(array(
564             'name' => $this->name
565         ));
566         
567         if(!empty($this->id)){
568             $company->whereAdd("id != {$this->id}");
569         }
570         
571         if(!$company->find(true)){
572             return true;
573         }
574         
575         return false;
576     }
577 }