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