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'])}%'
42 if(!empty($q['_to_base64']) && !empty($q['image_id'])) {
43 $i = DB_DataObject::factory("Images");
44 $i->get($q['image_id']);
45 $roo->jok($i->toBase64());
51 function checkPerm($lvl, $au)
53 // default permissons are to
54 // allow create / edit / if the user has
62 if ($o && method_exists($o, 'checkPerm')) {
63 // edit permissions on related object needed...
64 return $o->checkPerm( $lvl == 'S' ? 'S' : 'E' , $au);
68 return true; //// ??? not really that safe...
72 function beforeInsert($q, $roo)
74 if (isset($q['_remote_upload'])) {
75 require_once 'System.php';
77 $tmpdir = System::mktemp("-d remote_upload");
79 $path = $tmpdir . '/' . basename($q['_remote_upload']);
81 if(!file_exists($path)){
82 file_put_contents($path, file_get_contents($q['_remote_upload']));
85 $imageInfo = getimagesize($path);
87 require_once 'File/MimeType.php';
88 $y = new File_MimeType();
89 $ext = $y->toExt(trim((string) $imageInfo['mime'] ));
91 if (!preg_match("/\." . $ext."$/", $path, $matches)) {
92 rename($path,$path.".".$ext);
96 if (!$this->createFrom($path)) {
97 $roo->jerr("erro making image" . $q['_remote_upload']);
100 if(!empty($q['_return_after_create'])){
104 $roo->addEvent("ADD", $this, $this->toEventString());
106 $r = DB_DataObject::factory($this->tableName());
111 $roo->jok($r->URL(-1,'/Images') . '#attachment-'. $r->id);
118 * create an email from file.
119 * these must have been set first.
123 function createFrom($file, $filename=false)
125 // copy the file into the storage area..
126 if (!file_exists($file) || !filesize($file)) {
127 $this->err = "File $file did not exist or is 0 size";
131 $filename = empty($filename) ? $file : $filename;
133 if (empty($this->mimetype)) {
134 require_once 'File/MimeType.php';
135 $y = new File_MimeType();
136 $this->mimetype = $y->fromFilename($filename);
139 $this->mimetype = strtolower($this->mimetype);
141 $mta = explode('/', $this->mimetype);
142 if (array_shift($mta) == 'image') {
144 $imgs = @getimagesize($file);
146 if (empty($imgs) || empty($imgs[0]) || empty($imgs[1])) {
149 list($this->width , $this->height) = $imgs;
153 if($this->mimetype == 'application/pdf'){
154 $this->no_of_pages = $this->getPdfPages($file);
157 $this->filesize = filesize($file);
158 $this->created = date('Y-m-d H:i:s');
161 if (empty($this->filename)) {
162 $this->filename = basename($filename);
165 //DB_DataObject::debugLevel(1);
174 $f = $this->getStoreName();
176 if (!file_exists($dest)) {
177 // currently this is 0775 due to problems using shared hosing (FTP)
178 // it makes all the files unaccessable..
179 // you can normally solve this by giving the storedirectory better perms
180 // if needed on a dedicated server..
181 $oldumask = umask(0);
182 mkdir($dest, 0775, true);
193 // $this->createThumbnail(0,50);
199 * Calculate target file name
201 * @return - target file name
203 function getStoreName()
205 $opts = HTML_FlexyFramework::get()->Pman;
206 $fn = preg_replace('/[^a-z0-9\.]+/i', '_', $this->filename);
207 return implode( '/', array(
208 $opts['storedir'], '_images_', date('Y/m', strtotime($this->created)), $this->id . '-'. $fn
214 * does the files exist?
218 return file_exists($this->getStoreName());
223 * deletes all the image instances of it...
227 function beforeDelete($dependants_array, $roo)
230 if (!empty($dependants_array)) {
234 $opts = HTML_FlexyFramework::get()->Pman;
235 $deldir = $opts['storedir']. '/_deleted_images_';
237 if (!file_exists( $deldir )) {
238 @mkdir($deldir, 0755); // not sure why we are erroring here.. after checking - maybe permissions?
241 $fn = $this->getStoreName();
243 if (file_exists($fn)) {
245 if (file_exists($deldir . '/'. $b)) {
248 rename($fn, $deldir .'/'. $b);
256 if (file_exists($d)) {
259 while (false !== ($fn = readdir($dh))) {
260 if (substr($fn, 0, strlen($b)) == $b) {
262 if (file_exists($deldir . '/'. $fn)) {
263 unlink($d. '/'. $fn);
266 rename($d. '/'. $fn, $deldir .'/'. $fn);
274 * check mimetype against type
275 * - eg. img.is(#image#)
280 if (empty($this->mimetype)) {
283 return 0 === strcasecmp($type, array_shift(explode('/',$this->mimetype)));
287 * onUpload (singlely attached image to a table)
290 function onUploadWithTbl($tbl, $fld)
292 if ( $tbl->__table == 'Images') {
293 return; // not upload to self...
295 if (empty($_FILES['imageUpload']['tmp_name']) ||
296 empty($_FILES['imageUpload']['name']) ||
297 empty($_FILES['imageUpload']['type'])
302 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
304 $image = DB_DataObject::factory('Images');
305 $image->get($tbl->$fld);
306 $image->beforeDelete();
310 $image = DB_DataObject::factory('Images');
311 $image->onid = $tbl->id;
312 $image->ontable = $tbl->__table;
313 $image->filename = $_FILES['imageUpload']['name'];
314 $image->mimetype = $_FILES['imageUpload']['type'];
316 if (!$image->createFrom($_FILES['imageUpload']['tmp_name'])) {
320 $tbl->$fld = $image->id;
327 function onUpload($roo, $table = false, $file = false)
330 if ($table !== false) {
331 $this->ontable = $table->tableName();
332 $this->onid = $table->pid();
335 if ($file === false) {
336 $file = isset($_FILES['imageUpload']) ? $_FILES['imageUpload'] : array();
339 //print_r($_FILES); echo $_FILES['imageUpload']['type'];exit;
340 if (empty($file['tmp_name']) ||
341 empty($file['name']) ||
346 0=>"There is no error, the file uploaded with success",
347 1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
348 2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form" ,
349 3=>"The uploaded file was only partially uploaded",
350 4=>"No file was uploaded",
351 6=>"Missing a temporary folder"
353 $estr = (empty($file['error']) ? '?': $emap[$file['error']]);
354 $this->err = "Missing file details : Error=". $estr;
359 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
361 $this->beforeDelete();
363 if ( empty($this->ontable)) {
364 $this->err = "Missing ontable";
368 if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
369 // then its an upload
370 $img = DB_DataObject::factory('Images');
371 $img->onid = $this->onid;
372 $img->ontable = $this->ontable;
373 $img->imgtype = $this->imgtype;
376 while ($img->fetch()) {
377 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
379 $img->beforeDelete();
387 require_once 'File/MimeType.php';
388 $y = new File_MimeType();
389 $this->mimetype = $file['type'];
390 if (in_array($this->mimetype, array(
392 'application/octet-stream',
393 'image/x-png', // WTF does this?
394 'image/pjpeg', // WTF does this?
395 'application/x-apple-msg-attachment', /// apple doing it's magic...
396 'application/vnd.ms-excel', /// sometimes windows reports csv as excel???
397 'application/csv-tab-delimited-table', // windows again!!?
398 ))) { // weird tyeps..
399 $inf = pathinfo($file['name']);
400 $this->mimetype = $y->fromExt($inf['extension']);
404 $ext = $y->toExt(trim((string) $this->mimetype ));
406 $this->filename = empty($this->filename) ?
407 $file['name'] : ($this->filename .'.'. $ext);
411 if (!$this->createFrom($file['tmp_name'])) {
412 $this->err = isset($this->err) ? $this->err : "createFrom Image failed";
422 * return a list of images for an object, optionally with a mime regex.
423 * eg. '%/pdf' or 'image/%'
427 * $i = DB_DataObject::factory('Images');
428 * $i->imgtype = 'LOGO';
429 * $ar = $i->gather($somedataobject, 'image/%');
431 * @param {DB_DataObject} dataobject = the object to gather data on.
432 * @param {String} mimelike LIKE query to use for search
435 function gather($obj, $mime_like='', $opts=array())
437 //DB_DataObject::debugLevel(1);
438 if (empty($obj->id)) {
443 $c->whereAddIn($this->tableName() . '.ontable', array( $obj->tableName(), $obj->__table) , 'string');
446 if (!empty($mime_like)) {
447 $c->whereAdd("Images.mimetype LIKE '". $c->escape($mime_like) ."'");
449 $c->orderBy('created DESC');
451 return $c->fetchAll();
456 * set or get the dataobject this image is associated with
457 * @param DB_DataObject $obj An object to associate this image with
458 * (does not store it - you need to call update() to do that)
459 * @return DB_DataObject the dataobject this image is attached to.
461 function object($obj=false)
463 if ($obj === false) {
464 if (empty($this->ontable) || empty($this->onid)) {
467 $ret = DB_DataObject::factory($this->ontable);
468 $ret->get($this->onid);
473 $this->ontable = $obj->tableName();
474 $this->onid = $obj->id; /// assumes our nice standard of using ids..
479 function toRooArray($req)
482 $ret= $this->toArray();
485 $ff = HTML_FlexyFramework::get();
488 $ret['public_baseURL'] = isset($ff->Pman_Images['public_baseURL']) ?
489 $ff->Pman_Images['public_baseURL'] : $ff->baseURL;
491 if (!empty($req['query']['imagesize'])) {
492 // query/imageBaseURL ... depricated...? -- set it in config?
494 $baseURL = isset($req['query']['imageBaseURL']) ? $req['query']['imageBaseURL'] : $ret['public_baseURL'];
496 $ret['url'] = $this->URL(-1, '/Images/Download',$baseURL);
498 $ret['url_view'] = $this->URL(-1, '/Images',$baseURL);
500 if (!empty($req['query']['imagesize'])) {
501 $ret['url_thumb'] = $this->URL($req['query']['imagesize'], '/Images/Thumb',$baseURL);
506 $ret['shorten_name'] = $ret['filename'] = $this->shorten_name();
512 * URL - create a url for the image.
513 * size - use -1 to show full size.
514 * provier = baseURL + /Images/Thumb ... use '/Images/' for full
518 function URL($size , $provider = '/Images/Thumb', $baseURL=false)
521 return 'about:blank';
523 if (!$this->exists()) {
524 return 'about:missing';
527 $shorten_name = $this->shorten_name();
529 $ff = HTML_FlexyFramework::get();
530 $baseURL = $baseURL ? $baseURL : $ff->baseURL ;
531 if (preg_match('#^http[s]*://#', $provider)) {
536 $provider = preg_replace('#/Thumb$#', '', $provider);
538 return $baseURL . $provider . "/{$this->id}/{$shorten_name}"; // -- this breaks the rss feed #image-{$this->id}";
541 //$size = max(100, (int) $size);
542 //$size = min(1024, (int) $size);
543 // the size should 200x150 to convert
544 $sizear = preg_split('/(x|c)/', $size);
545 if(!isset($sizear[1])){
546 $sizear[1] = 0; // 0x with '0' is a box? why
549 $size = implode(strpos($size,'c') > -1 ? 'c' : 'x', $sizear);
551 $fc = $this->toFileConvert();
554 $mt = $this->mimetype;
555 if (!preg_match('#^image/#i',$mt)) {
559 $fc->convert($mt, $size);
561 return $baseURL . $provider . "/$size/{$this->id}/{$shorten_name}"; // -- this breaks the rss feed #image-{$this->id}";
564 function getFromHashURL($url)
567 if (preg_match('/#image-([0-9]+)$/', $url, $matches)) {
569 } else if (preg_match('#Images/Thumb/[^/]+/([0-9]+)/#', $url, $matches)) {
571 } else if (preg_match('#Images/([0-9]+)/#', $url, $matches)) {
575 if ($id === false || $id < 1) {
579 $img = DB_DAtaObject::Factory('images');
580 if ($img->get($id)) {
587 function shorten_name()
589 if(empty($this->filename)) {
593 $filename = explode('.', $this->filename);
594 $ext = array_pop($filename);
595 $name = preg_replace("/[^A-Z0-9.]+/i", '-', implode('-', $filename)) ;
597 if(strlen($name) > 32) {
598 $name = substr($name, 0, 32);
601 $shorten_name = "{$name}.{$ext}";
603 return $shorten_name;
606 * size could be 123x345
610 function toHTML($size, $provider = '/Images/Thumb', $extra = '')
615 $sz = explode('x', $size);
618 if (!$this->id || empty($this->width)) {
620 $this->width = empty($sz[1]) ? $sx : $sz[1];
624 $ratio = empty($this->width) ? 1 : $this->height/ ($this->width *1.0);
625 $sy = intval($ratio * $sx);
631 if (strlen($this->title)) {
632 $extra = ' title="'. htmlspecialchars($this->title) . '"';
635 return '<img src="' . $this->URL($size, $provider) . '"' .
637 ' width="'. $sx . '"' .
638 ' height="'. $sy . '">';
645 * #2142 [new] CMS - image link urls
650 function toLinkHTML($size, $provider = '/Images/Thumb')
652 if(empty($this->linkurl)){
653 return $this->toHTML($size, $provider = '/Images/Thumb');
656 return '<a href="'.$this->linkurl.'" target="_blank">'.$this->toHTML($size, $provider = '/Images/Thumb').'</a>';
662 * to Fileconvert object..
667 function toFileConvert()
669 require_once 'File/Convert.php';
670 $fc = new File_Convert($this->getStoreName(), $this->mimetype);
677 require_once 'File/MimeType.php';
679 $y = new File_MimeType();
680 return $y->toExt($this->mimetype);
692 function setFromRoo($ar, $roo)
694 // not sure why we do this..
696 // if imgtype starts with '-' ? then we set the 'old' (probably to delete later)
697 if (!empty($ar['imgtype']) && !empty($ar['ontable']) && !empty($ar['onid']) && ($ar['imgtype'][0] == '-')) {
700 if ($this->find(true)) {
701 $roo->old = clone($this);
706 if (!empty($ar['_copy_from'])) {
708 if (!$this->checkPerm( 'A' , $roo->authUser)) {
709 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
712 $copy = DB_DataObject::factory('Images');
713 $copy->get($ar['_copy_from']);
714 $this->setFrom($copy->toArray());
716 $this->createFrom($copy->getStoreName());
718 $roo->addEvent("ADD", $this, $this->toEventString());
720 $r = DB_DataObject::factory($this->tableName());
726 $roo->jok($r->toRooArray($ar));
733 // FIXME - we should be checking perms here...
735 // this should be doign update
738 if (!$this->checkPerm($this->id ? 'A' : 'E', $roo->authUser)) {
739 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
743 if (!isset($_FILES['imageUpload'])) {
744 return; // standard update...
748 // print_r(!$this->onUpload($this));
750 if ( !$this->onUpload($this)) {
751 $roo->jerr("File upload failed : error = ". (!empty($this->err) ? $this->err : ''));
754 $this->addEvent($ar, $roo);
756 $r = DB_DataObject::factory($this->tableName());
761 $roo->jok($r->toRooArray($ar));
765 function addEvent($ar, $roo)
767 $roo->addEvent("ADD", $this, $this->toEventString());
770 function toEventString()
773 //$p = DB_DataObject::factory($this->ontable);
775 // return "ERROR unknown table? {$this->ontable}";
779 return $this->filename .' - on ' . $this->ontable . ':' . $this->onid;
780 //$p->toEventString();
783 function onUploadFromData($data, $roo)
786 $this->err = "Missing file details";
791 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
793 $this->beforeDelete();
796 if (empty($this->ontable)) {
797 $this->err = "Missing ontable";
801 if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
802 // then its an upload
803 $img = DB_DataObject::factory('Images');
804 $img->onid = $this->onid;
805 $img->ontable = $this->ontable;
806 $img->imgtype = $this->imgtype;
809 while ($img->fetch()) {
810 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
812 $img->beforeDelete();
818 require_once 'File/MimeType.php';
819 $y = new File_MimeType();
821 if (in_array($this->mimetype, array(
823 'application/octet-stream',
824 'image/x-png', // WTF does this?
825 'image/pjpeg', // WTF does this?
826 'application/x-apple-msg-attachment', /// apple doing it's magic...
827 'application/vnd.ms-excel', /// sometimes windows reports csv as excel???
828 'application/csv-tab-delimited-table', // windows again!!?
829 ))) { // weird tyeps..
830 $inf = pathinfo($this->filename);
831 $this->mimetype = $y->fromExt($inf['extension']);
834 $ext = $y->toExt(trim((string) $this->mimetype ));
836 $explode_filename = explode('.', $this->filename);
837 if(array_pop($explode_filename) != $ext){
838 $this->filename = $this->filename .'.'. $ext;
841 if (!$this->createFromData($data)) {
849 function createFromData($data)
852 if (0 === strpos($data, "data:")) {
853 // data:image/png;base64,
854 $data = substr($data,5);
855 $bits = explode(";", $data);
856 $this->mimetype = $bits[0];
859 if (empty($this->filename)) {
860 require_once 'File/MimeType.php';
861 $y = new File_MimeType();
862 $this->filename = 'image-'.$imgid++.'.'.$y->toExt($this->mimetype);
866 $this->mimetype = strtolower($this->mimetype);
867 if ($this->mimetype == 'image/jpg') {
868 $this->mimetype = 'image/jpeg';
872 $explode_mimetype = explode('/', $this->mimetype);
874 if (array_shift($explode_mimetype) == 'image') {
876 $imgs = @getimagesize('data://'. $data);
878 if (!empty($imgs) && !empty($imgs[0]) && !empty($imgs[1])) {
879 list($this->width , $this->height) = $imgs;
883 $this->created = date('Y-m-d H:i:s');
891 $f = $this->getStoreName();
893 if (!file_exists($dest)) {
894 $oldumask = umask(0);
895 mkdir($dest, 0775, true);
899 file_put_contents($f, file_get_contents("data://" . $data));
903 $this->filesize = filesize($f);
905 if($this->mimetype == 'application/pdf'){
906 $this->no_of_pages = $this->getPdfPages($f);
915 function toBase64($rotate = false, $scaleWidth = 0, $scaleHeight = 0)
917 if(!preg_match('/^image\//', $this->mimetype)){
921 $file = $this->getStoreName();
923 if(!file_exists($file)){
927 $data = file_get_contents($file);
929 if(!empty($scaleWidth) || !empty($scaleHeight)){
930 $data = $this->scale(false, $scaleWidth, $scaleHeight);
934 $data = $this->rotate($data);
937 $base64 = 'data:' . $this->mimetype . ';base64,' . base64_encode($data);
942 function getPdfPages($file)
944 require_once 'System.php';
948 $pdfinfo = System::which('pdfinfo');
950 if (!file_exists($file) || empty($pdfinfo)) {
954 $cmd = "{$pdfinfo} {$file}";
958 $info = explode("\n", $ret);
960 foreach ($info as $i){
962 if(!preg_match('/^Pages:[\s]*([0-9]+)/', $i, $matches)){
966 $page = (empty($matches[1])) ? 0 : $matches[1];
972 function rotate($imageBlob = false)
974 if(empty($imageBlob)){
975 $imagick = new Imagick($this->getStoreName());
977 $imagick = new Imagick();
978 $imagick->readImageBlob($imageBlob);
981 $orientation = $imagick->getImageOrientation();
983 switch($orientation) {
984 case Imagick::ORIENTATION_BOTTOMRIGHT:
985 $imagick->rotateimage(new ImagickPixel('#00000000'), 180); // rotate 180 degrees
988 case Imagick::ORIENTATION_RIGHTTOP:
989 $imagick->rotateimage(new ImagickPixel('#00000000'), 90); // rotate 90 degrees CW
992 case Imagick::ORIENTATION_LEFTBOTTOM:
993 $imagick->rotateimage(new ImagickPixel('#00000000'), -90); // rotate 90 degrees CCW
997 return $imagick->getImageBlob();
1000 function scale($imageBlob = false, $width = 0, $height = 0)
1002 if(empty($imageBlob)){
1003 $imagick = new Imagick($this->getStoreName());
1005 $imagick = new Imagick();
1006 $imagick->readImageBlob($imageBlob);
1009 $imagick->resizeimage($width, $height, Imagick::FILTER_LANCZOS, true, true);
1011 return $imagick->getImageBlob();