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 return self::staticGetStoreName($this);
209 static function staticGetStoreName($o)
211 $opts = HTML_FlexyFramework::get()->Pman;
212 $fn = preg_replace('/[^a-z0-9\.]+/i', '_', $o->filename);
213 return implode( '/', array(
214 $opts['storedir'], '_images_', date('Y/m', strtotime($o->created)), $o->id . '-'. $fn
219 * does the files exist?
223 return self::staticExists($this);
226 static function staticExists($o)
229 $ret = file_exists(self::staticGetStoreName($o));
231 return self::staticCanFix($o);
237 * the getStorename code got changed, and some old files may not end up with the correct name anymore.
238 * this tries to fix it.
243 return self::staticCanFix($this);
246 static function staticCanFix($o)
248 // look for the image in the folder, with matching id.
249 // this is problematic..
250 $fn = self::staticGetStoreName($o);
251 if (file_exists($fn . '-really-missing')) {
254 if (!file_exists(dirname($fn))) {
257 foreach( scandir(dirname($fn)) as $n) {
258 if (empty($n) || $n[0] == '.') {
261 $bits = explode('-', $n);
262 if ($bits[0] != $o->id) {
265 if (preg_match('/\.[0-9]+x[0-9]]+\.jpeg$/', $n)) {
268 copy(dirname($fn). '/'. $n, $fn);
272 // fixme - flag it as bad
273 touch($fn . '-really-missing');
278 * deletes all the image instances of it...
282 function beforeDelete($dependants_array, $roo)
285 if (!empty($dependants_array)) {
289 $opts = HTML_FlexyFramework::get()->Pman;
290 $deldir = $opts['storedir']. '/_deleted_images_';
292 if (!file_exists( $deldir )) {
293 @mkdir($deldir, 0755); // not sure why we are erroring here.. after checking - maybe permissions?
296 $fn = $this->getStoreName();
299 if (file_exists($fn)) {
301 if (file_exists($deldir . '/'. $b)) {
304 rename($fn, $deldir .'/'. $b);
312 if (file_exists($d)) {
315 while (false !== ($fn = readdir($dh))) {
316 if (substr($fn, 0, strlen($b)) == $b) {
318 if (file_exists($deldir . '/'. $fn)) {
319 unlink($d. '/'. $fn);
322 if (file_exists($d. '/'. $fn)) {
323 rename($d. '/'. $fn, $deldir .'/'. $fn);
332 * check mimetype against type
333 * - eg. img.is(#image#)
338 if (empty($this->mimetype)) {
341 return 0 === strcasecmp($type, array_shift(explode('/',$this->mimetype)));
345 * onUpload (singlely attached image to a table)
348 function onUploadWithTbl($tbl, $fld)
350 if ( $tbl->__table == 'Images') {
351 return; // not upload to self...
353 if (empty($_FILES['imageUpload']['tmp_name']) ||
354 empty($_FILES['imageUpload']['name']) ||
355 empty($_FILES['imageUpload']['type'])
360 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
362 $image = DB_DataObject::factory('Images');
363 $image->get($tbl->$fld);
364 $image->beforeDelete();
368 $image = DB_DataObject::factory('Images');
369 $image->onid = $tbl->id;
370 $image->ontable = $tbl->__table;
371 $image->filename = $_FILES['imageUpload']['name'];
372 $image->mimetype = $_FILES['imageUpload']['type'];
374 if (!$image->createFrom($_FILES['imageUpload']['tmp_name'])) {
378 $tbl->$fld = $image->id;
385 function onUpload($roo, $table = false, $file = false)
388 if ($table !== false) {
389 $this->ontable = $table->tableName();
390 $this->onid = $table->pid();
393 if ($file === false) {
394 $file = isset($_FILES['imageUpload']) ? $_FILES['imageUpload'] : array();
397 //print_r($_FILES); echo $_FILES['imageUpload']['type'];exit;
398 if (empty($file['tmp_name']) ||
399 empty($file['name']) ||
404 0=>"There is no error, the file uploaded with success",
405 1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
406 2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form" ,
407 3=>"The uploaded file was only partially uploaded",
408 4=>"No file was uploaded",
409 6=>"Missing a temporary folder"
411 $estr = (empty($file['error']) ? '?': $emap[$file['error']]);
412 $this->err = "Missing file details : Error=". $estr;
417 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
419 $this->beforeDelete();
421 if ( empty($this->ontable)) {
422 $this->err = "Missing ontable";
426 if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
427 // then its an upload
428 $img = DB_DataObject::factory('Images');
429 $img->onid = $this->onid;
430 $img->ontable = $this->ontable;
431 $img->imgtype = $this->imgtype;
434 while ($img->fetch()) {
435 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
437 $img->beforeDelete();
445 require_once 'File/MimeType.php';
446 $y = new File_MimeType();
447 $this->mimetype = $file['type'];
448 if (in_array($this->mimetype, array(
450 'application/octet-stream',
451 'image/x-png', // WTF does this?
452 'image/pjpeg', // WTF does this?
453 'application/x-apple-msg-attachment', /// apple doing it's magic...
454 'application/vnd.ms-excel', /// sometimes windows reports csv as excel???
455 'application/csv-tab-delimited-table', // windows again!!?
456 ))) { // weird tyeps..
457 $inf = pathinfo($file['name']);
458 $this->mimetype = $y->fromExt($inf['extension']);
462 $ext = $y->toExt(trim((string) $this->mimetype ));
464 $this->filename = empty($this->filename) ?
465 $file['name'] : ($this->filename .'.'. $ext);
469 if (!$this->createFrom($file['tmp_name'])) {
470 $this->err = isset($this->err) ? $this->err : "createFrom Image failed";
480 * return a list of images for an object, optionally with a mime regex.
481 * eg. '%/pdf' or 'image/%'
485 * $i = DB_DataObject::factory('Images');
486 * $i->imgtype = 'LOGO';
487 * $ar = $i->gather($somedataobject, 'image/%');
489 * @param {DB_DataObject} dataobject = the object to gather data on.
490 * @param {String} mimelike LIKE query to use for search
493 function gather($obj, $mime_like='', $opts=array())
495 //DB_DataObject::debugLevel(1);
496 if (empty($obj->id)) {
501 $c->whereAddIn($this->tableName() . '.ontable', array( $obj->tableName(), $obj->__table) , 'string');
504 if (!empty($mime_like)) {
505 $c->whereAdd("Images.mimetype LIKE '". $c->escape($mime_like) ."'");
507 $c->orderBy('created DESC');
509 return $c->fetchAll();
514 * set or get the dataobject this image is associated with
515 * @param DB_DataObject $obj An object to associate this image with
516 * (does not store it - you need to call update() to do that)
517 * @return DB_DataObject the dataobject this image is attached to.
519 function object($obj=false)
521 if ($obj === false) {
522 if (empty($this->ontable) || empty($this->onid)) {
525 $ret = DB_DataObject::factory($this->ontable);
526 $ret->get($this->onid);
531 $this->ontable = $obj->tableName();
532 $this->onid = $obj->id; /// assumes our nice standard of using ids..
537 function toRooArray($req)
540 $ret= $this->toArray();
543 $ff = HTML_FlexyFramework::get();
546 $ret['public_baseURL'] = isset($ff->Pman_Images['public_baseURL']) ?
547 $ff->Pman_Images['public_baseURL'] : $ff->baseURL;
549 if (!empty($req['query']['imagesize'])) {
550 // query/imageBaseURL ... depricated...? -- set it in config?
552 $baseURL = isset($req['query']['imageBaseURL']) ? $req['query']['imageBaseURL'] : $ret['public_baseURL'];
554 $ret['url'] = $this->URL(-1, '/Images/Download',$baseURL);
556 $ret['url_view'] = $this->URL(-1, '/Images',$baseURL);
558 if (!empty($req['query']['imagesize'])) {
559 $ret['url_thumb'] = $this->URL($req['query']['imagesize'], '/Images/Thumb',$baseURL);
564 $ret['shorten_name'] = $this->shorten_name();
570 * URL - create a url for the image.
571 * size - use -1 to show full size.
572 * provier = baseURL + /Images/Thumb ... use '/Images/' for full
576 function URL($size , $provider = '/Images/Thumb', $baseURL=false, $to_type=false)
579 return 'about:blank';
581 if (!$this->exists()) {
582 return 'about:missing';
585 $shorten_name = $this->shorten_name();
587 $ff = HTML_FlexyFramework::get();
588 $baseURL = $baseURL ? $baseURL : $ff->baseURL ;
589 if (preg_match('#^http[s]*://#', $provider)) {
594 $provider = preg_replace('#/Thumb$#', '', $provider);
596 return $baseURL . $provider . "/{$this->id}/{$shorten_name}"; // -- this breaks the rss feed #image-{$this->id}";
599 //$size = max(100, (int) $size);
600 //$size = min(1024, (int) $size);
601 // the size should 200x150 to convert
602 $sizear = preg_split('/(x|c)/', $size);
603 if(!isset($sizear[1])){
604 $sizear[1] = 0; // 0x with '0' is a box? why
607 $size = implode(strpos($size,'c') > -1 ? 'c' : 'x', $sizear);
609 $fc = $this->toFileConvert();
612 $mt = $to_type === false ? $this->mimetype : $to_type;
613 if (!preg_match('#^image/#i',$mt)) {
617 $cn = $fc->convert($mt, $size);
618 $shorten_name = $this->shorten_name(basename($cn));
620 return $baseURL . $provider . "/$size/{$this->id}/{$shorten_name}"; // -- this breaks the rss feed #image-{$this->id}";
624 * tries to get an image from then URL - not always has based... - also from the normal url
626 function getFromHashURL($url)
629 if (preg_match('/#image-([0-9]+)$/', $url, $matches)) {
631 } else if (preg_match('#Images/Thumb/[^/]+/([0-9]+)/#', $url, $matches)) {
633 } else if (preg_match('#Images/([0-9]+)/#', $url, $matches)) {
635 } else if (preg_match('#images[^/]+/([0-9]+)/#i', $url, $matches)) {
636 // supports images.xxxxx.com/{number}/name...
638 } else if (preg_match('#Thumb/[^/]+/([0-9]+)/#', $url, $matches)) {
641 if ($id === false || $id < 1) {
645 $img = DB_DAtaObject::Factory('images');
646 if ($img->get($id)) {
653 function shorten_name($fn = false)
655 if(empty($this->filename)) {
658 $fn = $fn === false ? $this->filename : $fn;
660 $filename = explode('.', $fn);
661 $ext = array_pop($filename);
662 $name = preg_replace("/[^A-Z0-9.]+/i", '-', implode('-', $filename)) ;
664 if(strlen($name) > 32) {
665 $name = substr($name, 0, 32);
668 $shorten_name = "{$name}.{$ext}";
670 return $shorten_name;
673 * size could be 123x345
677 function toHTML($size, $provider = '/Images/Thumb', $extra = '')
682 $sz = explode('x', $size);
685 if (!$this->id || empty($this->width)) {
687 $this->width = empty($sz[1]) ? $sx : $sz[1];
691 $ratio = empty($this->width) ? 1 : $this->height/ ($this->width *1.0);
692 $sy = intval($ratio * $sx);
698 if (strlen($this->title)) {
699 $extra = ' title="'. htmlspecialchars($this->title) . '"';
702 return '<img src="' . $this->URL($size, $provider) . '"' .
704 ' width="'. $sx . '"' .
705 ' height="'. $sy . '">';
712 * #2142 [new] CMS - image link urls
717 function toLinkHTML($size, $provider = '/Images/Thumb')
719 if(empty($this->linkurl)){
720 return $this->toHTML($size, $provider = '/Images/Thumb');
723 return '<a href="'.$this->linkurl.'" target="_blank">'.$this->toHTML($size, $provider = '/Images/Thumb').'</a>';
729 * to Fileconvert object..
734 function toFileConvert()
736 $fn = $this->getStoreName();
738 require_once 'File/Convert.php';
739 $fc = new File_Convert($this->getStoreName(), $this->mimetype);
746 require_once 'File/MimeType.php';
748 $y = new File_MimeType();
749 return $y->toExt($this->mimetype);
761 function setFromRoo($ar, $roo)
763 // not sure why we do this..
765 // if imgtype starts with '-' ? then we set the 'old' (probably to delete later)
766 if (!empty($ar['imgtype']) && !empty($ar['ontable']) && !empty($ar['onid']) && ($ar['imgtype'][0] == '-')) {
769 if ($this->find(true)) {
770 $roo->old = clone($this);
775 if (!empty($ar['_copy_from'])) {
777 if (!$this->checkPerm( 'A' , $roo->authUser)) {
778 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
781 $copy = DB_DataObject::factory('Images');
782 $copy->get($ar['_copy_from']);
783 $this->setFrom($copy->toArray());
785 $this->createFrom($copy->getStoreName());
787 $roo->addEvent("ADD", $this, $this->toEventString());
789 $r = DB_DataObject::factory($this->tableName());
795 $roo->jok($r->toRooArray($ar));
802 // FIXME - we should be checking perms here...
804 // this should be doign update
807 if (!$this->checkPerm($this->id ? 'A' : 'E', $roo->authUser)) {
808 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
812 if (!isset($_FILES['imageUpload'])) {
813 return; // standard update...
817 // print_r(!$this->onUpload($this));
819 if ( !$this->onUpload($this)) {
820 $roo->jerr("File upload failed : error = ". (!empty($this->err) ? $this->err : ''));
823 $this->addEvent($ar, $roo);
825 $r = DB_DataObject::factory($this->tableName());
830 $roo->jok($r->toRooArray($ar));
834 function addEvent($ar, $roo)
836 $roo->addEvent("ADD", $this, $this->toEventString());
839 function toEventString()
842 //$p = DB_DataObject::factory($this->ontable);
844 // return "ERROR unknown table? {$this->ontable}";
848 return $this->filename .' - on ' . $this->ontable . ':' . $this->onid;
849 //$p->toEventString();
852 function onUploadFromData($data, $roo)
855 $this->err = "Missing file details";
860 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
862 $this->beforeDelete();
865 if (empty($this->ontable)) {
866 $this->err = "Missing ontable";
870 if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
871 // then its an upload
872 $img = DB_DataObject::factory('Images');
873 $img->onid = $this->onid;
874 $img->ontable = $this->ontable;
875 $img->imgtype = $this->imgtype;
878 while ($img->fetch()) {
879 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
881 $img->beforeDelete();
887 require_once 'File/MimeType.php';
888 $y = new File_MimeType();
890 if (in_array($this->mimetype, array(
892 'application/octet-stream',
893 'image/x-png', // WTF does this?
894 'image/pjpeg', // WTF does this?
895 'application/x-apple-msg-attachment', /// apple doing it's magic...
896 'application/vnd.ms-excel', /// sometimes windows reports csv as excel???
897 'application/csv-tab-delimited-table', // windows again!!?
898 ))) { // weird tyeps..
899 $inf = pathinfo($this->filename);
900 $this->mimetype = $y->fromExt($inf['extension']);
903 $ext = $y->toExt(trim((string) $this->mimetype ));
905 $explode_filename = explode('.', $this->filename);
906 if(array_pop($explode_filename) != $ext){
907 $this->filename = $this->filename .'.'. $ext;
910 if (!$this->createFromData($data)) {
918 function createFromData($data)
921 if (0 === strpos($data, "data:")) {
922 // data:image/png;base64,
923 $data = substr($data,5);
924 $bits = explode(";", $data);
925 $this->mimetype = $bits[0];
928 if (empty($this->filename)) {
929 require_once 'File/MimeType.php';
930 $y = new File_MimeType();
931 $this->filename = 'image-'.$imgid++.'.'.$y->toExt($this->mimetype);
935 $this->mimetype = strtolower($this->mimetype);
936 if ($this->mimetype == 'image/jpg') {
937 $this->mimetype = 'image/jpeg';
941 $explode_mimetype = explode('/', $this->mimetype);
943 if (array_shift($explode_mimetype) == 'image') {
945 $imgs = @getimagesize('data://'. $data);
947 if (!empty($imgs) && !empty($imgs[0]) && !empty($imgs[1])) {
948 list($this->width , $this->height) = $imgs;
952 $this->created = date('Y-m-d H:i:s');
960 $f = $this->getStoreName();
962 if (!file_exists($dest)) {
963 $oldumask = umask(0);
964 mkdir($dest, 0775, true);
968 file_put_contents($f, file_get_contents("data://" . $data));
972 $this->filesize = filesize($f);
974 if($this->mimetype == 'application/pdf'){
975 $this->no_of_pages = $this->getPdfPages($f);
984 function toBase64($rotate = false, $scaleWidth = 0, $scaleHeight = 0)
986 if(!preg_match('/^image\//', $this->mimetype)){
990 $file = $this->getStoreName();
992 if(!file_exists($file)){
996 $data = file_get_contents($file);
998 if(!empty($scaleWidth) || !empty($scaleHeight)){
999 $data = $this->scale(false, $scaleWidth, $scaleHeight);
1003 $data = $this->rotate($data);
1006 $base64 = 'data:' . $this->mimetype . ';base64,' . base64_encode($data);
1011 function getPdfPages($file)
1013 require_once 'System.php';
1017 $pdfinfo = System::which('pdfinfo');
1019 if (!file_exists($file) || empty($pdfinfo)) {
1023 $cmd = "{$pdfinfo} {$file}";
1027 $info = explode("\n", $ret);
1029 foreach ($info as $i){
1031 if(!preg_match('/^Pages:[\s]*([0-9]+)/', $i, $matches)){
1035 $page = (empty($matches[1])) ? 0 : $matches[1];
1041 function rotate($imageBlob = false)
1043 if(empty($imageBlob)){
1044 $imagick = new Imagick($this->getStoreName());
1046 $imagick = new Imagick();
1047 $imagick->readImageBlob($imageBlob);
1050 $orientation = $imagick->getImageOrientation();
1052 switch($orientation) {
1053 case Imagick::ORIENTATION_BOTTOMRIGHT:
1054 $imagick->rotateimage(new ImagickPixel('#00000000'), 180); // rotate 180 degrees
1057 case Imagick::ORIENTATION_RIGHTTOP:
1058 $imagick->rotateimage(new ImagickPixel('#00000000'), 90); // rotate 90 degrees CW
1061 case Imagick::ORIENTATION_LEFTBOTTOM:
1062 $imagick->rotateimage(new ImagickPixel('#00000000'), -90); // rotate 90 degrees CCW
1066 return $imagick->getImageBlob();
1069 function scale($imageBlob = false, $width = 0, $height = 0)
1071 if(empty($imageBlob)){
1072 $imagick = new Imagick($this->getStoreName());
1074 $imagick = new Imagick();
1075 $imagick->readImageBlob($imageBlob);
1078 $imagick->resizeimage($width, $height, Imagick::FILTER_LANCZOS, true, true);
1080 return $imagick->getImageBlob();