3 * Table Definition for Images
5 class_exists('DB_DataObject') ? '' : require_once 'DB/DataObject.php';
7 class Pman_Core_DataObjects_Images extends DB_DataObject
10 /* the code below is auto generated do not remove the above tag */
12 public $__table = 'Images'; // table name
13 public $id; // int(11) not_null primary_key auto_increment
14 public $filename; // string(255) not_null
15 public $ontable; // string(32) not_null multiple_key
16 public $onid; // int(11) not_null
17 public $mimetype; // string(64) not_null
18 public $width; // int(11) not_null
19 public $height; // int(11) not_null
20 public $filesize; // int(11) not_null
21 public $displayorder; // int(11) not_null
22 public $language; // string(6) not_null
23 public $parent_image_id; // int(11) not_null
24 public $created; // datetime(19) not_null binary
25 public $imgtype; // string(32) not_null
26 public $linkurl; // string(254) not_null
27 public $descript; // blob(65535) not_null blob
28 public $title; // string(128) not_null
30 /* the code above is auto generated do not remove the tag below */
33 function checkPerm($lvl, $au)
35 // default permissons are to
36 // allow create / edit / if the user has
44 if (method_exists($o, 'checkPerm')) {
45 // edit permissions on related object needed...
46 return $o->checkPerm( $lvl == 'S' ? 'S' : 'E' , $au);
50 return true; //// ??? not really that safe...
54 function beforeInsert($q, $roo)
56 if (isset($q['_remote_upload'])) {
57 require_once 'System.php';
59 $tmpdir = System::mktemp("-d remote_upload");
61 $path = $tmpdir . '/' . basename($q['_remote_upload']);
63 if(!file_exists($path)){
64 file_put_contents($path, file_get_contents($q['_remote_upload']));
67 $imageInfo = getimagesize($path);
69 require_once 'File/MimeType.php';
70 $y = new File_MimeType();
71 $ext = $y->toExt(trim((string) $imageInfo['mime'] ));
73 if (!preg_match("/\." . $ext."$/", $path, $matches)) {
74 rename($path,$path.".".$ext);
78 if (!$this->createFrom($path)) {
79 $roo->jerr("erro making image" . $q['_remote_upload']);
82 if(!empty($q['_return_after_create'])){
86 $roo->addEvent("ADD", $this, $this->toEventString());
88 $r = DB_DataObject::factory($this->tableName());
93 $roo->jok($r->URL(-1,'/Images') . '#attachment-'. $r->id);
100 * create an email from file.
101 * these must have been set first.
105 function createFrom($file, $filename=false)
107 // copy the file into the storage area..
108 if (!file_exists($file) || !filesize($file)) {
109 $this->err = "File $file did not exist or is 0 size";
113 $filename = empty($filename) ? $file : $filename;
115 if (empty($this->mimetype)) {
116 require_once 'File/MimeType.php';
117 $y = new File_MimeType();
118 $this->mimetype = $y->fromFilename($filename);
121 $this->mimetype= strtolower($this->mimetype);
123 if (array_shift(explode('/', $this->mimetype)) == 'image') {
125 $imgs = @getimagesize($file);
127 if (empty($imgs) || empty($imgs[0]) || empty($imgs[1])) {
130 list($this->width , $this->height) = $imgs;
134 if($this->mimetype == 'application/pdf'){
135 require_once 'System.php';
137 $this->no_of_pages = 0;
139 $pdfinfo = System::which('pdfinfo');
141 if (!empty($pdfinfo)) {
143 $cmd = "{$pdfinfo} {$file}";
147 $info = explode("\n", $ret);
149 foreach ($info as $i){
151 if(!preg_match('/^Pages:[\s]?([0-9]+)/', $i, $matches)){
154 print_R($matches);exit;
155 $ret = (empty($matches[1])) ? false : $matches[1];
162 $this->filesize = filesize($file);
163 $this->created = date('Y-m-d H:i:s');
166 if (empty($this->filename)) {
167 $this->filename = basename($filename);
170 //DB_DataObject::debugLevel(1);
179 $f = $this->getStoreName();
181 if (!file_exists($dest)) {
182 // currently this is 0775 due to problems using shared hosing (FTP)
183 // it makes all the files unaccessable..
184 // you can normally solve this by giving the storedirectory better perms
185 // if needed on a dedicated server..
186 $oldumask = umask(0);
187 mkdir($dest, 0775, true);
198 // $this->createThumbnail(0,50);
204 * Calculate target file name
206 * @return - target file name
208 function getStoreName()
210 $opts = HTML_FlexyFramework::get()->Pman;
211 $fn = preg_replace('/[^a-z0-9\.]+/i', '_', $this->filename);
212 return implode( '/', array(
213 $opts['storedir'], '_images_', date('Y/m', strtotime($this->created)), $this->id . '-'. $fn
219 * deletes all the image instances of it...
223 function beforeDelete()
225 $fn = $this->getStoreName();
226 if (file_exists($fn)) {
232 if (file_exists($d)) {
235 while (false !== ($fn = readdir($dh))) {
236 if (substr($fn, 0, strlen($b)) == $b) {
237 unlink($d. '/'. $fn);
244 * check mimetype against type
245 * - eg. img.is(#image#)
250 if (empty($this->mimetype)) {
253 return 0 === strcasecmp($type, array_shift(explode('/',$this->mimetype)));
257 * onUpload (singlely attached image to a table)
260 function onUploadWithTbl($tbl, $fld)
262 if ( $tbl->__table == 'Images') {
263 return; // not upload to self...
265 if (empty($_FILES['imageUpload']['tmp_name']) ||
266 empty($_FILES['imageUpload']['name']) ||
267 empty($_FILES['imageUpload']['type'])
272 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
274 $image = DB_DataObject::factory('Images');
275 $image->get($tbl->$fld);
276 $image->beforeDelete();
280 $image = DB_DataObject::factory('Images');
281 $image->onid = $tbl->id;
282 $image->ontable = $tbl->__table;
283 $image->filename = $_FILES['imageUpload']['name'];
284 $image->mimetype = $_FILES['imageUpload']['type'];
286 if (!$image->createFrom($_FILES['imageUpload']['tmp_name'])) {
290 $tbl->$fld = $image->id;
297 function onUpload($roo)
299 //print_r($_FILES); echo $_FILES['imageUpload']['type'];exit;
300 if (empty($_FILES['imageUpload']['tmp_name']) ||
301 empty($_FILES['imageUpload']['name']) ||
302 empty($_FILES['imageUpload']['type'])
306 0=>"There is no error, the file uploaded with success",
307 1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
308 2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form" ,
309 3=>"The uploaded file was only partially uploaded",
310 4=>"No file was uploaded",
311 6=>"Missing a temporary folder"
313 $estr = (empty($_FILES['imageUpload']['error']) ? '?': $emap[$_FILES['imageUpload']['error']]);
314 $this->err = "Missing file details : Error=". $estr;
319 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
321 $this->beforeDelete();
323 if ( empty($this->ontable)) {
324 $this->err = "Missing ontable";
328 if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
329 // then its an upload
330 $img = DB_DataObject::factory('Images');
331 $img->onid = $this->onid;
332 $img->ontable = $this->ontable;
333 $img->imgtype = $this->imgtype;
336 while ($img->fetch()) {
337 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
339 $img->beforeDelete();
347 require_once 'File/MimeType.php';
348 $y = new File_MimeType();
349 $this->mimetype = $_FILES['imageUpload']['type'];
350 if (in_array($this->mimetype, array(
352 'application/octet-stream',
353 'image/x-png', // WTF does this?
354 'image/pjpeg', // WTF does this?
355 'application/x-apple-msg-attachment', /// apple doing it's magic...
356 'application/vnd.ms-excel', /// sometimes windows reports csv as excel???
357 'application/csv-tab-delimited-table', // windows again!!?
358 ))) { // weird tyeps..
359 $inf = pathinfo($_FILES['imageUpload']['name']);
360 $this->mimetype = $y->fromExt($inf['extension']);
364 $ext = $y->toExt(trim((string) $this->mimetype ));
366 $this->filename = empty($this->filename) ?
367 $_FILES['imageUpload']['name'] : ($this->filename .'.'. $ext);
371 if (!$this->createFrom($_FILES['imageUpload']['tmp_name'])) {
372 $this->err = isset($this->err) ? $this->err : "createFrom Image failed";
382 * return a list of images for an object, optionally with a mime regex.
383 * eg. '%/pdf' or 'image/%'
387 * $i = DB_DataObject::factory('Images');
388 * $i->imgtype = 'LOGO';
389 * $ar = $i->gather($somedataobject, 'image/%');
391 * @param {DB_DataObject} dataobject = the object to gather data on.
392 * @param {String} mimelike LIKE query to use for search
395 function gather($obj, $mime_like='', $opts=array())
397 //DB_DataObject::debugLevel(1);
398 if (empty($obj->id)) {
403 $c->whereAddIn($this->tableName() . '.ontable', array( $obj->tableName(), $obj->__table) , 'string');
406 if (!empty($mime_like)) {
407 $c->whereAdd("Images.mimetype LIKE '". $c->escape($mime_like) ."'");
409 $c->orderBy('created DESC');
411 return $c->fetchAll();
416 * set or get the dataobject this image is associated with
417 * @param DB_DataObject $obj An object to associate this image with
418 * (does not store it - you need to call update() to do that)
419 * @return DB_DataObject the dataobject this image is attached to.
421 function object($obj=false)
423 if ($obj === false) {
424 if (empty($this->ontable) || empty($this->onid)) {
427 $ret = DB_DataObject::factory($this->ontable);
428 $ret->get($this->onid);
433 $this->ontable = $obj->tableName();
434 $this->onid = $obj->id; /// assumes our nice standard of using ids..
439 function toRooArray($req) {
441 $ret= $this->toArray();
445 $ff = HTML_FlexyFramework::get();
448 $ret['public_baseURL'] = isset($ff->Pman_Images['public_baseURL']) ?
449 $ff->Pman_Images['public_baseURL'] : $ff->baseURL;
451 if (!empty($req['query']['imagesize'])) {
452 // query/imageBaseURL ... depricated...? -- set it in config?
454 $baseURL = isset($req['query']['imageBaseURL']) ? $req['query']['imageBaseURL'] : $ret['public_baseURL'];
456 $ret['url'] = $this->URL(-1, '/Images/Download',$baseURL);
458 $ret['url_view'] = $this->URL(-1, '/Images',$baseURL);
460 if (!empty($req['query']['imagesize'])) {
461 $ret['url_thumb'] = $this->URL($req['query']['imagesize'], '/Images/Thumb',$baseURL);
471 * URL - create a url for the image.
472 * size - use -1 to show full size.
473 * provier = baseURL + /Images/Thumb ... use '/Images/' for full
477 function URL($size , $provider = '/Images/Thumb', $baseURL=false)
480 return 'about:blank';
484 $ff = HTML_FlexyFramework::get();
485 $baseURL = $baseURL ? $baseURL : $ff->baseURL ;
486 if (preg_match('#^http[s]*://#', $provider)) {
491 $provider = preg_replace('#/Thumb$#', '', $provider);
493 return $baseURL . $provider . "/{$this->id}/{$this->filename}";
496 //$size = max(100, (int) $size);
497 //$size = min(1024, (int) $size);
498 // the size should 200x150 to convert
499 $sizear = preg_split('/(x|c)/', $size);
500 if(empty($sizear[1])){
503 $size = implode(strpos($size,'c') > -1 ? 'c' : 'x', $sizear);
505 $fc = $this->toFileConvert();
508 $mt = $this->mimetype;
509 if (!preg_match('#^image/#i',$mt)) {
513 $fc->convert($mt, $size);
515 return $baseURL . $provider . "/$size/{$this->id}/{$this->filename}";
518 * size could be 123x345
522 function toHTML($size, $provider = '/Images/Thumb')
527 $sz = explode('x', $size);
530 if (!$this->id || empty($this->width)) {
532 $this->width = empty($sz[1]) ? $sx : $sz[1];
536 $ratio = empty($this->width) ? 1 : $this->height/ ($this->width *1.0);
543 if (strlen($this->title)) {
544 $extra = ' title="'. htmlspecialchars($this->title) . '"';
547 return '<img src="' . $this->URL($size, $provider) . '"' .
549 ' width="'. $sx . '"' .
550 ' height="'. $sy . '">';
557 * #2142 [new] CMS - image link urls
562 function toLinkHTML($size, $provider = '/Images/Thumb')
564 if(empty($this->linkurl)){
565 return $this->toHTML($size, $provider = '/Images/Thumb');
568 return '<a href="'.$this->linkurl.'" target="_blank">'.$this->toHTML($size, $provider = '/Images/Thumb').'</a>';
574 * to Fileconvert object..
579 function toFileConvert()
581 require_once 'File/Convert.php';
582 $fc = new File_Convert($this->getStoreName(), $this->mimetype);
589 require_once 'File/MimeType.php';
591 $y = new File_MimeType();
592 return $y->toExt($this->mimetype);
604 function setFromRoo($ar, $roo)
606 // not sure why we do this..
608 // if imgtype starts with '-' ? then we set the 'old' (probably to delete later)
609 if (!empty($ar['imgtype']) && !empty($ar['ontable']) && !empty($ar['onid']) && ($ar['imgtype'][0] == '-')) {
612 if ($this->find(true)) {
613 $roo->old = clone($this);
618 if (!empty($ar['_copy_from'])) {
620 if (!$this->checkPerm( 'A' , $roo->authUser)) {
621 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
624 $copy = DB_DataObject::factory('Images');
625 $copy->get($ar['_copy_from']);
626 $this->setFrom($copy->toArray());
628 $this->createFrom($copy->getStoreName());
630 $roo->addEvent("ADD", $this, $this->toEventString());
632 $r = DB_DataObject::factory($this->tableName());
637 $roo->jok($r->toArray());
644 // FIXME - we should be checking perms here...
646 // this should be doign update
649 if (!$this->checkPerm($this->id ? 'A' : 'E', $roo->authUser)) {
650 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
655 if (!isset($_FILES['imageUpload'])) {
656 return; // standard update...
660 // print_r(!$this->onUpload($this));
662 if ( !$this->onUpload($this)) {
663 $roo->jerr("File upload failed : error = ". (!empty($this->err) ? $this->err : ''));
666 $this->addEvent($ar, $roo);
668 $r = DB_DataObject::factory($this->tableName());
673 $roo->jok($r->toArray());
677 function addEvent($ar, $roo)
679 $roo->addEvent("ADD", $this, $this->toEventString());
682 function toEventString()
685 //$p = DB_DataObject::factory($this->ontable);
687 // return "ERROR unknown table? {$this->ontable}";
691 return $this->filename .' - on ' . $this->ontable . ':' . $this->onid;
692 //$p->toEventString();
695 function onUploadFromData($data, $roo)
698 $this->err = "Missing file details";
703 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
705 $this->beforeDelete();
708 if (empty($this->ontable)) {
709 $this->err = "Missing ontable";
713 if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
714 // then its an upload
715 $img = DB_DataObject::factory('Images');
716 $img->onid = $this->onid;
717 $img->ontable = $this->ontable;
718 $img->imgtype = $this->imgtype;
721 while ($img->fetch()) {
722 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
724 $img->beforeDelete();
730 require_once 'File/MimeType.php';
731 $y = new File_MimeType();
733 if (in_array($this->mimetype, array(
735 'application/octet-stream',
736 'image/x-png', // WTF does this?
737 'image/pjpeg', // WTF does this?
738 'application/x-apple-msg-attachment', /// apple doing it's magic...
739 'application/vnd.ms-excel', /// sometimes windows reports csv as excel???
740 'application/csv-tab-delimited-table', // windows again!!?
741 ))) { // weird tyeps..
742 $inf = pathinfo($this->filename);
743 $this->mimetype = $y->fromExt($inf['extension']);
746 $ext = $y->toExt(trim((string) $this->mimetype ));
748 if(array_pop(explode('.', $this->filename)) != $ext){
749 $this->filename = $this->filename .'.'. $ext;
752 if (!$this->createFromData($data)) {
760 function createFromData($data)
763 $this->mimetype= strtolower($this->mimetype);
765 if (array_shift(explode('/', $this->mimetype)) == 'image') {
767 $imgs = @getimagesize($data);
769 if (!empty($imgs) && !empty($imgs[0]) && !empty($imgs[1])) {
770 list($this->width , $this->height) = $imgs;
774 $this->created = date('Y-m-d H:i:s');
782 $f = $this->getStoreName();
784 if (!file_exists($dest)) {
785 $oldumask = umask(0);
786 mkdir($dest, 0775, true);
790 file_put_contents($f, file_get_contents("data://" . $data));
794 $this->filesize = filesize($f);
804 if(!preg_match('/^image\//', $this->mimetype)){
808 $file = $this->getStoreName();
810 if(!file_exists($file)){
814 $data = file_get_contents($file);
816 $base64 = 'data:' . $this->mimetype . ';base64,' . base64_encode($data);