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 */
32 function applyFilters($q, $au, $roo)
34 $tn = $this->tableName();
36 if(!empty($q['search']['filename'])){
38 $tn.filename LIKE '%{$this->escape($q['search']['filename'])}%' OR $tn.title LIKE '%{$this->escape($q['search']['filename'])}%'
45 function checkPerm($lvl, $au)
47 // default permissons are to
48 // allow create / edit / if the user has
56 if (method_exists($o, 'checkPerm')) {
57 // edit permissions on related object needed...
58 return $o->checkPerm( $lvl == 'S' ? 'S' : 'E' , $au);
62 return true; //// ??? not really that safe...
66 function beforeInsert($q, $roo)
68 if (isset($q['_remote_upload'])) {
69 require_once 'System.php';
71 $tmpdir = System::mktemp("-d remote_upload");
73 $path = $tmpdir . '/' . basename($q['_remote_upload']);
75 if(!file_exists($path)){
76 file_put_contents($path, file_get_contents($q['_remote_upload']));
79 $imageInfo = getimagesize($path);
81 require_once 'File/MimeType.php';
82 $y = new File_MimeType();
83 $ext = $y->toExt(trim((string) $imageInfo['mime'] ));
85 if (!preg_match("/\." . $ext."$/", $path, $matches)) {
86 rename($path,$path.".".$ext);
90 if (!$this->createFrom($path)) {
91 $roo->jerr("erro making image" . $q['_remote_upload']);
94 if(!empty($q['_return_after_create'])){
98 $roo->addEvent("ADD", $this, $this->toEventString());
100 $r = DB_DataObject::factory($this->tableName());
105 $roo->jok($r->URL(-1,'/Images') . '#attachment-'. $r->id);
112 * create an email from file.
113 * these must have been set first.
117 function createFrom($file, $filename=false)
119 // copy the file into the storage area..
120 if (!file_exists($file) || !filesize($file)) {
121 $this->err = "File $file did not exist or is 0 size";
125 $filename = empty($filename) ? $file : $filename;
127 if (empty($this->mimetype)) {
128 require_once 'File/MimeType.php';
129 $y = new File_MimeType();
130 $this->mimetype = $y->fromFilename($filename);
133 $this->mimetype = strtolower($this->mimetype);
135 $mta = explode('/', $this->mimetype);
136 if (array_shift($mta) == 'image') {
138 $imgs = @getimagesize($file);
140 if (empty($imgs) || empty($imgs[0]) || empty($imgs[1])) {
143 list($this->width , $this->height) = $imgs;
147 if($this->mimetype == 'application/pdf'){
148 $this->no_of_pages = $this->getPdfPages($file);
151 $this->filesize = filesize($file);
152 $this->created = date('Y-m-d H:i:s');
155 if (empty($this->filename)) {
156 $this->filename = basename($filename);
159 //DB_DataObject::debugLevel(1);
168 $f = $this->getStoreName();
170 if (!file_exists($dest)) {
171 // currently this is 0775 due to problems using shared hosing (FTP)
172 // it makes all the files unaccessable..
173 // you can normally solve this by giving the storedirectory better perms
174 // if needed on a dedicated server..
175 $oldumask = umask(0);
176 mkdir($dest, 0775, true);
187 // $this->createThumbnail(0,50);
193 * Calculate target file name
195 * @return - target file name
197 function getStoreName()
199 $opts = HTML_FlexyFramework::get()->Pman;
200 $fn = preg_replace('/[^a-z0-9\.]+/i', '_', $this->filename);
201 return implode( '/', array(
202 $opts['storedir'], '_images_', date('Y/m', strtotime($this->created)), $this->id . '-'. $fn
208 * deletes all the image instances of it...
212 function beforeDelete($dependants_array, $roo)
215 $opts = HTML_FlexyFramework::get()->Pman;
216 $deldir = $opts['storedir']. '/_deleted_images_';
217 if (!file_exists( $deldir )) {
218 mkdir($deldir, 0755);
221 $fn = $this->getStoreName();
223 if (file_exists($fn)) {
225 if (file_exists($deldir . '/'. $b)) {
228 rename($fn, $deldir .'/'. $b);
236 if (file_exists($d)) {
239 while (false !== ($fn = readdir($dh))) {
240 if (substr($fn, 0, strlen($b)) == $b) {
242 if (file_exists($deldir . '/'. $fn)) {
243 unlink($d. '/'. $fn);
246 rename($d. '/'. $fn, $deldir .'/'. $fn);
254 * check mimetype against type
255 * - eg. img.is(#image#)
260 if (empty($this->mimetype)) {
263 return 0 === strcasecmp($type, array_shift(explode('/',$this->mimetype)));
267 * onUpload (singlely attached image to a table)
270 function onUploadWithTbl($tbl, $fld)
272 if ( $tbl->__table == 'Images') {
273 return; // not upload to self...
275 if (empty($_FILES['imageUpload']['tmp_name']) ||
276 empty($_FILES['imageUpload']['name']) ||
277 empty($_FILES['imageUpload']['type'])
282 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
284 $image = DB_DataObject::factory('Images');
285 $image->get($tbl->$fld);
286 $image->beforeDelete();
290 $image = DB_DataObject::factory('Images');
291 $image->onid = $tbl->id;
292 $image->ontable = $tbl->__table;
293 $image->filename = $_FILES['imageUpload']['name'];
294 $image->mimetype = $_FILES['imageUpload']['type'];
296 if (!$image->createFrom($_FILES['imageUpload']['tmp_name'])) {
300 $tbl->$fld = $image->id;
307 function onUpload($roo)
309 //print_r($_FILES); echo $_FILES['imageUpload']['type'];exit;
310 if (empty($_FILES['imageUpload']['tmp_name']) ||
311 empty($_FILES['imageUpload']['name']) ||
312 empty($_FILES['imageUpload']['type'])
316 0=>"There is no error, the file uploaded with success",
317 1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
318 2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form" ,
319 3=>"The uploaded file was only partially uploaded",
320 4=>"No file was uploaded",
321 6=>"Missing a temporary folder"
323 $estr = (empty($_FILES['imageUpload']['error']) ? '?': $emap[$_FILES['imageUpload']['error']]);
324 $this->err = "Missing file details : Error=". $estr;
329 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
331 $this->beforeDelete();
333 if ( empty($this->ontable)) {
334 $this->err = "Missing ontable";
338 if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
339 // then its an upload
340 $img = DB_DataObject::factory('Images');
341 $img->onid = $this->onid;
342 $img->ontable = $this->ontable;
343 $img->imgtype = $this->imgtype;
346 while ($img->fetch()) {
347 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
349 $img->beforeDelete();
357 require_once 'File/MimeType.php';
358 $y = new File_MimeType();
359 $this->mimetype = $_FILES['imageUpload']['type'];
360 if (in_array($this->mimetype, array(
362 'application/octet-stream',
363 'image/x-png', // WTF does this?
364 'image/pjpeg', // WTF does this?
365 'application/x-apple-msg-attachment', /// apple doing it's magic...
366 'application/vnd.ms-excel', /// sometimes windows reports csv as excel???
367 'application/csv-tab-delimited-table', // windows again!!?
368 ))) { // weird tyeps..
369 $inf = pathinfo($_FILES['imageUpload']['name']);
370 $this->mimetype = $y->fromExt($inf['extension']);
374 $ext = $y->toExt(trim((string) $this->mimetype ));
376 $this->filename = empty($this->filename) ?
377 $_FILES['imageUpload']['name'] : ($this->filename .'.'. $ext);
381 if (!$this->createFrom($_FILES['imageUpload']['tmp_name'])) {
382 $this->err = isset($this->err) ? $this->err : "createFrom Image failed";
392 * return a list of images for an object, optionally with a mime regex.
393 * eg. '%/pdf' or 'image/%'
397 * $i = DB_DataObject::factory('Images');
398 * $i->imgtype = 'LOGO';
399 * $ar = $i->gather($somedataobject, 'image/%');
401 * @param {DB_DataObject} dataobject = the object to gather data on.
402 * @param {String} mimelike LIKE query to use for search
405 function gather($obj, $mime_like='', $opts=array())
407 //DB_DataObject::debugLevel(1);
408 if (empty($obj->id)) {
413 $c->whereAddIn($this->tableName() . '.ontable', array( $obj->tableName(), $obj->__table) , 'string');
416 if (!empty($mime_like)) {
417 $c->whereAdd("Images.mimetype LIKE '". $c->escape($mime_like) ."'");
419 $c->orderBy('created DESC');
421 return $c->fetchAll();
426 * set or get the dataobject this image is associated with
427 * @param DB_DataObject $obj An object to associate this image with
428 * (does not store it - you need to call update() to do that)
429 * @return DB_DataObject the dataobject this image is attached to.
431 function object($obj=false)
433 if ($obj === false) {
434 if (empty($this->ontable) || empty($this->onid)) {
437 $ret = DB_DataObject::factory($this->ontable);
438 $ret->get($this->onid);
443 $this->ontable = $obj->tableName();
444 $this->onid = $obj->id; /// assumes our nice standard of using ids..
449 function toRooArray($req)
452 $ret= $this->toArray();
455 $ff = HTML_FlexyFramework::get();
458 $ret['public_baseURL'] = isset($ff->Pman_Images['public_baseURL']) ?
459 $ff->Pman_Images['public_baseURL'] : $ff->baseURL;
461 if (!empty($req['query']['imagesize'])) {
462 // query/imageBaseURL ... depricated...? -- set it in config?
464 $baseURL = isset($req['query']['imageBaseURL']) ? $req['query']['imageBaseURL'] : $ret['public_baseURL'];
466 $ret['url'] = $this->URL(-1, '/Images/Download',$baseURL);
468 $ret['url_view'] = $this->URL(-1, '/Images',$baseURL);
470 if (!empty($req['query']['imagesize'])) {
471 $ret['url_thumb'] = $this->URL($req['query']['imagesize'], '/Images/Thumb',$baseURL);
476 $ret['shorten_name'] = $ret['filename'] = $this->shorten_name();
482 * URL - create a url for the image.
483 * size - use -1 to show full size.
484 * provier = baseURL + /Images/Thumb ... use '/Images/' for full
488 function URL($size , $provider = '/Images/Thumb', $baseURL=false)
491 return 'about:blank';
494 $shorten_name = $this->shorten_name();
496 $ff = HTML_FlexyFramework::get();
497 $baseURL = $baseURL ? $baseURL : $ff->baseURL ;
498 if (preg_match('#^http[s]*://#', $provider)) {
503 $provider = preg_replace('#/Thumb$#', '', $provider);
505 return $baseURL . $provider . "/{$this->id}/{$shorten_name}"; // -- this breaks the rss feed #image-{$this->id}";
508 //$size = max(100, (int) $size);
509 //$size = min(1024, (int) $size);
510 // the size should 200x150 to convert
511 $sizear = preg_split('/(x|c)/', $size);
512 if(empty($sizear[1])){
515 $size = implode(strpos($size,'c') > -1 ? 'c' : 'x', $sizear);
517 $fc = $this->toFileConvert();
520 $mt = $this->mimetype;
521 if (!preg_match('#^image/#i',$mt)) {
525 $fc->convert($mt, $size);
527 return $baseURL . $provider . "/$size/{$this->id}/{$shorten_name}"; // -- this breaks the rss feed #image-{$this->id}";
530 function getFromHashURL($url)
533 if (preg_match('/#image-([0-9]+)$/', $url, $matches)) {
535 } else if (preg_match('#Images/Thumb/[^/]+/([0-9]+)/#', $url, $matches)) {
537 } else if (preg_match('#Images/([0-9]+)/#', $url, $matches)) {
541 if ($id === false || $id < 1) {
545 $img = DB_DAtaObject::Factory('images');
546 if ($img->get($id)) {
553 function shorten_name()
555 if(empty($this->filename)) {
559 $filename = explode('.', $this->filename);
560 $ext = array_pop($filename);
561 $name = preg_replace("/[^A-Z0-9.]+/i", '-', implode('-', $filename)) ;
563 if(strlen($name) > 32) {
564 $name = substr($name, 0, 32);
567 $shorten_name = "{$name}.{$ext}";
569 return $shorten_name;
572 * size could be 123x345
576 function toHTML($size, $provider = '/Images/Thumb')
581 $sz = explode('x', $size);
584 if (!$this->id || empty($this->width)) {
586 $this->width = empty($sz[1]) ? $sx : $sz[1];
590 $ratio = empty($this->width) ? 1 : $this->height/ ($this->width *1.0);
597 if (strlen($this->title)) {
598 $extra = ' title="'. htmlspecialchars($this->title) . '"';
601 return '<img src="' . $this->URL($size, $provider) . '"' .
603 ' width="'. $sx . '"' .
604 ' height="'. $sy . '">';
611 * #2142 [new] CMS - image link urls
616 function toLinkHTML($size, $provider = '/Images/Thumb')
618 if(empty($this->linkurl)){
619 return $this->toHTML($size, $provider = '/Images/Thumb');
622 return '<a href="'.$this->linkurl.'" target="_blank">'.$this->toHTML($size, $provider = '/Images/Thumb').'</a>';
628 * to Fileconvert object..
633 function toFileConvert()
635 require_once 'File/Convert.php';
636 $fc = new File_Convert($this->getStoreName(), $this->mimetype);
643 require_once 'File/MimeType.php';
645 $y = new File_MimeType();
646 return $y->toExt($this->mimetype);
658 function setFromRoo($ar, $roo)
660 // not sure why we do this..
662 // if imgtype starts with '-' ? then we set the 'old' (probably to delete later)
663 if (!empty($ar['imgtype']) && !empty($ar['ontable']) && !empty($ar['onid']) && ($ar['imgtype'][0] == '-')) {
666 if ($this->find(true)) {
667 $roo->old = clone($this);
672 if (!empty($ar['_copy_from'])) {
674 if (!$this->checkPerm( 'A' , $roo->authUser)) {
675 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
678 $copy = DB_DataObject::factory('Images');
679 $copy->get($ar['_copy_from']);
680 $this->setFrom($copy->toArray());
682 $this->createFrom($copy->getStoreName());
684 $roo->addEvent("ADD", $this, $this->toEventString());
686 $r = DB_DataObject::factory($this->tableName());
691 $roo->jok($r->toArray());
698 // FIXME - we should be checking perms here...
700 // this should be doign update
703 if (!$this->checkPerm($this->id ? 'A' : 'E', $roo->authUser)) {
704 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
709 if (!isset($_FILES['imageUpload'])) {
710 return; // standard update...
714 // print_r(!$this->onUpload($this));
716 if ( !$this->onUpload($this)) {
717 $roo->jerr("File upload failed : error = ". (!empty($this->err) ? $this->err : ''));
720 $this->addEvent($ar, $roo);
722 $r = DB_DataObject::factory($this->tableName());
727 $roo->jok($r->toArray());
731 function addEvent($ar, $roo)
733 $roo->addEvent("ADD", $this, $this->toEventString());
736 function toEventString()
739 //$p = DB_DataObject::factory($this->ontable);
741 // return "ERROR unknown table? {$this->ontable}";
745 return $this->filename .' - on ' . $this->ontable . ':' . $this->onid;
746 //$p->toEventString();
749 function onUploadFromData($data, $roo)
752 $this->err = "Missing file details";
757 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
759 $this->beforeDelete();
762 if (empty($this->ontable)) {
763 $this->err = "Missing ontable";
767 if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
768 // then its an upload
769 $img = DB_DataObject::factory('Images');
770 $img->onid = $this->onid;
771 $img->ontable = $this->ontable;
772 $img->imgtype = $this->imgtype;
775 while ($img->fetch()) {
776 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
778 $img->beforeDelete();
784 require_once 'File/MimeType.php';
785 $y = new File_MimeType();
787 if (in_array($this->mimetype, array(
789 'application/octet-stream',
790 'image/x-png', // WTF does this?
791 'image/pjpeg', // WTF does this?
792 'application/x-apple-msg-attachment', /// apple doing it's magic...
793 'application/vnd.ms-excel', /// sometimes windows reports csv as excel???
794 'application/csv-tab-delimited-table', // windows again!!?
795 ))) { // weird tyeps..
796 $inf = pathinfo($this->filename);
797 $this->mimetype = $y->fromExt($inf['extension']);
800 $ext = $y->toExt(trim((string) $this->mimetype ));
802 $explode_filename = explode('.', $this->filename);
803 if(array_pop($explode_filename) != $ext){
804 $this->filename = $this->filename .'.'. $ext;
807 if (!$this->createFromData($data)) {
815 function createFromData($data)
818 $this->mimetype= strtolower($this->mimetype);
820 $explode_mimetype = explode('/', $this->mimetype);
822 if (array_shift($explode_mimetype) == 'image') {
824 $imgs = @getimagesize($data);
826 if (!empty($imgs) && !empty($imgs[0]) && !empty($imgs[1])) {
827 list($this->width , $this->height) = $imgs;
831 $this->created = date('Y-m-d H:i:s');
839 $f = $this->getStoreName();
841 if (!file_exists($dest)) {
842 $oldumask = umask(0);
843 mkdir($dest, 0775, true);
847 file_put_contents($f, file_get_contents("data://" . $data));
851 $this->filesize = filesize($f);
853 if($this->mimetype == 'application/pdf'){
854 $this->no_of_pages = $this->getPdfPages($f);
863 function toBase64($rotate = false, $scaleWidth = 0, $scaleHeight = 0)
865 if(!preg_match('/^image\//', $this->mimetype)){
869 $file = $this->getStoreName();
871 if(!file_exists($file)){
875 $data = file_get_contents($file);
877 if(!empty($scaleWidth) || !empty($scaleHeight)){
878 $data = $this->scale(false, $scaleWidth, $scaleHeight);
882 $data = $this->rotate($data);
885 $base64 = 'data:' . $this->mimetype . ';base64,' . base64_encode($data);
890 function getPdfPages($file)
892 require_once 'System.php';
896 $pdfinfo = System::which('pdfinfo');
898 if (!file_exists($file) || empty($pdfinfo)) {
902 $cmd = "{$pdfinfo} {$file}";
906 $info = explode("\n", $ret);
908 foreach ($info as $i){
910 if(!preg_match('/^Pages:[\s]*([0-9]+)/', $i, $matches)){
914 $page = (empty($matches[1])) ? 0 : $matches[1];
920 function rotate($imageBlob = false)
922 if(empty($imageBlob)){
923 $imagick = new Imagick($this->getStoreName());
925 $imagick = new Imagick();
926 $imagick->readImageBlob($imageBlob);
929 $orientation = $imagick->getImageOrientation();
931 switch($orientation) {
932 case Imagick::ORIENTATION_BOTTOMRIGHT:
933 $imagick->rotateimage(new ImagickPixel('#00000000'), 180); // rotate 180 degrees
936 case Imagick::ORIENTATION_RIGHTTOP:
937 $imagick->rotateimage(new ImagickPixel('#00000000'), 90); // rotate 90 degrees CW
940 case Imagick::ORIENTATION_LEFTBOTTOM:
941 $imagick->rotateimage(new ImagickPixel('#00000000'), -90); // rotate 90 degrees CCW
945 return $imagick->getImageBlob();
948 function scale($imageBlob = false, $width = 0, $height = 0)
950 if(empty($imageBlob)){
951 $imagick = new Imagick($this->getStoreName());
953 $imagick = new Imagick();
954 $imagick->readImageBlob($imageBlob);
957 $imagick->resizeimage($width, $height, Imagick::FILTER_LANCZOS, true, true);
959 return $imagick->getImageBlob();