Squiz Matrix  4.12.2
 All Data Structures Namespaces Functions Variables Pages
preview.inc
1 <?php
16 require_once SQ_LIB_PATH.'/html_form/html_form.inc';
17 
38 function paintPreview(&$owner, &$o, &$ei, $keywords=NULL)
39 {
40  // turning off error reporting for get size function
41  // `since a wrong url will display all unwanted error messgae...
42  error_reporting(0);
43  $q = $_GET['calc'];
44  if (strlen($q) > 0) {
45  printSize($owner);
46  exit;
47  }
48  error_reporting(6143); // restore the error reporting
49  $db = MatrixDAL::getDb();
50  $sql = 'SELECT l.url, l.http, l.https, lv.name
51  FROM '.SQ_TABLE_RUNNING_PREFIX.'ast_lookup l
52  LEFT JOIN '.SQ_TABLE_RUNNING_PREFIX.'ast_lookup_value lv
53  ON ((l.url = lv.url)
54  OR (l.url || \'/\' = lv.url)
55  OR ((l.url LIKE lv.url || \'/%\')
56  AND (l.url NOT LIKE lv.url || \'%/$\')))';
57 
58  $where = 'l.assetid = :ownerid
59  AND lv.name LIKE :pattern';
60  $where = $GLOBALS['SQ_SYSTEM']->constructRollbackWhereClause($where, 'l');
61  $where = $GLOBALS['SQ_SYSTEM']->constructRollbackWhereClause($where, 'lv');
62 
63  $full_sql = $sql.' '.$where.' ORDER BY l.url';
64  $query = MatrixDAL::preparePdoQuery($full_sql);
65 
66  try {
67  MatrixDAL::bindValueToPdo($query, 'ownerid', $owner->id);
68  MatrixDAL::bindValueToPdo($query, 'pattern', 'design::%');
69  $url_data = MatrixDAL::executePdoAll($query);
70  } catch (Exception $e) {
71  throw new Exception('Unable to get the design name and url for assetid #'.$owner->id.' due to the following database error:'.$e->getMessage());
72  }//end try catch
73 
74  if (empty($url_data)) {
75  // there is no direct URL for this asset
76  // so look at the dependant parents to try and find one
77  $parents = $GLOBALS['SQ_SYSTEM']->am->getDependantParents($owner->id);
78  foreach ($parents as $parentid) {
79  $parent = $GLOBALS['SQ_SYSTEM']->am->getAsset($parentid, '', TRUE);
80  if (is_null($parent)) continue;
81 
82  // Recycle query from before
83  try {
84  MatrixDAL::bindValueToPdo($query, 'ownerid', $parent->id);
85  MatrixDAL::bindValueToPdo($query, 'pattern', 'design::%');
86  $parent_urls = MatrixDAL::executePdoAll($query);
87  } catch (Exception $e) {
88  throw new Exception('Unable to get the design name and url for assetid #'.$owner->id.' due to the following database error:'.$e->getMessage());
89  }//end try catch
90 
91  $url_data = array_merge($url_data, $parent_urls);
92  $GLOBALS['SQ_SYSTEM']->am->forgetAsset($parent);
93  }
94  }
95 
96  if (empty($url_data)) {
97  // there is no URL with lookup values for this asset
98  // so just do a straight call for lookups
99  $url_data = $owner->getLookups();
100  }
101 
102 
103  if (!empty($url_data)) {
104  $preview_urls = Array();
105  $preview_designs = Array('system::frontend' => 'Default Frontend Design');
106  $has_default_design = FALSE;
107 
108  $contains_diff_domain = FALSE;
109  $current_url = parse_url(current_url());
110 
111  // set the primary preview url to the current root url
112  $root_urls = explode("\n", SQ_CONF_SYSTEM_ROOT_URLS);
113  $current_root_url = $root_urls[0];
114  foreach ($root_urls as $root_url) {
115  if (preg_match('/'.$current_url['host'].'/i', $root_url)) {
116  $current_root_url = $root_url;
117  break;
118  }
119  }
120 
121  $primary_url = $GLOBALS['SQ_SYSTEM']->am->getAssetURL($owner->id, $current_root_url);
122  foreach ($url_data as $url_info) {
123  $protocol_list = Array();
124 
125  if ($url_info['https']) {
126  $protocol_list['https'] = 'https://';
127  }
128  if ($url_info['http']) {
129  $protocol_list['http'] = 'http://';
130  }
131 
132  foreach ($protocol_list as $protocol) {
133  $preview_urls[$protocol.$url_info['url']] = $protocol.$url_info['url'];
134 
135  if (empty($primary_url)) {
136  $primary_url = $protocol.$url_info['url'];
137  }
138 
139  $url_pieces = parse_url($protocol.$url_info['url']);
140  if ($url_pieces['host'] != $current_url['host']) {
141  $contains_diff_domain = TRUE;
142  }
143 
144  if (!empty($url_info['name'])) {
145  $design_name = $url_info['name'];
146  if (!preg_match('/^design::(system|user)::(.*)$/', $design_name, $matches)) {
147  continue;
148  }
149  if ($matches[1] == 'user') {
150  $preview_designs[$matches[2]] = ucwords(str_replace('_', ' ', $matches[2]));
151  } else if ($design_name == 'design::system::frontend') {
152  $has_default_design = TRUE;
153  }
154  }
155  }//end foreach protocol
156  }//end foreach url
157 
158  if (!$has_default_design) {
159  $preview_designs[''] = 'None';
160  }
161 
162  $add_nocache = TRUE;
163  $root_url_array = $GLOBALS['SQ_SYSTEM']->am->getRootURL(strip_url($owner->getURL(), TRUE));
164  $root_url = trim($root_url_array['url']);
165 
166  if (strpos($primary_url, '/__data/') !== FALSE || (SQ_CONF_STATIC_ROOT_URL && ($root_url == SQ_CONF_STATIC_ROOT_URL || strpos($root_url, SQ_CONF_STATIC_ROOT_URL.'/') !== FALSE || strpos($primary_url, SQ_CONF_STATIC_ROOT_URL.'/') !== FALSE))) {
167  $add_nocache = FALSE;
168  }
169  //Bug #4708 openRaw and closeRaw incompatible in LIMBO mode with buffering OFF as they behave as sections (creating tables).
170  if (!((!$o->_buffering) && SQ_IN_LIMBO)) $o->openRaw();
171 
172  ?>
173  <script type="text/javascript">
174 
175  var preview_url = '<?php echo str_replace("'", "\'", $primary_url); ?>';
176  var xmlHttp = null;
177  var url_calculate;
178 
179  function update_preview_url()
180  {
181  var url = document.getElementById('preview_url').value;
182  var query_args = [];
183 
184  var uc = document.getElementById('use_cache');
185  if (uc != null) {
186  if (!uc.checked) {
187  url += '<?php echo ($add_nocache) ? '/'.SQ_CONF_NOCACHE_SUFFIX : ''; ?>';
188  }
189  }
190 
191  var sd = document.getElementById('show_diff');
192  if (sd != null) {
193  if (sd.checked) {
194  query_args.push('SQ_ACTION=diff');
195  }
196  }
197 
198  var pd = document.getElementById('preview_design');
199  if ((pd != null) && (pd.value != '')) {
200  query_args.push('SQ_DESIGN_NAME='+pd.value);
201  }
202 
203  var pc = document.getElementById('preview_context');
204  if ((pc != null) && (pc.value != '-sep-') && (pc.value != '-default-')) {
205  query_args.push('SQ_CONTEXT_NAME='+pc.value);
206  }
207 
208  if (query_args.length != 0) {
209  var query_str = '';
210  for (var i=0; i < query_args.length; i++) {
211  query_str += '&'+query_args[i];
212  }
213  url += '?'+query_str.substr(1);
214  }
215 
216  document.getElementById('sq_preview_new_window').href = url;
217  preview_url = url;
218  }
219 
220  function do_preview()
221  {
222  document.getElementById('sq_preview_frame').src = preview_url;
223  }
224 
225  function get_size() {
226  try
227  {
228  xmlHttp=new XMLHttpRequest();
229  }
230  catch(e)
231  {
232  try
233  {
234  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
235  }
236  catch(e)
237  {
238  alert ("Your browser does not support XMLHTTP!");
239  return;
240  }
241  }
242  document.getElementById("size_button").value = "Calculating ....";
243  document.getElementById("size_button").disabled = true;
244  if (preview_url.match(/SQ_DESIGN_NAME=/)) {
245  var design_name = preview_url.split("?SQ_DESIGN_NAME=");
246  if(design_name[0].match(/_nocache/)){
247  url_calculate = design_name[0].split("_nocache");
248  }
249  url_calculate=url_calculate+"/_admin/?SQ_BACKEND_PAGE=main&backend_section=am&am_section=edit_asset&assetid=<?php echo $owner->id ?>&asset_ei_screen=preview";
250  url_calculate = url_calculate+"&calc=calculate";
251  url_calculate = url_calculate+"&sid="+Math.random();
252  } else {
253  if(preview_url.match(/_nocache/)){
254  url_calculate = preview_url.split("_nocache");
255  }
256  url_calculate=preview_url+"/_admin/?SQ_BACKEND_PAGE=main&backend_section=am&am_section=edit_asset&assetid=<?php echo $owner->id ?>&asset_ei_screen=preview";
257  url_calculate = url_calculate+"&calc=calculate";
258  url_calculate = url_calculate+"&sid="+Math.random();
259  }
260 
261 
262  if (preview_url.match(/SQ_DESIGN_NAME=/)) {
263  url_calculate = url_calculate+"&SQ_DESIGN_NAME="+design_name[1];
264  }
265  xmlHttp.onreadystatechange = stateChanged;
266  xmlHttp.open("GET",url_calculate,true);
267  xmlHttp.send(null);
268  }
269 
270  function stateChanged()
271  {
272  if (xmlHttp.readyState==4)
273  {
274  document.getElementById("size_elements").innerHTML=xmlHttp.responseText;
275  document.getElementById("size_title").innerHTML = "Size";
276  document.getElementById("size_button").value = "Calculate Size";
277  document.getElementById("size_button").disabled = false;
278  }
279  }
280 
281  </script>
282  <?php
283  //Bug #4708 openRaw and closeRaw incompatible in LIMBO mode with buffering OFF as they behave as sections (creating tables).
284  if (!((!$o->_buffering) && SQ_IN_LIMBO)) $o->closeRaw();
285 
286  $o->openSection(translate('preview_options'));
287  $o->openField(translate('url'));
288  if (count($preview_urls) > 1) {
289  combo_box('preview_url', $preview_urls, FALSE, $primary_url, 1, 'onchange="update_preview_url()"');
290  } else {
291  echo $primary_url;
292  hidden_field('preview_url', $primary_url);
293  }
294  $o->closeField();
295 
296  $o->openField(translate('design'));
297  if (count($preview_designs) > 1) {
298  combo_box('preview_design', $preview_designs, FALSE, '', 1, 'onchange="update_preview_url()"');
299  } else {
300  echo ($has_default_design) ? 'Default Frontend Design' : 'None';
301  }
302  $o->closeField();
303 
304  $o->openField(translate('context'));
305  $contexts = $GLOBALS['SQ_SYSTEM']->getAllContexts();
306  $current_context = $GLOBALS['SQ_SYSTEM']->getContextId();
307  if (count($contexts) > 1) {
308  $context_list = Array(
309  '-default-' => translate('use_normal_context_for_this_url'),
310  '-sep-' => '----------------------',
311  );
312  foreach ($contexts as $context_item_id => $context_item) {
313  if ((int)$current_context === (int)$context_item_id) {
314  $context_name = $context_item['name'];
315  }
316 
317  $context_list[rawurlencode($context_item['name'])] = $context_item['name'];
318  }
319  combo_box('preview_context', $context_list, FALSE, Array('-default-'), 1, 'onchange="update_preview_url()"');
320  }
321  $o->closeField();
322 
323 
324  $o->openField(translate('use_cache'));
325  check_box('use_cache', '1', FALSE, 'if (this.checked) { document.getElementById(\'show_diff\').checked = false; } update_preview_url()');
326  label(translate('show_cached_asset'), 'use_cache');
327  $o->closeField();
328 
329  if ($owner->status & SQ_SC_STATUS_SAFE_EDITING) {
330  $o->openField(translate('show_diff'));
331  check_box('show_diff', '1', FALSE, 'if (this.checked) { document.getElementById(\'use_cache\').checked = false; } update_preview_url()');
332  label(translate('show_safe_edit_difference'), 'show_diff');
333  $o->closeField();
334  }
335  $o->openField('');
336  ?>
337  <i><?php echo translate('preview_change_options'); ?></i>
338  <?php
339  if ($contains_diff_domain && !$owner->effectiveUnrestricted()) {
340  echo translate('different_domain_login', $current_url['host']);
341  }
342  $o->closeField();
343 
344  $o->openField('<span id="size_title"></span>');
345  ?>
346  <span id="size_elements"></span>
347  <p style="text-align: right;">
348  <?php normal_button('preview_button', translate('preview'), 'do_preview()'); echo ' ';
349  normal_button('size_button', translate('calculate'), 'get_size()');?>
350  </p>
351  <?php
352  $o->closeField();
353  $o->closeSection();
354 
355  $o->openSection(translate('preview'));
356  $o->openRaw('');
357  if ($add_nocache) {
358  $primary_url .= '/'.SQ_CONF_NOCACHE_SUFFIX;
359  }
360  ob_start();
361  ?><a href="<?php echo $primary_url; ?>" id="sq_preview_new_window" target="_blank"><?php echo translate('show_in_new_window'); ?></a><?php
362  $replacements_link = ob_get_contents();
363  ob_end_clean();
364  ?>
365  <p class="sq-backend-field">
366  <?php echo translate('currently_previewing', htmlspecialchars($owner->name, ENT_COMPAT, SQ_CONF_DEFAULT_CHARACTER_SET), $replacements_link); ?>
367  </p>
368  <iframe name="sq_preview_frame" id="sq_preview_frame" src="<?php echo $primary_url; ?>" style="width: 100%; height: 400px; border: 1px solid #C3C3C3;"></iframe>
369  <?php
370  $o->closeRaw();
371  $o->closeSection();
372 
373  } else {
374 
375  // there is no preview URL available for this asset
376  $o->openSection(translate('no_preview_available'));
377  $o->openField('');
378  echo translate('asset_cannot_preview');
379  $o->closeField();
380  $o->closeSection();
381 
382  }//end if we have URLs
383 
384  return FALSE;
385 
386 }//end paintPreview()
387 
388 
399 function processPreview(&$owner, &$o, &$ei)
400 {
401  return FALSE;
402 
403 }//end processPreview()
404 
405 
414 function printSize(&$owner)
415 {
416  $asset_here = $GLOBALS['SQ_SYSTEM']->am->getAsset($owner->id,'',TRUE);
417  // If its a file asset just get the size and display it
418  if ($owner instanceof File) {
419  $existing = $asset_here->getExistingFile();
420  echo '<b>'.easy_filesize($existing['size']).'</b>';
421  return;
422  }
423  ob_start();
424  $asset_here->printFrontend();
425  $file_content = ob_get_contents();
426  ob_end_clean();
427  $file_size = mb_strlen($file_content);
428  ob_start();
429  $asset_here->printBody();
430  $body_content = ob_get_contents();
431  ob_end_clean();
432  $body_size = mb_strlen($body_content);
433  $array_img = Array();
434  $array_img_2 = Array();
435  $array_css = Array();
436  $array_js = Array();
437  $total_img_size = 0;
438  $total_js_size = 0;
439  $total_css_size = 0;
440  $total_other_size = 0;
441  preg_match_all('/(url\(\"?([^\")]+))/ie', $file_content, $array_img);
442  preg_match_all('/<(img|input|embed).*>/iU', $file_content, $matches);
443  preg_match_all('/(?:src|background)[\s]?=[\s]?"?([^"]+)"?/i', implode('', $matches[0]), $array_img_embd);
444 
445  preg_match_all('/<script[^>]+.*[\s]*(src|background)[\040]*=[\040]*\"?([^\"\' >]+)/ie', $file_content, $array_js);
446  preg_match_all('/<link[^>]+href[\040]*=[\040]*[\"|\'|\\\\]*([^\'|\"|>|\040]*(.*)\.css)[\"|\'|>|\040|\\\\]* /ie',$file_content, $array_css);
447  $array_img = $array_img[2];
448  $array_img = array_unique(array_merge($array_img,$array_img_embd[1]));
449  $array_js = array_unique($array_js[2]);
450  $array_css = array_unique($array_css[1]);
451  $array_types = Array(
452  'img' => Array(
453  0 => $system_url_img = NULL,
454  1 => $array_img,
455  ),
456  'css' => Array(
457  0 => $system_url_css = NULL,
458  1 => $array_css,
459  ),
460  'js' => Array(
461  0 => $system_url_js = NULL,
462  1 => $array_js,
463  ),
464  );
465 
466  foreach ($array_types as $key => $type_asset) {
467  foreach ($type_asset[1] as $key_value => $url) {
468  $url = str_replace("'",'',$url);
469  $basename = explode('/',$url);
470  $protocol = explode(':',$url);
471  $db = MatrixDAL::getDb();
472  $sql = 'SELECT
473  assetid
474  FROM
475  sq_ast_path
476  WHERE
477  path = :url';
478  try {
479  $query = MatrixDAL::preparePdoQuery($sql);
480  MatrixDAL::bindValueToPdo($query, 'url', $basename[sizeof($basename)-1]);
481  $result = MatrixDAL::executePdoAll($query);
482  } catch (Exception $e) {
483  throw new Exception('Unable to get URLs for asset '.$path.' due to database error: '.$e->getMessage());
484  }
485  if (!($result)) {
486  $type_asset[0] = $type_asset[0].$url.'~';
487  } else {
488  $asset = $GLOBALS['SQ_SYSTEM']->am->getAsset($result[0][0]);
489  if ($asset && $key == 'img') {
490  $total_img_size += $asset->attr('size');
491  } else if ($asset && $key == 'css') {
492  $total_css_size += filesize($asset->data_path.'/'.$asset->name);
493  } else if ($asset && $key == 'js') {
494  $total_js_size += filesize($asset->data_path.'/'.$asset->name);
495  } else if ($asset) {
496  $total_other_size += filesize($asset->data_path.'/'.$asset->name);
497  }
498  }
499  }//end foreach
500  // get default times so that we can restore them later
501  $default_execution_time = ini_get('max_execution_time');
502  $default_socket_time = ini_get('default_socket_timeout');
503  $type_asset[0] = explode('~',$type_asset[0]);
504  if (sizeof($type_asset[0]) != 1) {
505  foreach ($type_asset[0] as $key => $url) {
506  $url = str_replace("'",'',$url);
507  if (strpos($url, '__data') !== FALSE && $url != '') {
508  $parts = explode('__data',$url);
509  $url = SQ_DATA_PATH.'/public'.$parts[1];
510  $total_js_size_here = filesize($url);
511  $total_js_size += $total_js_size_here;
512  } else {
513  if (strpos($url, '__lib') !== FALSE && $url != '') {
514  $parts = explode('__lib',$url);
515  $url = SQ_INCLUDE_PATH.'/../lib'.$parts[1];
516  $total_js_size_here = filesize($url);
517  $total_js_size += $total_js_size_here;
518  } else if ($url != '') {
519  // set execution time to 5 second so that script doesnt take too long to fetch the headers
520  set_time_limit(5);
521  ini_set('default_socket_timeout', 5);
522  $headers = get_headers($url,1);
523  if ($key == 'img') {
524  $total_img_size += $headers['Content-Length'];
525  } else if ($key == 'css') {
526  $total_css_size += $headers['Content-Length'];
527  } else if ($key == 'js') {
528  $total_js_size += $headers['Content-Length'];
529  } else {
530  $total_other_size += $headers['Content-Length'];
531  }
532  if (strpos($headers[0], '404') !== FALSE || !($headers)) {
533  $element_unknown = $element_unknown.$url.'~';
534  }
535  set_time_limit($default_execution_time);
536  ini_set('default_socket_timeout', $default_socket_time);
537  }
538  }
539  }//end foreach
540  }//end if
541  }//end foreach
542  $output = '<table width=40% cellspacing =\'0\'>
543  <tr><td></td><td>'.sq_get_icon($GLOBALS['SQ_SYSTEM']->am->getAssetIconURL('page_standard'),15,15,'',NULL,'').'</td><td>HTML content</td><td align=right>'.number_format(($file_size/1024),2).'</td><td>KB</td></tr>
544  <tr><td></td><td>'.sq_get_icon($GLOBALS['SQ_SYSTEM']->am->getAssetIconURL('bodycopy'),15,15,'',NULL,'').'</td><td>Body content</td><td align=right>'.number_format(($body_size/1024),2).'</td><td>KB</td></tr>
545  <tr><td></td><td>'.sq_get_icon($GLOBALS['SQ_SYSTEM']->am->getAssetIconURL('design_css'),15,15,'',NULL,'').'</td><td>CSS ('.sizeof($array_css).')</td><td align=right>'.number_format((($total_css_size)/1024),2).'</td><td>KB</td></tr>
546  <tr><td></td><td>'.sq_get_icon($GLOBALS['SQ_SYSTEM']->am->getAssetIconURL('text_file'),15,15,'',NULL,'').'</td><td>Javascript ('.sizeof($array_js).')</td><td align=right>'.number_format((($total_js_size)/1024),2).'</td><td>KB</td></tr>
547  <tr><td></td><td>'.sq_get_icon($GLOBALS['SQ_SYSTEM']->am->getAssetIconURL('image'),15,15,'',NULL,'').'</td><td>Media ('.sizeof($array_img).')</td><td align=right>'.number_format(($total_img_size/1024),2).'</td><td>KB</td></tr>';
548 
549  if ($total_other_size > 0) {
550  $output .= '<tr><td></td><td>'.sq_get_icon($GLOBALS['SQ_SYSTEM']->am->getAssetIconURL('file'),15,15,'',NULL,'').'</td><td>Other Elements</td><td align=right>'.number_format(($total_other_size/1024),2).'</td><td>KB</td></tr>
551  <tr><td></td><td>'.sq_get_icon(sq_web_path('lib').'/web/images/blank.gif',15,15,'',NULL,'').'</td><td style=\'border-top: thin solid#000000\'><b>Total<b></td><td align=right style=\'border-top: thin solid#000000\'><b>'.number_format((($file_size+$total_img_size+$total_js_size+$total_css_size)/1024),2).'</b></td><td style=\'border-top: thin solid#000000\'><b>KB</b></td></tr></table>';
552  } else {
553  $output .= '<tr><td></td><td>'.sq_get_icon(sq_web_path('lib').'/web/images/blank.gif',15,15,'',NULL,'').'</td><td style=\'border-top: thin solid#000000\'><b>Total</b></td><td align=right style=\'border-top: thin solid#000000\'><b>'.number_format((($file_size+$total_img_size+$total_js_size+$total_css_size)/1024),2).'</b></td><td style=\'border-top: thin solid#000000\'><b>KB</b></td></tr></table>';
554  }
555 
556  echo $output;
557 
558  $element_unknown = explode('~',$element_unknown);
559  if (sizeof($element_unknown)!= 1) {
560  echo '<br><span class="sq-backend-warning ">Could not get data for</span>';
561  foreach ($element_unknown as $key => $unknown_url) {
562  if ($unknown_url != '') {
563  echo '<br><span class="sq-backend-warning ">'.$unknown_url.'</span>';
564  }
565  }
566  }
567 
568 }//end printSize()
569 
570 
571 ?>