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