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