· 6 years ago · Oct 07, 2019, 01:48 PM
1<?php
2
3include_once "modules/sendmail.php";
4
5function get_user_ip() {
6 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
7 $ip = $_SERVER['HTTP_CLIENT_IP'];
8 }
9 elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
10 $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
11 }
12 else {
13 $ip = $_SERVER['REMOTE_ADDR'];
14 }
15
16 if (strlen($ip) > 16) {
17 $explode_ip = explode(',', $ip);
18
19 $new_ip = array();
20 foreach ($explode_ip as $item_ip) {
21 $new_ip[] = trim($item_ip);
22 }
23
24 if (count($new_ip) > 0) {
25 $ip = end($new_ip);
26 }
27 }
28
29 return $ip;
30}
31
32function get_me_magazin_description_user_by_email_user($email) {
33 //include_once "modules/connect_to_sup_db.php";
34
35 $magazin_description = '';
36 $email = str_replace(array(
37 '"',
38 "'",
39 '`',
40 "/",
41 "\\",
42 '=',
43 '?',
44 '&',
45 "#",
46 ':',
47 ' ',
48 ), '', $email);
49
50 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_users']}` WHERE `email_md5`=MD5('{$email}');") or die(errorDiv(mysql_error()));
51 if (mysql_num_rows($result)) {
52 $subj = mysql_fetch_array($result);
53 $magazin_description = trim($subj['magazin_description']);
54 }
55
56 return $magazin_description;
57}
58
59function generate_password() {
60
61 $arr1 = array(
62 'a',
63 'b',
64 'c',
65 'd',
66 'e',
67 'f',
68 'g',
69 'i',
70 'k',
71 'm',
72 'n',
73 'o',
74 'p',
75 'r',
76 's',
77 't',
78 'u',
79 'v',
80 'x',
81 'y',
82 'z',
83 );
84 $arr2 = array('1', '2', '3', '4', '5', '6', '7', '8', '9', '0');
85
86 $pass = "";
87
88 for ($i = 0; $i < 3; $i++) {
89 $pass .= $arr1[rand(0, count($arr1) - 1)];
90 }
91 for ($i = 0; $i < 3; $i++) {
92 $pass .= $arr2[rand(0, count($arr2) - 1)];
93 }
94
95 return $pass;
96
97}
98
99// отрезаем последние байты из ip
100function castration_ip($ip, $stars = 0) {
101 $ip_a = explode('.', $ip);
102 if (!$stars || $stars < 0) {
103 $stars = 0;
104 }
105 switch ($stars) {
106 case '0':
107 {
108 return $ip;
109 break;
110 }
111 case '1':
112 {
113 return $ip_a[0] . '.' . $ip_a[1] . '.' . $ip_a[2] . '.*';
114 break;
115 }
116 case '2':
117 {
118 return $ip_a[0] . '.' . $ip_a[1] . '.*.*';
119 break;
120 }
121 case '3':
122 {
123 return $ip_a[0] . '.*.*.*';
124 break;
125 }
126 case '4':
127 {
128 return '*.*.*.*';
129 break;
130 }
131 default :
132 {
133 return '*.*.*.*';
134 break;
135 }
136 }
137}
138
139// проверяем ip на причастность к диапазону разрешенных
140function access_ip($user_ip, $ips_a = array()) {
141 if (!preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/i', $user_ip)) {
142 return 0;
143 }
144 if (!$user_ip) {
145 $user_ip = get_user_ip();
146 }
147
148 foreach ($ips_a as $ip) {
149 $ip = trim($ip);
150 if (!substr_count($ip, '*')) {
151 if ($user_ip == $ip) {
152 return 1;
153 }
154 else {
155 continue;
156 }
157 }
158 else {
159 for ($stars = 1; $stars <= substr_count($ip, '*'); $stars++) {
160 if (castration_ip($user_ip, $stars) == $ip) {
161 return 1;
162 }
163 }
164 }
165 }
166
167 return 0;
168}
169
170function get_user_agent() {
171 return getenv("HTTP_USER_AGENT");
172}
173
174/*
175 function price($key=0,$name=0,$simple=0,$nocomment=0,$image=0,$link=0,$include=0)
176 { if(!$key)return NULL;
177 if(!$name)unset($simple); // нельзя запросить только значение суммы не уточнив комментарий
178
179 if($simple)$nocomment=1; // отключаем приписку комментария, если выводим лишь цену
180
181 $ret_mysql=mysql_query("SELECT * FROM `{$GLOBALS['TABLE_prices']}` WHERE `key`='{$key}' ".($name?" AND `name`='{$name}' ":'')." ORDER BY `price` ASC ".($simple?" LIMIT 1":'').";");
182 if($ret_mysql&&mysql_num_rows($ret_mysql))
183 { if($simple) // просто стоимость
184 { $a=mysql_fetch_assoc($ret_mysql);
185 $ret='<nobr>'.addpoint($a['price']).' '.$a['unit'].'</nobr>';
186 } else // стоимость таблицей
187 { $i=0;
188 $ret="<div style=\"background:#d3d3d3;\"><table style=\"width:100%;\" border=\"0\" cellspacing=\"1\" cellpadding=\"5\"><col width=\"300\"><col width=\"200\"><tbody>";
189 while($a=mysql_fetch_assoc($ret_mysql))
190 { $ret.="<tr style=\"background:".($i%2?'#f6f6f6':'#fff').";\">";
191 if($a['key']&&!$premier_tr)
192 {
193 $ret.="<td style=\"width:300px;\" rowspan=\"".mysql_num_rows($ret_mysql)."\"><div class=\"strong\">".$a['key']."</div>";
194 if($image)
195 { $ret.="<div>";
196 if($link)$ret.="<a href=\"{$link}\" target=\"_blank\" title=\"{$a['key']}\">";
197 $ret.="<img src=\"{$image}\" alt=\"{$a['key']}\" />";
198 if($link)$ret.="</a>";
199 $ret.="</div>";
200 }
201 if($include)$ret.="<div>".include_virtual(str_replace("include:","",$include))."</div>";
202 $ret.="</td>";
203 $premier_tr=1;
204 }
205 if($a['name'])$ret.="<td style=\"width:200px;\">".stripslashes($a['name'])."</td>";
206 $ret.="<td>".(round($a['price'])?"<nobr>".addpoint($a['price'])." {$a['unit']}</nobr>":'')."</td>";
207 $ret.="</tr>";
208 $i++;
209 }
210 $ret.="</tbody></table></div>";
211 }
212 }
213
214 if(!$nocomment)$ret.="<div style=\"font-size:11px;\" class=\"strong red\">По вопросам о просчете цен и скидках Вы можете звонить по телефону 8 (812) ".$_SESSION['global_phone'].", все расскажем и покажем!</div>";
215
216 return $ret;
217 }
218 */
219/*
220 function clear_price($s) // очистка цены от тегов для калькулятора
221 {
222 $ret=str_replace(',','.',round(strip_tags($s),2));
223 return $ret;
224 }
225 */
226
227function addpoint($item0) {
228 $minus = '';
229 $ret = '';
230 $item0 = str_replace(',', '.', $item0); // в случаях, если дробь в системе идет через запятую, то заменяем ее на точку
231
232 if ($item0 < 0) {
233 $minus = 1;
234 }
235 $item0 = str_replace('-', '', $item0);
236
237 $item_a = explode(".", $item0);
238 $item = $item_a[0];
239 $item = strrev($item);
240 for ($i = 0; $i < strlen($item); $i++) {
241 $ret .= $item[$i];
242 if (($i % 3 == 2) && ($i < strlen($item) - 1)) {
243 $ret .= ",";
244 }
245 }
246
247 $ret = strrev($ret);
248 if (strpos($item0, ".")) {
249 $ret .= "." . (strlen($item_a[1]) == 1 ? $item_a[1] . "0" : substr($item_a[1], 0, 2));
250 }
251
252 if ($minus) {
253 $ret = '-' . $ret;
254 }
255
256 return $ret;
257}
258
259/*
260 function replace_all_price($content)
261 {
262
263 if(auth()!="full")
264 {
265 $comment="Узнать подробности и условия заказа Вы можете по телефону <nobr><span style=\"font-size:18px;\">8 (812) {phone}</span></nobr> или по почте <nobr><a href=\"mailto:{email}\" style=\"font-size:18px;\">{email}</a></nobr><br />";
266 $content=str_replace(array("{comment}","{phone}","{email}"),array($comment,$_SESSION['global_phone'],$_SESSION['global_email']),$content);
267
268 preg_match_all('/#{price\(\"(.*?)\"\)}#/i',$content,$a);
269
270 foreach($a[1] as $key=>$value)
271 { $m[0][]="#{price(\"{$value}\")}#";
272
273 $value_a=explode(',',str_replace('"','',$value));
274//echo count($value_a).'-+';
275//echo $value_a[6];
276 if(count($value_a)==1) $m[1][]=price($value_a[0]);
277 if(count($value_a)==2) $m[1][]=price($value_a[0],$value_a[1]);
278 if(count($value_a)==3) $m[1][]=price($value_a[0],$value_a[1],$value_a[2]);
279 if(count($value_a)==4) $m[1][]=price($value_a[0],$value_a[1],$value_a[2],$value_a[3]);
280 if(count($value_a)==5) $m[1][]=price($value_a[0],$value_a[1],$value_a[2],$value_a[3],$value_a[4]);
281 if(count($value_a)==6) $m[1][]=price($value_a[0],$value_a[1],$value_a[2],$value_a[3],$value_a[4],$value_a[5]);
282 if(count($value_a)==7) $m[1][]=price($value_a[0],$value_a[1],$value_a[2],$value_a[3],$value_a[4],$value_a[5],$value_a[6]);
283 }
284
285 return str_replace($m[0],$m[1],$content);
286 } else return($content);
287 }
288 */
289
290/*
291 function see_also($id, $lite=0)
292 { global $a_before,$a_after;
293 $id=round($id);
294
295 $ret_mysql=mysql_query("SELECT * FROM `{$GLOBALS['TABLE_items']}` WHERE `id`='{$id}' LIMIT 1;");
296 if($ret_mysql&&mysql_num_rows($ret_mysql))
297 { $a=mysql_fetch_assoc($ret_mysql);
298 $porn=$a['porn'];
299 $parent=$a['parent'];
300 } else return '';
301
302 $ret_mysql=mysql_query("SELECT * FROM `{$GLOBALS['TABLE_items']}` WHERE `parent`='{$parent}' AND `porn`>'{$porn}' ORDER BY `porn` ASC LIMIT 1;");
303 if($ret_mysql&&mysql_num_rows($ret_mysql)) $a_before=mysql_fetch_assoc($ret_mysql); else $a_befor='';
304
305 $ret_mysql=mysql_query("SELECT * FROM `{$GLOBALS['TABLE_items']}` WHERE `parent`='{$parent}' AND `porn`<'{$porn}' ORDER BY `porn` DESC LIMIT 1;");
306 if($ret_mysql&&mysql_num_rows($ret_mysql)) $a_after=mysql_fetch_assoc($ret_mysql); else $a_after='';
307
308 return $lite?include_virtual("templates/see_also_lite.html"):include_virtual("templates/see_also.html");
309
310 }
311 */
312
313/*
314 function replace_form_feedback($content)
315 {
316
317 if(auth()!='full') $content=str_replace("{form_feedback}",include_virtual("templates/form_feedback.html"),$content);
318
319 return $content;
320
321 }
322 */
323
324/*
325 function see_also_image($id)
326 { $id=round($id);
327
328 $ret_mysql=mysql_query("SELECT * FROM `{$GLOBALS['TABLE_items']}` WHERE `id`='{$id}' LIMIT 1;");
329 if($ret_mysql&&mysql_num_rows($ret_mysql))
330 { $a=mysql_fetch_assoc($ret_mysql);
331 $porn=$a['porn'];
332 $parent=$a['parent'];
333 } else return '';
334
335 $ret_mysql=mysql_query("SELECT * FROM `{$GLOBALS['TABLE_items']}` WHERE `parent`='{$parent}' AND `porn`>'{$porn}' ORDER BY `porn` ASC LIMIT 1;");
336 $count = mysql_num_rows($ret_mysql);
337 if ($count)
338 { for ($i=0; $i<$count; $i++)
339 { $subj=mysql_fetch_array($ret_mysql);
340
341 $ret_img0=mysql_query("SELECT * FROM `{$GLOBALS['TABLE_foto']}` WHERE `parent`='{$parent}-".$subj['id']."' AND `image`!='' ORDER BY `pornfoto` DESC LIMIT 1;");
342 if($ret_img0&&mysql_num_rows($ret_img0))
343 { $a_img0=mysql_fetch_assoc($ret_img0);
344
345 $image_foto=$a_img0['image'];
346 $PUTH_foto=$GLOBALS[PUTH_items];
347 $size=getimagesize($PUTH_foto.$image_foto);
348 $image_foto_width = 80;
349 $image_foto_height = round(($size[1]*$image_foto_width)/$size[0]);
350
351 $path=$PUTH_foto.str_replace('.',"_{$image_foto_width}x{$image_foto_height}.",$image_foto);
352 if(!is_file($path)) if(!copy('http://'.$_SERVER[HTTP_HOST].'/'.'functions/thumb.php?filename='.$PUTH_foto.$image_foto.'&width='.$image_foto_width.'&height='.$image_foto_height,$path)) $path="functions/thumb.php?filename=".$PUTH_foto.$image_foto."&width=".$image_foto_width.'&height='.$image_foto_height;
353
354 $puth_to_image0=$path;
355
356 } else $puth_to_image0='images/nofoto7070.gif';
357
358 $titlefoto0=str_replace('"',"'",stripslashes($subj['title']));
359 $link_items="/{$parent}/1/".($subj['text_id']?$subj['text_id']:$subj['id']);
360
361 $ret="<div style=\"display:table;\"><div style=\"float:left;border:2px solid #fff;\"><div style=\"background:#fff;padding:3px;\"><a href=\"{$link_items}#fullscreen\"><img src=\"/{$puth_to_image0}\" class=\"opacity\" title=\"{$titlefoto0}\" alt=\"{$titlefoto0}\" style=\"width:80px;\"></a></div></div></div>".$ret;
362
363 }
364 }
365
366
367 // -----------------------------
368
369
370 $ret_img0=mysql_query("SELECT * FROM `{$GLOBALS['TABLE_foto']}` WHERE `parent`='{$parent}-{$id}' AND `image`!='' ORDER BY `pornfoto` DESC LIMIT 1;");
371 if($ret_img0&&mysql_num_rows($ret_img0))
372 { $a_img0=mysql_fetch_assoc($ret_img0);
373
374 $image_foto=$a_img0['image'];
375 $PUTH_foto=$GLOBALS[PUTH_items];
376 $size=getimagesize($PUTH_foto.$image_foto);
377 $image_foto_width = 80;
378 $image_foto_height = round(($size[1]*$image_foto_width)/$size[0]);
379
380 $path=$PUTH_foto.str_replace('.',"_{$image_foto_width}x{$image_foto_height}.",$image_foto);
381 if(!is_file($path)) if(!copy('http://'.$_SERVER[HTTP_HOST].'/'.'functions/thumb.php?filename='.$PUTH_foto.$image_foto.'&width='.$image_foto_width.'&height='.$image_foto_height,$path)) $path="functions/thumb.php?filename=".$PUTH_foto.$image_foto."&width=".$image_foto_width.'&height='.$image_foto_height;
382
383 $puth_to_image0=$path;
384
385 $titlefoto0=str_replace('"',"'",stripslashes($a_img0['titlefoto']));
386 } else $puth_to_image0='images/nofoto7070.gif';
387
388 $titlefoto0=str_replace('"',"'",stripslashes($a['title']));
389 $ret.="<div style=\"display:table;\"><div style=\"float:left;border:2px solid #ccc;\"><div style=\"background:#fff;padding:3px;\"><img src=\"/{$puth_to_image0}\" title=\"{$titlefoto0}\" alt=\"{$titlefoto0}\" style=\"width:80px;\"></div></div></div>";
390
391
392 // -----------------------------
393
394
395 $ret_mysql=mysql_query("SELECT * FROM `{$GLOBALS['TABLE_items']}` WHERE `parent`='{$parent}' AND `porn`<'{$porn}' ORDER BY `porn` DESC LIMIT 15;");
396 $count = mysql_num_rows($ret_mysql);
397 if ($count)
398 { for ($i=0; $i<$count; $i++)
399 { $subj=mysql_fetch_array($ret_mysql);
400
401 $ret_img0=mysql_query("SELECT * FROM `{$GLOBALS['TABLE_foto']}` WHERE `parent`='{$parent}-".$subj['id']."' AND `image`!='' ORDER BY `pornfoto` DESC LIMIT 1;");
402 if($ret_img0&&mysql_num_rows($ret_img0))
403 { $a_img0=mysql_fetch_assoc($ret_img0);
404
405 $image_foto=$a_img0['image'];
406 $PUTH_foto=$GLOBALS[PUTH_items];
407 $size=getimagesize($PUTH_foto.$image_foto);
408 $image_foto_width = 80;
409 $image_foto_height = round(($size[1]*$image_foto_width)/$size[0]);
410
411 $path=$PUTH_foto.str_replace('.',"_{$image_foto_width}x{$image_foto_height}.",$image_foto);
412 if(!is_file($path)) if(!copy('http://'.$_SERVER[HTTP_HOST].'/'.'functions/thumb.php?filename='.$PUTH_foto.$image_foto.'&width='.$image_foto_width.'&height='.$image_foto_height,$path)) $path="functions/thumb.php?filename=".$PUTH_foto.$image_foto."&width=".$image_foto_width.'&height='.$image_foto_height;
413
414 $puth_to_image0=$path;
415
416 } else $puth_to_image0='images/nofoto7070.gif';
417
418 $titlefoto0=str_replace('"',"'",stripslashes($subj['title']));
419 $link_items="/{$parent}/1/".($subj['text_id']?$subj['text_id']:$subj['id']);
420
421 $ret=$ret."<div style=\"display:table;\"><div style=\"float:left;border:2px solid #fff;\"><div style=\"background:#fff;padding:3px;\"><a href=\"{$link_items}#fullscreen\"><img src=\"/{$puth_to_image0}\" class=\"opacity\" title=\"{$titlefoto0}\" alt=\"{$titlefoto0}\" style=\"width:80px;\"></a></div></div></div>";
422
423 }
424 }
425
426 return $ret;
427
428
429 }
430 */
431
432
433function get_me_name_project($id) {
434 global $TABLE_sup_projects;
435
436 $name = '';
437 $id = round($id);
438
439 $result = mysql_query("SELECT * FROM `{$TABLE_sup_projects}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
440 if (mysql_num_rows($result)) {
441 $subj = mysql_fetch_array($result);
442 $name = trim($subj['name']);
443 }
444
445 return $name;
446}
447
448function get_me_account_project_by_id_project($id) {
449 global $TABLE_sup_projects;
450
451 $account = '';
452 $id = round($id);
453
454 $result = mysql_query("SELECT * FROM `{$TABLE_sup_projects}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
455 if (mysql_num_rows($result)) {
456 $subj = mysql_fetch_array($result);
457 $account = trim($subj['account']);
458 }
459
460 return $account;
461}
462
463function get_me_deadline_project($id) {
464 global $TABLE_sup_projects;
465
466 $deadline = '';
467 $id = round($id);
468
469 $result = mysql_query("SELECT * FROM `{$TABLE_sup_projects}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
470 if (mysql_num_rows($result)) {
471 $subj = mysql_fetch_array($result);
472 $deadline = trim($subj['deadline']);
473 }
474
475 return $deadline;
476}
477
478function get_me_id_project_by_id_files_project($id_files_projects) {
479 global $TABLE_sup_files_projects;
480
481 $id_project = '';
482 $id_files_projects = round($id_files_projects);
483
484 $result = mysql_query("SELECT * FROM `{$TABLE_sup_files_projects}` WHERE `id`='{$id_files_projects}';") or die(errorDiv(mysql_error()));
485 if (mysql_num_rows($result)) {
486 $subj = mysql_fetch_array($result);
487 $id_project = trim($subj['id_project']);
488 }
489
490 return $id_project;
491}
492
493function get_me_position_equipment_by_id_equipment($id) {
494 global $TABLE_sup_equipment;
495
496 $position = 0;
497 $id = round($id);
498
499 $result = mysql_query("SELECT * FROM `{$TABLE_sup_equipment}` WHERE 1 /* AND `id_user_del`=0 */ AND `id`='{$id}';") or die(errorDiv(mysql_error()));
500 if (mysql_num_rows($result)) {
501 $subj = mysql_fetch_array($result);
502 $position = trim($subj['position']);
503 }
504
505 return $position;
506}
507
508function get_me_name_equipment_by_id_equipment($id) {
509 global $TABLE_sup_equipment;
510
511 $name = '';
512 $id = round($id);
513
514 $result = mysql_query("SELECT * FROM `{$TABLE_sup_equipment}` WHERE 1 /* AND `id_user_del`=0 */ AND `id`='{$id}';") or die(errorDiv(mysql_error()));
515 if (mysql_num_rows($result)) {
516 $subj = mysql_fetch_array($result);
517 $name = trim($subj['name']);
518 }
519
520 return $name;
521}
522
523function get_me_kprepare_equipment_by_id_equipment($id) {
524 global $TABLE_sup_equipment;
525
526 $kprepare = 0;
527 $id = round($id);
528
529 $result = mysql_query("SELECT * FROM `{$TABLE_sup_equipment}` WHERE 1 /* AND `id_user_del`=0 */ AND `id`='{$id}';") or die(errorDiv(mysql_error()));
530 if (mysql_num_rows($result)) {
531 $subj = mysql_fetch_array($result);
532 $kprepare = trim($subj['kprepare']);
533 }
534
535 return $kprepare;
536}
537
538function get_me_workinghours_equipment_by_id_equipment($id) {
539 global $TABLE_sup_equipment;
540
541 $workinghours = 0;
542 $id = round($id);
543
544 $result = mysql_query("SELECT * FROM `{$TABLE_sup_equipment}` WHERE 1 /* AND `id_user_del`=0 */ AND `id`='{$id}';") or die(errorDiv(mysql_error()));
545 if (mysql_num_rows($result)) {
546 $subj = mysql_fetch_array($result);
547 $workinghours = trim($subj['workinghours']);
548 }
549
550 return $workinghours;
551}
552
553function get_me_name_source_by_id_source($id) {
554 global $TABLE_sup_sources;
555
556 $name = '';
557 $id = round($id);
558
559 $result = mysql_query("SELECT * FROM `{$TABLE_sup_sources}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
560 if (mysql_num_rows($result)) {
561 $subj = mysql_fetch_array($result);
562 $name = trim($subj['name']);
563 }
564
565 return $name;
566}
567
568function get_me_date_storage_period_for_project_by_id($id) // определяем по id проекта дату, до которой заказ будет храниться, относительно даты, когда заказу был проставлен статус "принят, ждем клиента"
569{
570 global $TABLE_sup_projects;
571
572 $date = '';
573 $id = round($id);
574
575 $result = mysql_query("SELECT * FROM `{$TABLE_sup_projects}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
576 if (mysql_num_rows($result)) {
577 $subj = mysql_fetch_array($result);
578 $date = $subj['accepted'];
579 }
580
581 if (round($date) && round(STORAGEPERIOD)) {
582 $accepted = str_replace(array(' ', ':'), '-', $date);
583 $accepted_ar = explode('-', $accepted);
584 $date = date('d.m.Y', mktime(23, 59, 59, $accepted_ar[1], $accepted_ar[2] + STORAGEPERIOD, $accepted_ar[0]));
585 }
586 else {
587 $date = 'Не определен';
588 }
589
590 return $date;
591}
592
593/*
594 function get_me_adress_operator($id)
595 { // возвращаем адрес нахождения исполнителя
596 return "адрес";
597 }
598 */
599
600function get_me_name_user_by_id_user($id) {
601 static $name;
602
603 $id = (int) $id;
604
605 if (!isset($name[$id])) {
606 global $TABLE_sup_users;
607
608 if (!$id) {
609 return 'НЕ УКАЗАН';
610 }
611
612 $n = '';
613
614 $result = mysql_query("SELECT `name`, `surname` FROM `{$TABLE_sup_users}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
615
616 $subj = mysql_fetch_array($result);
617
618 if (is_array($subj) && array_key_exists('name', $subj) && array_key_exists('surname', $subj)) {
619 $n = trim($subj['name'] . ' ' . $subj['surname']);
620 }
621
622 if (empty($n)) {
623 $n = 'Админ';
624 }
625
626 $name[$id] = $n;
627 }
628
629 return $name[$id];
630}
631
632function get_me_start_workday_user_by_id_user($id) {
633 global $TABLE_sup_users;
634
635 $id = round($id);
636 if (!$id) {
637 return 'НЕ УКАЗАН';
638 }
639
640 unset($start_workday);
641
642 $result = mysql_query("SELECT * FROM `{$TABLE_sup_users}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
643 if (mysql_num_rows($result)) {
644 $subj = mysql_fetch_array($result);
645 $start_workday = trim($subj['start_workday']);
646 }
647
648 return $start_workday;
649}
650
651function get_me_all_count_orders_client_by_id_user($id) {
652 global $TABLE_sup_users;
653
654 $id = round($id);
655 if (!$id) {
656 return 'НЕ УКАЗАН';
657 }
658
659 $all_count_orders = '';
660
661 $result = mysql_query("SELECT * FROM `{$TABLE_sup_users}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
662 if (mysql_num_rows($result)) {
663 $subj = mysql_fetch_array($result);
664 $all_count_orders = round($subj['all_count_orders']);
665 }
666
667 return $all_count_orders;
668}
669
670function get_me_only_name_user_by_id_user($id) {
671 global $TABLE_sup_users;
672
673 $id = round($id);
674
675 if (!$id) {
676 return 'НЕ УКАЗАН';
677 }
678
679 $name = '';
680
681 $result = mysql_query("SELECT * FROM `{$TABLE_sup_users}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
682 if (mysql_num_rows($result)) {
683 $subj = mysql_fetch_array($result);
684 $name = trim($subj['name']);
685 }
686
687 return $name;
688}
689
690function get_me_type_user_by_id_user($id) {
691 global $TABLE_sup_users;
692
693 $id = round($id);
694
695 $type = '';
696
697 $result = mysql_query("SELECT * FROM `{$TABLE_sup_users}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
698 if (mysql_num_rows($result)) {
699 $subj = mysql_fetch_array($result);
700 $type = $subj['type'];
701 }
702
703 return $type;
704}
705
706function get_me_id_user_by_id_ticket($id_ticket) {
707 global $TABLE_sup_tickets;
708
709 $id_ticket = round($id_ticket);
710
711 $email = '';
712
713 $result = mysql_query("SELECT * FROM `{$TABLE_sup_tickets}` WHERE `id`='{$id_ticket}';") or die(errorDiv(mysql_error()));
714 if (mysql_num_rows($result)) {
715 $subj = mysql_fetch_array($result);
716 $email = $subj['email'];
717 }
718
719 return get_me_id_user_by_email_user($email);
720}
721
722function get_me_patronymic_user_by_id_user($id) {
723 global $TABLE_sup_users;
724
725 $id = round($id);
726
727 $patronymic = '';
728
729 $result = mysql_query("SELECT * FROM `{$TABLE_sup_users}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
730 if (mysql_num_rows($result)) {
731 $subj = mysql_fetch_array($result);
732 $patronymic = trim($subj['patronymic']);
733 }
734
735 return $patronymic;
736}
737
738function get_me_discount_user_by_id_user($id) {
739 global $TABLE_sup_users;
740
741 $id = round($id);
742
743 $discount = '';
744
745 $result = mysql_query("SELECT * FROM `{$TABLE_sup_users}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
746 if (mysql_num_rows($result)) {
747 $subj = mysql_fetch_array($result);
748 $discount = $subj['discount'];
749 }
750
751 return $discount;
752}
753
754function get_me_special_user_by_id_user($id) {
755 global $TABLE_sup_users;
756
757 $id = round($id);
758
759 $special = '';
760
761 $result = mysql_query("SELECT * FROM `{$TABLE_sup_users}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
762 if (mysql_num_rows($result)) {
763 $subj = mysql_fetch_array($result);
764 $special = $subj['special'];
765 }
766
767 return $special;
768}
769
770function get_me_firm_user_by_id_user($id) {
771 global $TABLE_sup_users;
772
773 $id = round($id);
774
775 $firm = '';
776
777 $result = mysql_query("SELECT * FROM `{$TABLE_sup_users}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
778 if (mysql_num_rows($result)) {
779 $subj = mysql_fetch_array($result);
780 $firm = trim(decode_db($subj['firm']));
781 }
782
783 return $firm;
784}
785
786function get_me_id_user_operator_by_id_project($id) {
787 global $TABLE_sup_projects;
788
789 $id = round($id);
790
791 $id_user_operator = '';
792
793 $result = mysql_query("SELECT * FROM `{$TABLE_sup_projects}` WHERE `id`='{$id}' AND `id_user_del`='0';") or die(errorDiv(mysql_error()));
794 if (mysql_num_rows($result)) {
795 $subj = mysql_fetch_array($result);
796 $id_user_operator = trim($subj['id_user_operator']);
797 }
798
799 return $id_user_operator;
800}
801
802function get_me_datetime_start_by_id_project($id) {
803 global $TABLE_sup_projects;
804
805 $id = round($id);
806
807 $start = '';
808
809 $result = mysql_query("SELECT * FROM `{$TABLE_sup_projects}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
810 if (mysql_num_rows($result)) {
811 $subj = mysql_fetch_array($result);
812 $start = $subj['start'];
813 }
814
815 return $start;
816}
817
818function get_me_status_project_by_id_project($id) {
819 global $TABLE_sup_projects;
820
821 $id = round($id);
822
823 $status = '';
824
825 $result = mysql_query("SELECT * FROM `{$TABLE_sup_projects}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
826 if (mysql_num_rows($result)) {
827 $subj = mysql_fetch_array($result);
828 $status = trim($subj['status']);
829 }
830
831 return $status;
832}
833
834function get_me_visible_project_by_id_project($id) {
835 global $TABLE_sup_projects;
836
837 $id = round($id);
838
839 unset($visible);
840
841 $result = mysql_query("SELECT * FROM `{$TABLE_sup_projects}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
842 if (mysql_num_rows($result)) {
843 $subj = mysql_fetch_array($result);
844 $visible = trim($subj['visible']);
845 }
846
847 return $visible;
848}
849
850function get_me_title_file_by_id_file($id) {
851 $id = round($id);
852
853 $titlefile = '';
854
855 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_files']}` WHERE 1 AND `id_user_del`='0' AND `id`='{$id}';") or die(errorDiv(mysql_error()));
856 if (mysql_num_rows($result)) {
857 $subj = mysql_fetch_array($result);
858 $titlefile = trim($subj['titlefile']);
859 }
860
861 return $titlefile;
862}
863
864function get_answer() // вручную достаем error из адресной строки, т.к. $_GET[error] работает почему-то не всегда
865{
866 $answer = '';
867
868 if (strpos($_SERVER['REQUEST_URI'], 'answer=')) {
869 $answer = array_pop(explode('answer=', $_SERVER['REQUEST_URI']));
870 if (strpos($answer, '&')) {
871 $answer = array_shift(explode('&', $answer));
872 }
873 if (strpos($answer, '?')) {
874 $answer = array_shift(explode('?', $answer));
875 }
876 }
877
878 return $answer;
879}
880
881function preview_next_items() // достаем соседние товары для интернет-магазина
882{
883
884 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_files']}` WHERE 1 AND `id_user_del`='0' AND `id_user`=(SELECT `id` FROM `{$GLOBALS['TABLE_sup_users']}` WHERE 1 AND `name`!='' AND `patronymic`!='' AND `email_md5`=MD5('{$GLOBALS['login']}') AND `type`='5' LIMIT 1) AND `titlefile`!='' AND (`id`='{$GLOBALS['id_magazin_item']}' OR `titlefile`!='{$GLOBALS['titlefile_magazin_item']}') AND `id_label`!=0 AND `file_preview`!='' AND `file_preview_mini`!='' /* AND `file_cdr`!='' AND `file_dxf`!='' */ GROUP BY `titlefile` ASC;") or die(errorDiv(mysql_error()));
885 $count = mysql_num_rows($result);
886
887 $list_magazin_list = '';
888
889 # ФОРМИРУЕМ ЛЕНТУ
890 if ($count) {
891 for ($i = 1; $i <= $count; $i++) {
892 $subj = mysql_fetch_array($result);
893
894 $id_magazin_list = $subj['id'];
895 $text_id_magazin_list = $subj['text_id'];
896 $titlefile_magazin_list = $subj['titlefile'];
897 $pricefile_magazin_list = $subj['pricefile'];
898 $commentfile_magazin_list = $subj['commentfile'];
899 $file_preview_mini_magazin_list = $subj['file_preview_mini'];
900
901 if ($id_magazin_list == $GLOBALS['id_magazin_item']) {
902 $current_i = $i;
903 }
904
905 //if(!$current_i) { $float="left"; $larr="← "; $rarr=""; } else { $float="right"; $larr=""; $rarr=" →"; }
906 //$float="left";
907
908 $items[$i] = "<div><a class='h3' title='{$titlefile_magazin_list}' href='/internet-magazin/{$GLOBALS['login']}/{$text_id_magazin_list}.html'>" . $titlefile_magazin_list . "</a></div>";
909 $items[$i] .= "<div class='small'>" . $commentfile_magazin_list . " <b>" . $pricefile_magazin_list . " руб.</b></div>";
910 $items[$i] .= "<div style='float:left;border:1px solid #ccc;padding:3px;margin-top:5px;'><a href='/internet-magazin/{$GLOBALS['login']}/{$text_id_magazin_list}.html' title='{$titlefile_magazin_list}'><img src='https://" . HOST_SUP . "/" . $GLOBALS['PUTH_files'] . $file_preview_mini_magazin_list . "' title='{$titlefile_magazin_list}' style='width:150px;" . ($id_magazin_list == $GLOBALS['id_magazin_item'] ? 'opacity:0.35;' : '') . "' /></a></div>";
911
912 }
913
914 $count = count($items) + 1;
915 $items[$count] = "<div class='h3'> </div>";
916 $items[$count] .= "<div class='small'> </div>";
917 $items[$count] .= "<div style='border:1px solid #ccc;padding:3px;margin-top:5px;width:150px;height:140px;text-align:center;'><br /><br /><br /><a class='h3' href='/internet-magazin/{$GLOBALS['login']}.html' title='{$titlefile_magazin_list}'>Вернуться в раздел</a></div>";
918
919 }
920
921 $ret = "<span class='gray'>Смотрите также:</span> <table border='0' cellspacing='0' cellpadding='0' style='margin-top:10px;width:100%;'><tr><td style='width:25%;'>";
922 if (isset($current_i)) {
923 $ret .= isset($items[$current_i]) ? $items[$current_i] : '';
924 }
925 $ret .= "</td><td style='width:25%;'>";
926 if (isset($current_i)) {
927 $ret .= isset($items[$current_i + 1]) ? $items[$current_i + 1] : '';
928 }
929 $ret .= "</td><td style='width:25%;'>";
930 if (isset($current_i)) {
931 $ret .= isset($items[$current_i + 2]) ? $items[$current_i + 2] : '';
932 }
933 $ret .= "</td><td style='width:25%;'>";
934 if (isset($current_i)) {
935 $ret .= isset($items[$current_i + 3]) ? $items[$current_i + 3] : '';
936 }
937 $ret .= "</td></tr></table>";
938
939 return $ret;
940}
941
942function get_me_id_user_manager_by_id_project($id) {
943 global $TABLE_sup_projects;
944
945 $id = round($id);
946
947 $id_user_manager = '';
948
949 $result = mysql_query("SELECT * FROM `{$TABLE_sup_projects}` WHERE `id`='{$id}' AND `id_user_del`='0';") or die(errorDiv(mysql_error()));
950 if (mysql_num_rows($result)) {
951 $subj = mysql_fetch_array($result);
952 $id_user_manager = trim($subj['id_user_manager']);
953 }
954
955 return $id_user_manager;
956}
957
958function get_me_name_user_by_email_user($email) {
959 $email = str_replace(array(
960 '"',
961 "'",
962 '`',
963 "/",
964 "\\",
965 '=',
966 '?',
967 '&',
968 "#",
969 ':',
970 ' ',
971 ), '', $email);
972
973 $name = '';
974
975 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_users']}` WHERE `email_md5`=MD5('{$email}');") or die(errorDiv(mysql_error()));
976 if (mysql_num_rows($result)) {
977 $subj = mysql_fetch_array($result);
978 $name = trim($subj['name']);
979 }
980
981 return $name;
982}
983
984function get_me_surname_user_by_email_user($email) {
985 $email = str_replace(array(
986 '"',
987 "'",
988 '`',
989 "/",
990 "\\",
991 '=',
992 '?',
993 '&',
994 "#",
995 ':',
996 ' ',
997 ), '', $email);
998
999 $surname = '';
1000
1001 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_users']}` WHERE `email_md5`=MD5('{$email}');") or die(errorDiv(mysql_error()));
1002 if (mysql_num_rows($result)) {
1003 $subj = mysql_fetch_array($result);
1004 $surname = trim($subj['surname']);
1005 }
1006
1007 return $surname;
1008}
1009
1010function get_me_patronymic_user_by_email_user($email) {
1011 $email = str_replace(array(
1012 '"',
1013 "'",
1014 '`',
1015 "/",
1016 "\\",
1017 '=',
1018 '?',
1019 '&',
1020 "#",
1021 ':',
1022 ' ',
1023 ), '', $email);
1024
1025 $patronymic = '';
1026
1027 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_users']}` WHERE `email_md5`=MD5('{$email}');") or die(errorDiv(mysql_error()));
1028 if (mysql_num_rows($result)) {
1029 $subj = mysql_fetch_array($result);
1030 $patronymic = trim($subj['patronymic']);
1031 }
1032
1033 return $patronymic;
1034}
1035
1036function get_me_type_user_by_email_user($email) {
1037 $email = str_replace(array(
1038 '"',
1039 "'",
1040 '`',
1041 "/",
1042 "\\",
1043 '=',
1044 '?',
1045 '&',
1046 "#",
1047 ':',
1048 ' ',
1049 ), '', $email);
1050
1051 $type = '';
1052
1053 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_users']}` WHERE `email_md5`=MD5('{$email}');") or die(errorDiv(mysql_error()));
1054 if (mysql_num_rows($result)) {
1055 $subj = mysql_fetch_array($result);
1056 $type = trim($subj['type']);
1057 }
1058
1059 return $type;
1060}
1061
1062function get_me_del_user_by_email_user($email) /* функция показывающая, что пользователь удален (нужен для вывода интернет-магазина) */ {
1063 $email = str_replace(array(
1064 '"',
1065 "'",
1066 '`',
1067 "/",
1068 "\\",
1069 '=',
1070 '?',
1071 '&',
1072 "#",
1073 ':',
1074 ' ',
1075 ), '', $email);
1076
1077 $type = '';
1078
1079 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_users']}` WHERE `email_md5`=MD5('{$email}');") or die(errorDiv(mysql_error()));
1080 if (mysql_num_rows($result)) {
1081 $subj = mysql_fetch_array($result);
1082 $del = trim($subj['id_user_del']);
1083 }
1084
1085 return $del ? 1 : 0;
1086}
1087
1088function get_me_not_use_for_magazin_user_by_email_user($email) /* функция показывающая, что пользователь удален (нужен для вывода интернет-магазина) */ {
1089 $email = str_replace(array(
1090 '"',
1091 "'",
1092 '`',
1093 "/",
1094 "\\",
1095 '=',
1096 '?',
1097 '&',
1098 "#",
1099 ':',
1100 ' ',
1101 ), '', $email);
1102
1103 $type = '';
1104
1105 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_users']}` WHERE `email_md5`=MD5('{$email}');") or die(errorDiv(mysql_error()));
1106 if (mysql_num_rows($result)) {
1107 $subj = mysql_fetch_array($result);
1108 $del = trim($subj['not_use_for_magazin']);
1109 }
1110
1111 return $del ? 1 : 0;
1112}
1113
1114function get_me_email_user_by_id_user($id) {
1115 global $TABLE_sup_users;
1116
1117 $email = '';
1118 $id = round($id);
1119
1120 $result = mysql_query("SELECT * FROM `{$TABLE_sup_users}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
1121 if (mysql_num_rows($result)) {
1122 $subj = mysql_fetch_array($result);
1123 $email = decode_db(trim($subj['email']));
1124 }
1125
1126 return $email;
1127}
1128
1129function get_me_phone_user_by_id_user($id) {
1130 global $TABLE_sup_users;
1131
1132 $phone = '';
1133 $id = round($id);
1134
1135 $result = mysql_query("SELECT * FROM `{$TABLE_sup_users}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
1136 if (mysql_num_rows($result)) {
1137 $subj = mysql_fetch_array($result);
1138 $phone = decode_db(trim($subj['phone1']));
1139 }
1140
1141 return $phone;
1142}
1143
1144function get_me_name_user_by_id_project($id) /// получаем name клиента заказавшего этот проект с $id
1145{
1146 global $TABLE_sup_projects;
1147
1148 $name = '';
1149 $id = round($id);
1150
1151 $result = mysql_query("SELECT `id_user` FROM `{$TABLE_sup_projects}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
1152
1153 if (mysql_num_rows($result)) {
1154 $subj = mysql_fetch_array($result);
1155 $name = get_me_name_user_by_id_user($subj['id_user']);
1156 }
1157
1158 return $name;
1159}
1160
1161function get_me_name_manager_by_id_project($id) /// получаем name менеджера исполняющего этот проект с $id
1162{
1163 global $TABLE_sup_projects;
1164
1165 $name = '';
1166 $id = round($id);
1167
1168 $result = mysql_query("SELECT `id_user_manager` FROM `{$TABLE_sup_projects}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
1169
1170 if (mysql_num_rows($result)) {
1171 $subj = mysql_fetch_array($result);
1172 $name = get_me_name_user_by_id_user($subj['id_user_manager']);
1173 }
1174
1175 return $name;
1176}
1177
1178function get_me_id_manager_by_id_project($id) /// получаем name менеджера исполняющего этот проект с $id
1179{
1180 global $TABLE_sup_projects;
1181
1182
1183 $id = round($id);
1184
1185 $result = mysql_query("SELECT `id_user_manager` FROM `{$TABLE_sup_projects}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
1186
1187 if (mysql_num_rows($result)) {
1188 $subj = mysql_fetch_array($result);
1189 $id = $subj['id_user_manager'];
1190 }
1191
1192 return $id;
1193}
1194
1195function get_me_name_operator_by_id_project($id) /// получаем name оператора исполняющего этот проект с $id
1196{
1197 global $TABLE_sup_projects;
1198
1199 $name = '';
1200 $id = round($id);
1201
1202 $result = mysql_query("SELECT `id_user_operator` FROM `{$TABLE_sup_projects}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
1203
1204 if (mysql_num_rows($result)) {
1205 $subj = mysql_fetch_array($result);
1206 $name = get_me_name_user_by_id_user($subj['id_user_operator']);
1207 }
1208
1209 return $name;
1210}
1211
1212function get_me_id_user_by_id_project($id) /// получаем id клиента заказавшего этот проект с $id
1213{
1214 global $TABLE_sup_projects;
1215
1216 $name = '';
1217 $id = round($id);
1218
1219 $result = mysql_query("SELECT `id_user` FROM `{$TABLE_sup_projects}` WHERE `id`='{$id}' AND `id_user_del`='0';") or die(errorDiv(mysql_error()));
1220
1221 if (mysql_num_rows($result)) {
1222 $subj = mysql_fetch_array($result);
1223 $name = $subj['id_user'];
1224 }
1225
1226 return $name;
1227}
1228
1229function get_me_name_label($id) {
1230 global $TABLE_sup_label;
1231
1232 $name = '';
1233 $id = round($id);
1234
1235 $result = mysql_query("SELECT `name` FROM `{$TABLE_sup_label}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
1236
1237 if (mysql_num_rows($result)) {
1238 $subj = mysql_fetch_array($result);
1239 $name = $subj['name'];
1240 }
1241
1242 return $name;
1243}
1244
1245function get_me_name_user_type($id) {
1246 switch ($id) {
1247 case '1':
1248 return 'Админ';
1249 break;
1250 case '2':
1251 return 'Менеджер';
1252 break;
1253 case '3':
1254 return 'Исполнитель';
1255 break;
1256 case '4':
1257 return 'Клиент';
1258 break;
1259 case '5':
1260 return 'Интернет-магазин';
1261 break;
1262 }
1263
1264 return '';
1265}
1266
1267function get_month($j) {
1268 switch ($j) {
1269 case '1':
1270 return 'январь';
1271 break;
1272 case '2':
1273 return 'февраль';
1274 break;
1275 case '3':
1276 return 'март';
1277 break;
1278 case '4':
1279 return 'апрель';
1280 break;
1281 case '5':
1282 return 'май';
1283 break;
1284 case '6':
1285 return 'июнь';
1286 break;
1287 case '7':
1288 return 'июль';
1289 break;
1290 case '8':
1291 return 'август';
1292 break;
1293 case '9':
1294 return 'сентябрь';
1295 break;
1296 case '10':
1297 return 'октябрь';
1298 break;
1299 case '11':
1300 return 'ноябрь';
1301 break;
1302 case '12':
1303 return 'декабрь';
1304 break;
1305 }
1306
1307 return 'ОШИБКА';
1308}
1309
1310function total_money_only_cash_positiv($date_bookkeeping, $type, $id_user_manager = 0) // вычисление выручки с возратом ТОЛЬКО суммы приходов
1311{
1312 global $TABLE_sup_bookkeeping, $TABLE_sup_projects;
1313
1314 switch ($type) {
1315 case 'day':
1316 $period = $date_bookkeeping;
1317 break;
1318 case 'month':
1319 $period = explode('-', $date_bookkeeping);
1320 $period = $period[0] . '-' . $period[1] . '-__';
1321 break;
1322 case 'year':
1323 $period = explode('-', $date_bookkeeping);
1324 $period = $period[0] . '-__-__';
1325 break;
1326 }
1327
1328 $id_user_manager = round($id_user_manager);
1329
1330 if ($id_user_manager == 1) {
1331 $id_user_manager = 0;
1332 }
1333
1334 $result = mysql_query("SELECT * FROM `{$TABLE_sup_bookkeeping}` WHERE 1 AND `id_user_del`=0 " . ($id_user_manager ? " AND `id_project` IN (SELECT `id` FROM `{$TABLE_sup_projects}` WHERE `id_user_manager`='{$id_user_manager}') " : '') . " AND `date` LIKE '{$period}';") or die(errorDiv(mysql_error()));
1335 $count = mysql_num_rows($result);
1336
1337 $positive = 0;
1338 # ФОРМИРУЕМ ЛЕНТУ
1339 if ($count) {
1340 for ($i = 0; $i < $count; $i++) {
1341 $subj = mysql_fetch_array($result);
1342 if ($subj['sum'] > 0) {
1343 $positive += $subj['sum'];
1344 }
1345 }
1346 }
1347
1348 return $positive;
1349}
1350
1351function get_me_id_user_by_email_user($email) {
1352 //include_once "modules/connect_to_sup_db.php";
1353
1354 $id = '';
1355 $email = str_replace(array(
1356 '"',
1357 "'",
1358 '`',
1359 "/",
1360 "\\",
1361 '=',
1362 '?',
1363 '&',
1364 "#",
1365 ':',
1366 ' ',
1367 ), '', $email);
1368
1369 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_users']}` WHERE `email_md5`=MD5('{$email}') AND `id_user_del`='0';") or die(errorDiv(mysql_error()));
1370 if (mysql_num_rows($result)) {
1371 $subj = mysql_fetch_array($result);
1372 $id = trim($subj['id']);
1373 }
1374
1375 return $id;
1376}
1377
1378function get_me_id_label_by_id_file($id_file) {
1379 global $TABLE_sup_files;
1380 //include "modules/connect_to_sup_db.php";
1381
1382 $id_label = '';
1383 $id_file = round($id_file);
1384
1385 $result = mysql_query("SELECT * FROM `{$TABLE_sup_files}` WHERE `id`='{$id_file}' AND `id_user_del`='0';") or die(errorDiv(mysql_error()));
1386 if (mysql_num_rows($result)) {
1387 $subj = mysql_fetch_array($result);
1388 $id_label = trim($subj['id_label']);
1389 }
1390
1391 return $id_label;
1392}
1393
1394/*
1395 function get_me_id_last_manager_by_email_user($email)
1396 {
1397 //include_once "modules/connect_to_sup_db.php";
1398
1399 $id='';
1400 $email=str_replace(array('"',"'",'`',"/","\\",'=','?','&',"#",':',' '),'',$email);
1401
1402 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_users']}` WHERE `email_md5`=MD5('{$email}') AND `id_user_del`='0';") or die(errorDiv(mysql_error()));
1403 if (mysql_num_rows($result))
1404 { $subj=mysql_fetch_array($result);
1405 $id=trim($subj['id_last_manager']);
1406 }
1407
1408 return $id;
1409 }
1410 */
1411
1412function total_money_only_cash_negativ($date_bookkeeping, $type, $id_user_manager = 0) // вычисление выручки с возратом ТОЛЬКО суммы расходов
1413{
1414 global $TABLE_sup_bookkeeping, $TABLE_sup_projects;
1415
1416 switch ($type) {
1417 case 'day':
1418 $period = $date_bookkeeping;
1419 break;
1420 case 'month':
1421 $period = explode('-', $date_bookkeeping);
1422 $period = $period[0] . '-' . $period[1] . '-__';
1423 break;
1424 case 'year':
1425 $period = explode('-', $date_bookkeeping);
1426 $period = $period[0] . '-__-__';
1427 break;
1428 }
1429
1430 $id_user_manager = round($id_user_manager);
1431
1432 if ($id_user_manager) {
1433 $id_user_manager = 0;
1434 }
1435
1436 $result = mysql_query("SELECT * FROM `{$TABLE_sup_bookkeeping}` WHERE 1 AND `id_user_del`=0 " . ($id_user_manager ? " AND `id_project` IN (SELECT `id` FROM `{$TABLE_sup_projects}` WHERE `id_user_manager`='{$id_user_manager}') " : '') . " AND `date` LIKE '{$period}';") or die(errorDiv(mysql_error()));
1437 $count = mysql_num_rows($result);
1438
1439 $negative = 0;
1440 # ФОРМИРУЕМ ЛЕНТУ
1441 if ($count) {
1442 for ($i = 0; $i < $count; $i++) {
1443 $subj = mysql_fetch_array($result);
1444 if ($subj['sum'] < 0) {
1445 $negative += $subj['sum'];
1446 }
1447 }
1448 }
1449
1450 return $negative;
1451}
1452
1453function total_money($date_bookkeeping, $type, $id_user_manager = 0) // вычисление выручки
1454{
1455 global $TABLE_sup_bookkeeping, $TABLE_sup_projects;
1456
1457 switch ($type) {
1458 case 'day':
1459 $period = $date_bookkeeping;
1460 break;
1461 case 'month':
1462 $period = explode('-', $date_bookkeeping);
1463 $period = $period[0] . '-' . $period[1] . '-__';
1464 break;
1465 case 'year':
1466 $period = explode('-', $date_bookkeeping);
1467 $period = $period[0] . '-__-__';
1468 break;
1469 }
1470
1471 $id_user_manager = round($id_user_manager);
1472
1473 if ($id_user_manager == 1) {
1474 $id_user_manager = 0;
1475 }
1476
1477 $result = mysql_query("SELECT * FROM `{$TABLE_sup_bookkeeping}` WHERE 1 AND `id_user_del`=0 " . ($id_user_manager ? " AND `id_project` IN (SELECT `id` FROM `{$TABLE_sup_projects}` WHERE `id_user_manager`='{$id_user_manager}') " : '') . " AND `date` LIKE '{$period}';") or die(errorDiv(mysql_error()));
1478 $count = mysql_num_rows($result);
1479
1480 $positive = 0;
1481 $negative = 0;
1482 # ФОРМИРУЕМ ЛЕНТУ
1483 if ($count) {
1484 for ($i = 0; $i < $count; $i++) {
1485 $subj = mysql_fetch_array($result);
1486 $subj['sum'] > 0 ? $positive += $subj['sum'] : $negative += $subj['sum'];
1487 }
1488 }
1489
1490 $ret = "Приходы: " . addpoint($positive) . ' руб.';
1491 if ($negative) {
1492 $ret .= "<br />Расходы: " . addpoint($negative) . ' руб.';
1493 }
1494
1495 return $ret;
1496}
1497
1498function new_url_filter_label($id = 0) { // функция, формирующая строку GET запрос для фильтра меток в разделе ПРОЕКТЫ
1499
1500 $id = round($id);
1501 $a = '';
1502
1503 if ($id) {
1504 if (!$GLOBALS['GET_ids_label']) {
1505 return "&ids_label[]={$id}";
1506 }
1507 $ids_label = array_unique($GLOBALS['GET_ids_label']);
1508
1509 if (in_array($id, $ids_label)) {
1510 foreach ($ids_label as $key) {
1511 if ($id != $key) {
1512 $a .= "&ids_label[]={$key}";
1513 }
1514 } // если id есть в строке, то убираем
1515 }
1516 else {
1517 $ids_label[] = $id;
1518 foreach ($ids_label as $key) {
1519 $a .= "&ids_label[]={$key}";
1520 } // если id нет в строке, то добавляем
1521 }
1522 }
1523 else {
1524 if (!$GLOBALS['GET_ids_label']) {
1525 return '';
1526 }
1527
1528 $ids_label = array_unique($GLOBALS['GET_ids_label']);
1529 foreach ($ids_label as $key) {
1530 $a .= "&ids_label[]={$key}";
1531 }
1532 }
1533
1534 //$a.="&all=".$_GET[all];
1535
1536 return $a;
1537}
1538
1539function paid($id) {
1540 $id = round($id);
1541
1542 $sum = mysql_query("SELECT SUM(`sum`) FROM `{$GLOBALS['TABLE_sup_bookkeeping']}` WHERE 1 AND `id_user_del`=0 AND `id_project`='{$id}';") or die(errorDiv(mysql_error()));
1543 $ret = mysql_result($sum, 0);
1544
1545 return round($ret);
1546}
1547
1548function closed($id) {
1549 $id = round($id);
1550
1551 $status4050 = 0;
1552 $result0 = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_projects']}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
1553 $count0 = mysql_num_rows($result0);
1554 # ФОРМИРУЕМ ЛЕНТУ
1555 if ($count0) {
1556 $subj0 = mysql_fetch_array($result0);
1557 if (in_array($subj0['status'], array('40', '50'))) {
1558 $status4050 = 1;
1559 }
1560 }
1561
1562 return $status4050;
1563}
1564
1565/*
1566 function utf8_win($s)
1567 { $s=strtr($s, array ("\xD0\xB0"=>"а", "\xD0\x90"=>"А", "\xD0\xB1"=>"б", "\xD0\x91"=>"Б", "\xD0\xB2"=>"в", "\xD0\x92"=>"В", "\xD0\xB3"=>"г", "\xD0\x93"=>"Г", "\xD0\xB4"=>"д", "\xD0\x94"=>"Д", "\xD0\xB5"=>"е", "\xD0\x95"=>"Е", "\xD1\x91"=>"ё", "\xD0\x81"=>"Ё", "\xD0\xB6"=>"ж", "\xD0\x96"=>"Ж", "\xD0\xB7"=>"з", "\xD0\x97"=>"З", "\xD0\xB8"=>"и", "\xD0\x98"=>"И", "\xD0\xB9"=>"й", "\xD0\x99"=>"Й", "\xD0\xBA"=>"к", "\xD0\x9A"=>"К", "\xD0\xBB"=>"л", "\xD0\x9B"=>"Л", "\xD0\xBC"=>"м", "\xD0\x9C"=>"М", "\xD0\xBD"=>"н", "\xD0\x9D"=>"Н", "\xD0\xBE"=>"о", "\xD0\x9E"=>"О", "\xD0\xBF"=>"п", "\xD0\x9F"=>"П", "\xD1\x80"=>"р", "\xD0\xA0"=>"Р", "\xD1\x81"=>"с", "\xD0\xA1"=>"С", "\xD1\x82"=>"т", "\xD0\xA2"=>"Т", "\xD1\x83"=>"у", "\xD0\xA3"=>"У", "\xD1\x84"=>"ф", "\xD0\xA4"=>"Ф", "\xD1\x85"=>"х", "\xD0\xA5"=>"Х", "\xD1\x86"=>"ц", "\xD0\xA6"=>"Ц", "\xD1\x87"=>"ч", "\xD0\xA7"=>"Ч", "\xD1\x88"=>"ш", "\xD0\xA8"=>"Ш", "\xD1\x89"=>"щ", "\xD0\xA9"=>"Щ", "\xD1\x8A"=>"ъ", "\xD0\xAA"=>"Ъ", "\xD1\x8B"=>"ы", "\xD0\xAB"=>"Ы", "\xD1\x8C"=>"ь", "\xD0\xAC"=>"Ь", "\xD1\x8D"=>"э", "\xD0\xAD"=>"Э", "\xD1\x8E"=>"ю", "\xD0\xAE"=>"Ю", "\xD1\x8F"=>"я", "\xD0\xAF"=>"Я"));
1568 return $s;
1569 }
1570 function win_utf8($s)
1571 { $s=strtr($s, array ("а"=>"\xD0\xB0", "А"=>"\xD0\x90","б"=>"\xD0\xB1", "Б"=>"\xD0\x91", "в"=>"\xD0\xB2", "В"=>"\xD0\x92", "г"=>"\xD0\xB3", "Г"=>"\xD0\x93", "д"=>"\xD0\xB4", "Д"=>"\xD0\x94", "е"=>"\xD0\xB5", "Е"=>"\xD0\x95", "ё"=>"\xD1\x91", "Ё"=>"\xD0\x81", "ж"=>"\xD0\xB6", "Ж"=>"\xD0\x96", "з"=>"\xD0\xB7", "З"=>"\xD0\x97", "и"=>"\xD0\xB8", "И"=>"\xD0\x98", "й"=>"\xD0\xB9", "Й"=>"\xD0\x99", "к"=>"\xD0\xBA", "К"=>"\xD0\x9A", "л"=>"\xD0\xBB", "Л"=>"\xD0\x9B", "м"=>"\xD0\xBC", "М"=>"\xD0\x9C", "н"=>"\xD0\xBD", "Н"=>"\xD0\x9D", "о"=>"\xD0\xBE", "О"=>"\xD0\x9E", "п"=>"\xD0\xBF", "П"=>"\xD0\x9F", "р"=>"\xD1\x80", "Р"=>"\xD0\xA0", "с"=>"\xD1\x81", "С"=>"\xD0\xA1", "т"=>"\xD1\x82", "Т"=>"\xD0\xA2", "у"=>"\xD1\x83", "У"=>"\xD0\xA3", "ф"=>"\xD1\x84", "Ф"=>"\xD0\xA4", "х"=>"\xD1\x85", "Х"=>"\xD0\xA5", "ц"=>"\xD1\x86", "Ц"=>"\xD0\xA6", "ч"=>"\xD1\x87", "Ч"=>"\xD0\xA7", "ш"=>"\xD1\x88", "Ш"=>"\xD0\xA8", "щ"=>"\xD1\x89", "Щ"=>"\xD0\xA9", "ъ"=>"\xD1\x8A", "Ъ"=>"\xD0\xAA", "ы"=>"\xD1\x8B", "Ы"=>"\xD0\xAB", "ь"=>"\xD1\x8C", "Ь"=>"\xD0\xAC", "э"=>"\xD1\x8D", "Э"=>"\xD0\xAD", "ю"=>"\xD1\x8E", "Ю"=>"\xD0\xAE", "я"=>"\xD1\x8F", "Я"=>"\xD0\xAF"));
1572 return $s;
1573 }
1574*/
1575
1576function get_count_projects_by_id_user($id_user) // определяем у этого клиента только количество закрытых коммерческих проектов, без полуфабрикатов и отказников
1577{
1578 global $TABLE_sup_projects;
1579
1580 $id_user = round($id_user);
1581
1582 $count = mysql_query("SELECT COUNT(*) FROM `{$TABLE_sup_projects}` WHERE `id_user`='{$id_user}' AND `total_price`>0 AND `status`='40' AND `id_user_del`='0';") or die(errorDiv(mysql_error()));
1583 $count = mysql_result($count, 0);
1584
1585 return $count;
1586}
1587
1588function get_count_all_projects_by_id_user($id_user) // определяем у этого клиента только количество закрытых коммерческих проектов, без полуфабрикатов и отказников
1589{
1590 global $TABLE_sup_projects;
1591
1592 $id_user = round($id_user);
1593
1594 $count = mysql_query("SELECT COUNT(*) FROM `{$TABLE_sup_projects}` WHERE `id_user`='{$id_user}' AND `id_user_del`='0';") or die(errorDiv(mysql_error()));
1595 $count = mysql_result($count, 0);
1596
1597 return $count;
1598}
1599
1600function checkbalancesms($auth) // функция передачи сообщения
1601{
1602 list(, $value) = explode(';', @file_get_contents('https://api.smsfeedback.ru/messages/v2/balance/?login=' . LOGINSMS . '&password=' . PASSWORDSMS));
1603
1604 if (!$value) {
1605 return "<b class='small red'>Не удалось соединиться с сервером</div>";
1606 die();
1607 }
1608
1609 if ($value < 100) // смотрим, если баланс меньше 100 руб, выделяем красным и предлагаем пополнить баланс
1610 {
1611 echo "<span class='strong red'>{$value} руб.</span>";
1612 if ($auth == 1) {
1613 echo "<br><a class='red' href='https://www.smsfeedback.ru/users/invoices/addinvoiceform.php' target='_blank'>Пополнить баланс</a>";
1614 } // пополнить баланс предлагаем только админу, т.к. у менеджера не будет доступа к деньгам
1615 }
1616 else {
1617 echo $value . ' руб.';
1618 }
1619
1620}
1621
1622function get_me_email_status_user_by_id_user($id) {
1623 global $TABLE_sup_users;
1624
1625 $opt = '';
1626 $id = round($id);
1627
1628 $result = mysql_query("SELECT `email_status` FROM `{$TABLE_sup_users}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
1629 if (mysql_num_rows($result)) {
1630 $subj = mysql_fetch_array($result);
1631 $opt = round($subj['email_status']);
1632 }
1633
1634 return $opt;
1635}
1636
1637function get_me_sms_status_user_by_id_user($id) {
1638 global $TABLE_sup_users;
1639
1640 $opt = '';
1641 $id = round($id);
1642
1643 $result = mysql_query("SELECT `sms_status` FROM `{$TABLE_sup_users}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
1644 if (mysql_num_rows($result)) {
1645 $subj = mysql_fetch_array($result);
1646 $opt = round($subj['sms_status']);
1647 }
1648
1649 return $opt;
1650}
1651
1652function get_me_delivery_by_id_project($id_project) {
1653 global $TABLE_sup_projects;
1654
1655 $delivery = '';
1656 $id_project = round($id_project);
1657
1658 $result = mysql_query("SELECT `delivery` FROM `{$TABLE_sup_projects}` WHERE `id`='{$id_project}';") or die(errorDiv(mysql_error()));
1659 if (mysql_num_rows($result)) {
1660 $subj = mysql_fetch_array($result);
1661 $delivery = trim($subj['delivery']);
1662 }
1663
1664 return $delivery;
1665}
1666
1667function get_me_total_price_by_id_project($id_project) {
1668 global $TABLE_sup_projects;
1669
1670 $total_price = '';
1671 $id_project = round($id_project);
1672
1673 $result = mysql_query("SELECT `total_price` FROM `{$TABLE_sup_projects}` WHERE `id`='{$id_project}';") or die(errorDiv(mysql_error()));
1674 if (mysql_num_rows($result)) {
1675 $subj = mysql_fetch_array($result);
1676 $total_price = trim($subj['total_price']);
1677 }
1678
1679 return $total_price;
1680}
1681
1682function send_report_a_problem($id_project, $id_file, $status) // функция вызывается в скрипте ACCEPTFILE.php при установке проблемного статуса макету и оптравляет email-уведомление менеджеру этого проекта
1683{
1684
1685 $id_project = round($id_project);
1686 $id_file = round($id_file);
1687 $status = round($status);
1688
1689 $problem = '';
1690 if ($status == 21) {
1691 $problem = 'Трудности с выполнением';
1692 }
1693 if ($status == 22) {
1694 $problem = 'Нехватка материала';
1695 }
1696
1697 $name_manager = get_me_name_manager_by_id_project($id_project); // получаем id клиента по id проекта
1698
1699 $charset = "windows-1251"; // устанавливаем кодировку
1700 $type = "text/html"; // устанавливаем тип сообщения
1701
1702 $to_email = trim(readsql_system("emailfeedback")); // Почта наша рабочая, на которую отправляются письма
1703 $to_name = trim($name_manager); // Имя клиента
1704 $to_name0 = $to_name;
1705 if (check_rus($to_name) == TRUE) {
1706 $to_name = base64_encode($to_name);
1707 $to_name = "=?{$charset}?B?{$to_name}?=";
1708 } // Кодируем имя клиента
1709
1710 $time = time() . mt_rand(100000, 999999);
1711
1712 $from_email = "bot-project{$id_project}@optima-cut.ru"; // Наша почта
1713 $from_name = 'Optima-Cut.ru'; // Наше Имя
1714 if (check_rus($from_name) == TRUE) {
1715 $from_name = base64_encode($from_name);
1716 $from_name = "=?{$charset}?B?{$from_name}?=";
1717 } // Кодируем наше имя
1718
1719 $subj0 = "Менеджеру " . strtoupper_m($to_name0) . ". \"{$problem}\" в заказе №{$id_project}";
1720 if (check_rus($subj0) == TRUE) {
1721 $subj0 = base64_encode($subj0);
1722 $subj0 = "=?{$charset}?B?{$subj0}?=";
1723 } // Кодируем тему сообщения
1724
1725 $body0 = "В Вашем <a href=\"//" . HOST_SUP . "/?p=projects&id={$id_project}\" target='_blank'>заказе №{$id_project}</a> макету <b>\"" . get_me_title_file_by_id_file($id_file) . "\"</b> установлен статус <b>\"{$problem}\"</b>.<br /><br />";
1726
1727
1728 // Указываем заголовки
1729 $headers = "MIME-Version: 1.0\n";
1730 $headers .= "Date: " . date("D, d M Y H:i:s") . " +0300\n";
1731 $headers .= "To: {$to_name} <{$to_email}>\n";
1732 // $headers .= "Cc: <".readsql_system("boss_email").">\n"; // отправляем копию управляющему
1733 $headers .= "From: {$from_name} <noreply@optima-cut.ru>\n";
1734 $headers .= "Reply-To: {$from_name} <{$from_email}>\n";
1735 $headers .= "Content-Type: {$type}; charset={$charset}\n";
1736 $headers .= "Content-Transfer-Encoding: 8bit\n";
1737 $headers .= "X-Mailer: 1 " . HOST_SUP . " WWW.OPTIMA-CUT.RU for {$to_email}";
1738 // / Указываем заголовки
1739
1740 @mail($to_email, $subj0, $body0, $headers); // Отправляем письмо
1741
1742}
1743
1744function send_report($id, $auto = FALSE) {
1745 global $TABLE_sup_users, $TABLE_sup_projects, $time_response;
1746
1747 $id = round($id);
1748
1749 $status = '# ' . date("d.m.Y H:i:s") . ($auto ? ' - ROBOT' : '') . ":\n";
1750
1751 $id_user = get_me_id_user_by_id_project($id); // получаем id клиента по id проекта
1752 $balance = get_me_total_price_by_id_project($id) - paid($id); // получаем остаток оплаты по проекту
1753
1754 $result = mysql_query("SELECT * FROM `{$TABLE_sup_users}` WHERE 1 AND `id_user_del`=0 AND `id`='{$id_user}';") or die(errorDiv(mysql_error())); // получаем данные клиента
1755 if (mysql_num_rows($result)) {
1756 $subj = mysql_fetch_array($result);
1757
1758 if (get_me_email_status_user_by_id_user($id_user)) // проверяем включена ли настройка получения email уведомлений
1759 { // здесь мы будем формировать и отправлять уведомительное письмо
1760
1761 // смотрим, прописаны ли настройки smtp для отправки писем через систему
1762 if (readsql_system("smtp_host") && readsql_system("smtp_login") && readsql_system("smtp_pass")) {
1763 $smtp = 1;
1764 }
1765 else {
1766 $smtp = 0;
1767 }
1768
1769 $result = '';
1770
1771 if ($smtp) {
1772 // достаем данные для доступа
1773 $smtp_host = "ssl://smtp." . readsql_system('smtp_host'); //gmail.com
1774 $smtp_pass = decode_db_password(readsql_system('smtp_pass'));
1775 $smtp_login = readsql_system('smtp_login');
1776
1777 $charset = "utf-8"; // устанавливаем кодировку
1778 $type = "text/html"; // устанавливаем тип сообщения
1779
1780 $to_email = decode_db(trim($subj['email'])); // Почта клиента
1781 if (strpos(' ' . $to_email, 'user_temporary_name')) {
1782 $to_email = 'notice@optima-cut.ru';
1783 }
1784 /* !!!!!!!!!! */ /* $to_email = 'notice@optima-cut.ru'; */
1785 $to_name = trim($subj['name']); // Имя клиента
1786
1787 $from_email = readsql_system("emailfeedback") ? readsql_system("emailfeedback") : "noreply@optima-cut.ru"; // Наша почта
1788 $from_name = readsql_system("name_company"); // Наше Имя
1789
1790 $subj0 = readsql_system("name_company") . ". Ваш заказ №{$id} готов.";
1791
1792 $body0 = "Ваш <a href=\"https://" . HOST_SUP . "/client_version_project.php?id={$id}&secure=" . md5($id . SALT) . "\">заказ №{$id}</a> готов.<br /><br />";
1793
1794 if ($balance > 0) {
1795 $body0 .= "Остаток оплаты: " . addpoint($balance) . " руб.<br /><br />";
1796 }
1797
1798 if (get_me_delivery_by_id_project($id)) // смотрим нужна ли доставка
1799 {
1800 $body0 .= "Ожидайте доставки.<br /><br />";
1801 }
1802 else {
1803 $body0 .= readsql_system("text_email_report_made_order");
1804 $body0 .= "<br />Срок хранения заказа до: " . get_me_date_storage_period_for_project_by_id($id) . "<br /><br />";
1805 }
1806
1807 $body0 .= readsql_system("footer_email_report_made_order");
1808
1809 // Собираем массив данных
1810 $arr = array(
1811 'host' => $smtp_host,
1812 'port' => 465,
1813 'login' => $smtp_login,
1814 'password' => $smtp_pass,
1815 'from' => array(
1816 'mail' => $from_email,
1817 'name' => iconv('windows-1251', 'utf-8', $from_name),
1818 ),
1819 'to' => array(
1820 'mail' => $to_email,
1821 'name' => iconv('windows-1251', 'utf-8', $to_name),
1822 ),
1823 'sender' => $smtp_login,
1824 'subject' => iconv('windows-1251', 'utf-8', $subj0),
1825 'body' => array(
1826 'text' => iconv('windows-1251', 'utf-8', $body0),
1827 'content_type' => $type,
1828 'charset' => $charset,
1829 ),
1830 );
1831
1832 $result = swift_mail($arr);
1833 }
1834
1835 $status .= "> отправка email: ";
1836
1837 // если настройки smtp прописаны и отправка прошла удачно, делаем соответствующие записи в базу
1838 if ($smtp && $result === TRUE) {
1839 $status .= "ОТПРАВЛЕНО";
1840 }
1841 else {
1842 $status .= "НЕ ОТПРАВЛЕНО";
1843 }
1844
1845 $status .= " to <{$to_email}>\n";
1846 }
1847 else {
1848 $status .= "отправка email: опция отключена\n";
1849 }
1850
1851
1852 $status .= '> отправка sms: ';
1853 if (!in_array(date("H"), $time_response)) {
1854 $status .= "NO - время отправки не входит в допустимый диапазон " . min($time_response) . '-' . (max($time_response) + 1) . " часов\n";
1855 }
1856 else {
1857 if (get_me_sms_status_user_by_id_user($id_user)) // проверяем включена ли настройка получения SMS уведомлений
1858 { // отправляем SMS
1859
1860 $phone1 = trim(str_replace(array(
1861 '+',
1862 ' ',
1863 '(',
1864 ')',
1865 '-',
1866 ), '', decode_db($subj['phone1'])));
1867 /* !!!! */ /* $phone1="79215911571"; */
1868
1869 $text = readsql_system("name_company") . "\nВаш заказ №{$id} готов.\n";
1870 if ($balance > 0) {
1871 $text .= "Остаток оплаты: " . addpoint($balance) . " руб.\n";
1872 }
1873 if (get_me_delivery_by_id_project($id)) {
1874 $text .= "Ожидайте доставки.\n";
1875 }
1876 else {
1877 $text .= "Срок хранения до: " . get_me_date_storage_period_for_project_by_id($id) . "\n";
1878 }
1879 // берем текст смски из БД
1880 //$text.=readsql_system("text_sms_report_made_order");
1881 $text .= str_replace("<br />", "", readsql_system("text_sms_report_made_order"));
1882
1883 if (round($phone1)) {
1884 $status .= sendsms($phone1, $text, "Laser") . " на <+{$phone1}>\n";
1885 }
1886 else {
1887 $status .= "нет номера телефона\n";
1888 }
1889 }
1890 else {
1891 $status .= "опция отключена в настройках пользователя\n";
1892 }
1893 }
1894
1895 }
1896
1897 $status .= "\n";
1898
1899 echo $status;
1900 mysql_query("UPDATE `{$TABLE_sup_projects}` SET `status_report`=CONCAT('{$status}',`status_report`),`last_report`=NOW() WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
1901}
1902
1903function check_sequre_bookkeeping() {
1904 global $TABLE_sup_bookkeeping, $TABLE_sup_users, $TABLE_sup_projects;
1905
1906 $result_secure = mysql_query("SELECT COUNT(*) FROM `{$TABLE_sup_bookkeeping}` WHERE 1 AND `id_user_del`=0 AND `sum`!='0' AND `security`!=MD5(CONCAT(`id`,`datetime`,`date`,`id_project`,`sum`,`comment`,`id_payment_method`,'" . SALT . "'));") or die(errorDiv(mysql_error()));
1907 $alarm_result_secure_count = mysql_result($result_secure, 0);
1908 if ($alarm_result_secure_count) { // возвращаем подпись в систему
1909 $alarm = '';
1910 // $alarm="<div style='background:#f00;color:#fff;padding:10px;margin:10px 0;font-weight:bold;text-align:center;'>ОБНАРУЖЕНЫ ПОДОЗРИТЕЛЬНЫЕ ЗАЧИСЛЕНИЯ СРЕДСТВ в ".get_subdomain().".optima-cut.ru</div>";
1911
1912 // блокируем пользователей, которым начислены подозрительные средства - ОООООЧЕНЬ ДОЛГИЙ ЗАПРОС!!
1913 /*mysql_query("UPDATE `{$TABLE_sup_users}` SET `type`='0',`last_update`=NOW(), `alarm`=' !!!!! ПОДОЗРЕНИЕ НА ПОДДЕЛЬНУЮ ТРАНЗАКЦИЮ' WHERE `id` IN (SELECT `id_user` FROM `{$TABLE_sup_projects}` WHERE `id` IN (SELECT `id_project` FROM `{$TABLE_sup_bookkeeping}` WHERE `sum`!='0' AND `security`!=MD5(CONCAT(`id`,`datetime`,`date`,`id_project`,`sum`,`comment`,`id_payment_method`,'".SALT."')))) AND `type`!='0'");
1914 if(mysql_affected_rows()>0) // проверяем были ли внесены изменения и если были, то отправляем уведомление. Если таблица изменена не было (т.е. никто больше не был заблокирован), то больше смс не отправляем.
1915 { // отправляем уведомление по смс боссу
1916 */
1917 // sendsms_free('79992113287', iconv('windows-1251', 'UTF-8', "ОБНАРУЖЕНЫ ПОДОЗРИТЕЛЬНЫЕ ЗАЧИСЛЕНИЯ СРЕДСТВ в ".get_subdomain().".optima-cut.ru"), "Laser");
1918 /*
1919 }*/
1920
1921 return $alarm;
1922 }
1923}
1924
1925function status_order_for_client($status) {
1926 global $order_status_for_client;
1927
1928 return $order_status_for_client[$status];
1929}
1930
1931function last_update_controller($table) { //global $$table;
1932
1933 $table = str_replace(array(
1934 '"',
1935 "'",
1936 '`',
1937 "/",
1938 "\\",
1939 '=',
1940 '?',
1941 '&',
1942 "#",
1943 ':',
1944 ' ',
1945 ), '', $table);
1946
1947 $GLOBALS['GET_id'] = round($GLOBALS['GET_id']); // проверка должна проводиться в index.php, но на всякий случай напишем
1948 $result0 = mysql_query("SELECT `last_update` FROM `{$table}` WHERE `id`='{$GLOBALS['GET_id']}';") or die(errorDiv(mysql_error()));
1949 # ФОРМИРУЕМ ЛЕНТУ
1950 if (mysql_num_rows($result0)) {
1951 $subj0 = mysql_fetch_array($result0);
1952 $last_update = $subj0['last_update'];
1953 }
1954 else {
1955 $last_update = '---';
1956 }
1957
1958 print "<span id=\"last_update\" style=\"display:none;\">{$last_update}</span>\n";
1959 print "<input type='hidden' value='0' id='last_update_error' />";
1960 print "<script>\n";
1961 print " $(function () {\n";
1962 print " // этой функцией мы будем проверять соответствие метки времени изменения этой страницы той, что была на момент открытия\n";
1963 print " // если метка времени изменилась, значит страница была изменена на другой машине и мы выводить об этом предупреждение\n";
1964 print " var alert_ok;\n";
1965 print " $(\"body\").everyTime(3000, function(i) {\n";
1966 print " callserver('getdatetimelastupdate','{$table}#%sep#{$GLOBALS['GET_id']}','last_update','innerHTML');\n";
1967 print " if($('#last_update').text()!='{$last_update}'&&alert_ok!=1)\n";
1968 print " { $(\"#alarm\").html(\"Эта страница была изменена <!--с другого компьютера -->в \"+$('#last_update').text()+\"<br /><a href='/?p=" . $GLOBALS['GET_p'] . "&id=" . $GLOBALS['GET_id'] . "' id='open_new_window' target='_blank'>Откройте эту страницу в новом окне, чтобы просмотреть изменения</a>.\");\n";
1969 print " $(\"#open_new_window\").click(function(){ $(\"#alarm\").hide(); });\n";
1970 print " $(\"body\").css({backgroundColor:\"#ff0\"});\n";
1971 print " $(\"body\").css({backgroundImage:\"url('')\"});\n";
1972 print " $(\"#alarm\").show();\n";
1973 print " document.getElementById('submit').disabled='true';\n";
1974 print " document.getElementById('submit').style.display='none';\n";
1975 print " document.getElementById('last_update_error').value='1';\n";
1976 print " //alert('Эта страница была изменена');\n";
1977 print " alert_ok=1;\n";
1978 print " }\n";
1979 print " });\n";
1980 print " });\n";
1981 print "</script>\n";
1982
1983}
1984
1985function getcolorrating($rating) {
1986 $ret = '#fff;';
1987
1988 switch ($rating) {
1989 case '1' :
1990 $ret = '#900;';
1991 break;
1992 case '2' :
1993 $ret = '#ff2a00;';
1994 break;
1995 case '3' :
1996 $ret = '#ff8a00;';
1997 break;
1998 case '4' :
1999 $ret = '#fffc00;';
2000 break;
2001 case '5' :
2002 $ret = '#7eff00;';
2003 break;
2004 }
2005
2006 return $ret;
2007}
2008
2009function get_me_list_skills_by_id_user($id_user) {
2010 global $TABLE_sup_users_label;
2011
2012 $id_user = round($id_user);
2013
2014 // если id указан, то выводим возможности для этого юзера, если не указан, то выводим полный список возможностей
2015 $result = mysql_query("SELECT * FROM `{$TABLE_sup_users_label}` WHERE " . ($id_user ? "`id_user`='{$id_user}'" : "1") . ";") or die(errorDiv(mysql_error()));
2016 $count = mysql_num_rows($result);
2017 if ($count) {
2018 $ids_label[] = 0; // !!! на всякий случай в список умений пользователя, который мы выдаем этой функцией, добавим также ноль, пускай пользователь умеет обрабатывать файлы с пустым видом работ. Дело в том, если опять (такое уже было) глюгнет программа и макет присоединится без указания вида работ, то такой макет повиснет в воздухе, а при добавленном 0 такой макет все равно будет виден пользователем.
2019 for ($i = 0; $i < $count; $i++) {
2020 $subj = mysql_fetch_array($result);
2021 $ids_label[] = $subj['id_label'];
2022 }
2023 }
2024 else {
2025 $ids_label = array();
2026 }
2027
2028 return implode(',', $ids_label);
2029}
2030
2031function get_me_percent_remuneration_user_by_id_user($id) {
2032 global $TABLE_sup_users;
2033
2034 $id = round($id);
2035
2036 $result = mysql_query("SELECT `remuneration` FROM `{$TABLE_sup_users}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
2037 if (mysql_num_rows($result)) {
2038 $subj = mysql_fetch_array($result);
2039 $remuneration = $subj['remuneration'];
2040 }
2041
2042 return round($remuneration, 2);
2043}
2044
2045function get_me_percent_samozakaz_remuneration_user_by_id_user($id) {
2046 global $TABLE_sup_users;
2047
2048 $id = round($id);
2049
2050 $result = mysql_query("SELECT `samozakaz_remuneration` FROM `{$TABLE_sup_users}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
2051 if (mysql_num_rows($result)) {
2052 $subj = mysql_fetch_array($result);
2053 $samozakaz_remuneration = $subj['samozakaz_remuneration'];
2054 }
2055
2056 return round($samozakaz_remuneration, 2);
2057}
2058
2059function get_me_working_days_user_by_id_user($id) {
2060 global $TABLE_sup_users;
2061
2062 $id = round($id);
2063
2064 $result = mysql_query("SELECT `working_days` FROM `{$TABLE_sup_users}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
2065 if (mysql_num_rows($result)) {
2066 $subj = mysql_fetch_array($result);
2067 $working_days = $subj['working_days'];
2068 }
2069
2070 return round($working_days);
2071}
2072
2073function get_me_form_payment_user_by_id_user($id) {
2074 global $TABLE_sup_users;
2075
2076 $id = round($id);
2077
2078 $result = mysql_query("SELECT `form_payment` FROM `{$TABLE_sup_users}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
2079 if (mysql_num_rows($result)) {
2080 $subj = mysql_fetch_array($result);
2081 $form_payment = $subj['form_payment'];
2082 }
2083
2084 return round($form_payment);
2085}
2086
2087function get_me_plan_user_by_id_user($id) {
2088 global $TABLE_sup_users;
2089
2090 $id = round($id);
2091
2092 $result = mysql_query("SELECT `plan` FROM `{$TABLE_sup_users}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
2093 if (mysql_num_rows($result)) {
2094 $subj = mysql_fetch_array($result);
2095 $plan = $subj['plan'];
2096 }
2097 else {
2098 $plan = 0;
2099 }
2100
2101 return round($plan);
2102}
2103
2104function get_me_salary_user_by_id_user($id) {
2105 global $TABLE_sup_users;
2106
2107 $id = round($id);
2108 $salary = 0;
2109
2110 $result = mysql_query("SELECT `salary` FROM `{$TABLE_sup_users}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
2111 if (mysql_num_rows($result)) {
2112 $subj = mysql_fetch_array($result);
2113 $salary = $subj['salary'];
2114 }
2115
2116 return round($salary);
2117}
2118
2119function get_me_parameter_only_his_projects_by_id_user($id) {
2120 global $TABLE_sup_users;
2121
2122 $id = round($id);
2123
2124 $result = mysql_query("SELECT `only_his_projects` FROM `{$TABLE_sup_users}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
2125 if (mysql_num_rows($result)) {
2126 $subj = mysql_fetch_array($result);
2127 $only_his_projects = $subj['only_his_projects'];
2128 }
2129 else {
2130 $only_his_projects = 0;
2131 }
2132
2133 return round($only_his_projects);
2134}
2135
2136function get_me_count_file_in_the_project_by_id_file_and_id_project($id_file, $id_project) {
2137 global $TABLE_sup_files_projects;
2138
2139 $id_file = round($id_file);
2140 $id_project = round($id_project);
2141
2142 $count = 0;
2143
2144 $result = mysql_query("SELECT `count` FROM `{$TABLE_sup_files_projects}` WHERE `id_file`='{$id_file}' AND `id_project`='{$id_project}';") or die(errorDiv(mysql_error()));
2145 if (mysql_num_rows($result)) {
2146 $subj = mysql_fetch_array($result);
2147 $count = $subj['count'];
2148 }
2149
2150 return $count;
2151}
2152
2153// функция получающая стоимость проекта из бд. Функция выдает стоимость указанную менеджером в проекте, нужно для начисления вознаграждения менеджерам
2154function get_me_total_price_project_by_id_project($id) {
2155 global $TABLE_sup_projects;
2156
2157 $id = round($id);
2158
2159 $result = mysql_query("SELECT `total_price` FROM `{$TABLE_sup_projects}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
2160 if (mysql_num_rows($result)) {
2161 $subj = mysql_fetch_array($result);
2162 $total_price = $subj['total_price'];
2163 }
2164
2165 return $total_price;
2166}
2167
2168// функция получающая суммарную стоимость файлов, включенных в проект $id, нужно для начисления вознаграждения операторам
2169function get_me_total_price_project_by_id_project_each_file($id) {
2170 global $TABLE_sup_files_projects, $TABLE_sup_files;
2171
2172 $id = round($id);
2173
2174 //$sum = mysql_query("SELECT SUM(`pricefile`) FROM `{$TABLE_sup_files}` WHERE `id` IN (SELECT `id_file` FROM `{$TABLE_sup_files_projects}` WHERE `id_project`='{$id}');") or die(errorDiv(mysql_error()));
2175 $sum = mysql_query("SELECT SUM(`{$GLOBALS['TABLE_sup_files']}`.`pricefile`*`{$GLOBALS['TABLE_sup_files_projects']}`.`count`) FROM `{$GLOBALS['TABLE_sup_files_projects']}`,`{$GLOBALS['TABLE_sup_files']}` WHERE `{$GLOBALS['TABLE_sup_files_projects']}`.`id_project`='{$id}' AND `{$GLOBALS['TABLE_sup_files']}`.`id`=`{$GLOBALS['TABLE_sup_files_projects']}`.`id_file`;") or die(errorDiv(mysql_error()));
2176 $sum = mysql_result($sum, 0);
2177
2178 return round($sum);
2179}
2180
2181function use_active_project_this_user_this_label($id_user, $id_label) {
2182 global $TABLE_sup_projects, $TABLE_sup_files, $TABLE_sup_files_projects;
2183
2184 $id_user = round($id_user);
2185 $id_label = round($id_label);
2186 $ids_label = array();
2187
2188 $type = get_me_type_user_by_id_user($id_user);
2189
2190 // если смотрим менеджера, то одна проверка
2191 if ($type == '2') {
2192 // получаем все действующие проекты этого менеджера
2193 $result = mysql_query("SELECT * FROM `{$TABLE_sup_projects}` WHERE `id_user_manager`='{$id_user}' AND `status` NOT IN ('40','50') AND `id_user_del`='0';") or die(errorDiv(mysql_error()));
2194 $count = mysql_num_rows($result);
2195 if ($count) {
2196 for ($i = 0; $i < $count; $i++) {
2197 $subj = mysql_fetch_array($result);
2198 $ids_projects[] = $subj['id'];
2199 }
2200 }
2201 else {
2202 $ids_projects = array();
2203 }
2204
2205 // если действующих проектов у этого пользователя нет, то выводим 0
2206 if (!$ids_projects) {
2207 return 0;
2208 }
2209
2210 // получаем файлы используемые в действующих проектах этого менеджера
2211 $result = mysql_query("SELECT * FROM `{$TABLE_sup_files_projects}` WHERE `id_project` IN (" . implode(',', $ids_projects) . ");") or die(errorDiv(mysql_error()));
2212 $count = mysql_num_rows($result);
2213 if ($count) {
2214 for ($i = 0; $i < $count; $i++) {
2215 $subj = mysql_fetch_array($result);
2216 $ids_files[] = $subj['id_file'];
2217 }
2218 }
2219 else {
2220 $ids_files = array();
2221 }
2222
2223 // если файлов в действующих проектах у этого пользователя нет, то выводим 0
2224 if (!$ids_files) {
2225 return 0;
2226 }
2227
2228 // получаем виды работ из файлов используемых в действующих проектах этого менеджера
2229 $result = mysql_query("SELECT * FROM `{$TABLE_sup_files}` WHERE 1 AND `id_user_del`='0' AND `id` IN (" . implode(',', $ids_files) . ");") or die(errorDiv(mysql_error()));
2230 $count = mysql_num_rows($result);
2231 if ($count) {
2232 for ($i = 0; $i < $count; $i++) {
2233 $subj = mysql_fetch_array($result);
2234 $ids_label[] = $subj['id_label'];
2235 }
2236 }
2237 else {
2238 $ids_label = array();
2239 }
2240
2241
2242 }
2243 elseif ($type == '3') // если проверяем оператора, то другая
2244 {
2245 // получаем все действующие проекты, вообще все-все
2246 $result = mysql_query("SELECT * FROM `{$TABLE_sup_projects}` WHERE `status` NOT IN ('40','50') AND `id_user_del`='0';") or die(errorDiv(mysql_error()));
2247 $count = mysql_num_rows($result);
2248 if ($count) {
2249 for ($i = 0; $i < $count; $i++) {
2250 $subj = mysql_fetch_array($result);
2251 $ids_projects[] = $subj['id'];
2252 }
2253 }
2254 else {
2255 $ids_projects = array();
2256 }
2257
2258 // если действующих проектов нет, то выводим 0
2259 if (!$ids_projects) {
2260 return 0;
2261 }
2262
2263 // получаем файлы используемые этим оператором в действующих проектах
2264 $result = mysql_query("SELECT * FROM `{$TABLE_sup_files_projects}` WHERE `id_user_operator`='{$id_user}' AND `id_project` IN (" . implode(',', $ids_projects) . ");") or die(errorDiv(mysql_error()));
2265 $count = mysql_num_rows($result);
2266 if ($count) {
2267 for ($i = 0; $i < $count; $i++) {
2268 $subj = mysql_fetch_array($result);
2269 $ids_files[] = $subj['id_file'];
2270 }
2271 }
2272 else {
2273 $ids_files = array();
2274 }
2275
2276 // если файлов у этого оператора нет, то выводим 0
2277 if (!$ids_files) {
2278 return 0;
2279 }
2280
2281 // получаем виды работ из файлов используемых этим оператором
2282 $result = mysql_query("SELECT * FROM `{$TABLE_sup_files}` WHERE 1 AND `id_user_del`='0' AND `id` IN (" . implode(',', $ids_files) . ");") or die(errorDiv(mysql_error()));
2283 $count = mysql_num_rows($result);
2284 if ($count) {
2285 for ($i = 0; $i < $count; $i++) {
2286 $subj = mysql_fetch_array($result);
2287 $ids_label[] = $subj['id_label'];
2288 }
2289 }
2290 else {
2291 $ids_label = array();
2292 }
2293
2294 }
2295
2296
2297 // в итоге мы мы получили (или не получили) массив видов работ, к которым имеет причастность этот пользователь (менеджер или оператор)
2298 // если среди этого массива есть рассматриваемый вид работы, то выводим 1, если нет, то 0
2299
2300 if (in_array($id_label, $ids_label)) {
2301 return 1;
2302 }
2303 else {
2304 return 0;
2305 }
2306
2307}
2308
2309function check_super_user($type) {
2310 global $TABLE_sup_label, $TABLE_sup_users, $TABLE_sup_users_label;
2311
2312 $type = round($type);
2313
2314 $count_labels = mysql_query("SELECT COUNT(*) FROM `{$TABLE_sup_label}` WHERE 1 AND `id_user_del`=0 AND `position`='1';") or die(errorDiv(mysql_error()));
2315 $count_labels = mysql_result($count_labels, 0); // определили количество активных компетенций
2316
2317 $super_user = 0;
2318
2319 // перебираем каждого менеджера и оператора и смотрим, какое количество компетенций записано в базе у него, если меньше $count_labels, выводим аларм
2320 $result = mysql_query("SELECT * FROM `{$TABLE_sup_users}` WHERE 1 AND `id_user_del`=0 AND `type`='{$type}' AND `not_use_for_magazin`='0';") or die(errorDiv(mysql_error()));
2321 $count = mysql_num_rows($result);
2322 if ($count) {
2323 for ($i = 0; $i < $count; $i++) {
2324 $subj = mysql_fetch_array($result);
2325
2326 $count_labels_user = mysql_query("SELECT COUNT(*) FROM `{$TABLE_sup_users_label}` WHERE `id_user`=\"{$subj['id']}\";") or die(errorDiv(mysql_error()));
2327 $count_labels_user = mysql_result($count_labels_user, 0); // определили количество компетенций для этого пользователя
2328
2329 // если количество компетенций обладаемых этим юзером равно полному количеству компетенций существующих в системе, то он "суперюзер" =), ставим аларм = 1, что нашли супер юзера
2330 if ($count_labels_user == $count_labels) {
2331 $super_user = 1;
2332 }
2333
2334 }
2335 }
2336
2337 return $super_user;
2338
2339}
2340
2341function filesize_get($file) {
2342 // проверяем существует ли файл
2343 if (!file_exists($file)) {
2344 return "Файл отсутствует.";
2345 }
2346
2347 //определяем размер файла
2348 $filesize = filesize($file);
2349
2350 // Если размер переданного в функцию файла больше 1кб
2351 if ($filesize > 1024) {
2352 $filesize = $filesize / 1024;
2353 // если размер файла больше одного килобайта
2354 // пересчитываем в мегабайтах
2355 if ($filesize > 1024) {
2356 $filesize = $filesize / 1024;
2357 // если размер файла больше одного мегабайта
2358 // пересчитываем в гигабайтах
2359 if ($filesize > 1024) {
2360 $filesize = $filesize / 1024;
2361 $filesize = round($filesize, 1);
2362 return $filesize . " ГБ";
2363
2364 }
2365 else {
2366 $filesize = round($filesize, 1);
2367 return $filesize . " MБ";
2368 }
2369
2370 }
2371 else {
2372 $filesize = round($filesize, 1);
2373 return $filesize . " Кб";
2374 }
2375
2376 }
2377 else {
2378 $filesize = round($filesize, 1);
2379 return $filesize . " байт";
2380 }
2381
2382}
2383
2384function get_me_average_rating_by_id_user($id_user, $type) // вычисляем средний бал менеджера или оператора за ПЛАТНЫЕ проекты, в которых они принимали участие
2385{
2386 if (!in_array($type, array(2, 3))) {
2387 die();
2388 } // вычисляем для менеджера и оператора
2389 if ($type == 2) {
2390 $type = 'manager';
2391 }
2392 if ($type == 3) {
2393 $type = 'operator';
2394 }
2395
2396 $id_user = round($id_user);
2397
2398 $sum = mysql_query("SELECT SUM(`rating`) FROM `{$GLOBALS['TABLE_sup_projects']}` WHERE `total_price`>0 AND `id_user_{$type}`='{$id_user}' AND `status`='40' AND NOW() - INTERVAL 30 DAY < `closed`;") or die(errorDiv(mysql_error()));
2399 $sum = mysql_result($sum, 0);
2400
2401 $count = COUNTROWS($GLOBALS['TABLE_sup_projects'], " AND `total_price`>0 AND `id_user_{$type}`='{$id_user}' AND `status`='40' AND `rating` > 0 AND NOW() - INTERVAL 30 DAY < `closed` ;");
2402
2403 return $count ? round($sum / $count, 2) : 0;
2404}
2405
2406function get_me_manager_answer_to_client_by_id_project($id) {
2407 global $TABLE_sup_projects;
2408
2409 $answer = '';
2410 $id = round($id);
2411
2412 $result = mysql_query("SELECT * FROM `{$TABLE_sup_projects}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
2413 if (mysql_num_rows($result)) {
2414 $subj = mysql_fetch_array($result);
2415 $answer = trim($subj['rating_client_answer']);
2416 }
2417
2418 return $answer;
2419}
2420
2421function get_me_comment_rating_by_id_user($id_user, $type) // возвращаем комментарии с оценками пользователей к ПЛАТНЫМ проектам, участие в которых принимали менеджеры или операторы
2422{
2423 if (!in_array($type, array(1, 2, 3))) {
2424 die();
2425 } // вычисляем для менеджера и оператора
2426
2427 $id_user = round($id_user);
2428 $ret = '';
2429
2430 if ($type == 1) {
2431 /*не обязательно*/
2432 $type = 'admin';
2433 // ищем какие комментарии оставили клиенты к работе этого менеджера или оператора
2434 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_projects']}` WHERE /* `total_price`>0 AND */ `status`='40' AND `rating`>0 ORDER BY `closed` DESC LIMIT 10;") or die(errorDiv(mysql_error()));
2435 $count = mysql_num_rows($result);
2436 if ($count) {
2437 $ret = '';
2438 for ($i = 0; $i < $count; $i++) {
2439 $subj = mysql_fetch_array($result);
2440
2441 $manager_answer = get_me_manager_answer_to_client_by_id_project($subj['id']);
2442
2443 if (trim($subj['rating_comment'])) {
2444 $subj['rating_comment'] = base64_decode($subj['rating_comment']);
2445 }
2446 else {
2447 $subj['rating_comment'] = '---';
2448 }
2449 $ret .= "<div style='margin-bottom:0px;' class='small " . ($subj['rating'] < 5 ? 'red' : '') . "'><a href=\"/?p=projects&id={$subj['id']}\" class=\"strong " . ($subj['rating'] < 5 ? 'red' : '') . "\">" . get_me_name_user_by_id_user($subj['id_user']) . "</a>: {$subj['rating']}, <span class=" . ($subj['rating'] < 5 ? 'red' : '') . ">\"" . $subj['rating_comment'] . "\"</span>";
2450 if ($manager_answer) {
2451 $ret .= " <b> — {$manager_answer}</b>";
2452 } // (".get_me_name_user_by_id_user(get_me_id_manager_answer_to_client_by_id_project($subj['id'])).")</b>";
2453 $ret .= "</div>";
2454 }
2455 }
2456 }
2457
2458 if ($type == 2) { // ищем какие комментарии оставили клиенты к работе этого менеджера или оператора
2459 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_projects']}` WHERE /* `total_price`>0 AND */ /* `id_user_manager`='{$id_user}' AND */ `status`='40' AND `rating`>0 ORDER BY `closed` DESC LIMIT 10;") or die(errorDiv(mysql_error()));
2460 $count = mysql_num_rows($result);
2461 if ($count) {
2462 $ret = '';
2463 for ($i = 0; $i < $count; $i++) {
2464 $subj = mysql_fetch_array($result);
2465
2466 $manager_answer = get_me_manager_answer_to_client_by_id_project($subj['id']);
2467
2468 if (trim($subj['rating_comment'])) {
2469 $subj['rating_comment'] = base64_decode($subj['rating_comment']);
2470 }
2471 else {
2472 $subj['rating_comment'] = '---';
2473 }
2474 $ret .= "<div style='margin-bottom:0px;' class='small " . ($subj['rating'] < 5 ? 'red' : '') . "'><a href=\"/?p=projects&id={$subj['id']}\" class=\"strong " . ($subj['rating'] < 5 ? 'red' : '') . "\">" . get_me_name_user_by_id_user($subj['id_user']) . "</a>: {$subj['rating']}, <span class=" . ($subj['rating'] < 5 ? 'red' : '') . ">\"" . $subj['rating_comment'] . "\"</span>";
2475 if ($manager_answer) {
2476 $ret .= " <b> — {$manager_answer}</b>";
2477 } // (".get_me_name_user_by_id_user(get_me_id_manager_answer_to_client_by_id_project($subj['id'])).")</b>";
2478 $ret .= "</div>";
2479 }
2480 }
2481 }
2482 if ($type == 3) { // ищем какие комментарии оставили клиенты к работе этого менеджера или оператора
2483 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_projects']}`,`{$GLOBALS['TABLE_sup_files_projects']}` WHERE /* `{$GLOBALS['TABLE_sup_files_projects']}`.`id_user_operator`='{$id_user}' AND */ `{$GLOBALS['TABLE_sup_files_projects']}`.`id_project`=`{$GLOBALS['TABLE_sup_projects']}`.`id` AND `{$GLOBALS['TABLE_sup_projects']}`.`total_price`>0 AND `{$GLOBALS['TABLE_sup_projects']}`.`status`='40' AND `{$GLOBALS['TABLE_sup_projects']}`.`rating`>0 GROUP BY `{$GLOBALS['TABLE_sup_projects']}`.`closed` DESC LIMIT 10;") or die(errorDiv(mysql_error()));
2484 $count = mysql_num_rows($result);
2485 if ($count) {
2486 $ret = '';
2487 for ($i = 0; $i < $count; $i++) {
2488 $subj = mysql_fetch_array($result);
2489
2490 $manager_answer = get_me_manager_answer_to_client_by_id_project($subj['id']);
2491
2492 if (trim($subj['rating_comment'])) {
2493 $subj['rating_comment'] = base64_decode($subj['rating_comment']);
2494 }
2495 else {
2496 $subj['rating_comment'] = '---';
2497 }
2498 $ret .= "<div style='margin-bottom:0px;' class='small " . ($subj['rating'] < 5 ? 'red' : '') . "'><a href=\"/?p=projects&id={$subj['id_project']}\" class=\"strong " . ($subj['rating'] < 5 ? 'red' : '') . "\">" . get_me_name_user_by_id_user($subj['id_user']) . "</a>: {$subj['rating']}, <span class=" . ($subj['rating'] < 5 ? 'red' : '') . ">\"" . $subj['rating_comment'] . "\"</span>";
2499 if ($manager_answer) {
2500 $ret .= " <b> — {$manager_answer}</b>";
2501 } // (".get_me_name_user_by_id_user(get_me_id_manager_answer_to_client_by_id_project($subj['id'])).")</b>";
2502 $ret .= "</div>";
2503 }
2504 }
2505 }
2506
2507 return $ret;
2508
2509}
2510
2511function get_me_list_items_in_order_by_id_project($id) {
2512 $ret = '';
2513
2514 $id = round($id);
2515
2516 // получаем файлы используемые в действующих проектах этого пользователя
2517 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_files_projects']}`,`{$GLOBALS['TABLE_sup_files']}` WHERE `{$GLOBALS['TABLE_sup_files_projects']}`.`id_project`='{$id}' AND `{$GLOBALS['TABLE_sup_files']}`.`id`=`{$GLOBALS['TABLE_sup_files_projects']}`.`id_file`;") or die(errorDiv(mysql_error()));
2518 $count = mysql_num_rows($result);
2519 if ($count) {
2520 for ($i = 0; $i < $count; $i++) {
2521 $subj = mysql_fetch_array($result);
2522 $ret .= $subj['titlefile'] . ': 0/' . $subj['count'] . ' шт.\n';
2523 }
2524 }
2525
2526 return $ret;
2527}
2528
2529function write_action($operation) {
2530 $operation = round($operation);
2531 if (!$operation) {
2532 die;
2533 }
2534
2535 if (isset($_SESSION['id_client']) && round($_SESSION['id_client'])) {
2536 $id_client = round($_SESSION['id_client']);
2537 }
2538 else {
2539 $id_client = auth('id');
2540 }
2541
2542 $page = $_SERVER['REQUEST_URI']; // получаем адрес текущей страницы
2543
2544 $stop_pages = array('/cron.php'); // страницы, обращение к которым не отслеживаем
2545 if (in_array($page, $stop_pages)) {
2546 return FALSE;
2547 }
2548
2549 //echo "INSERT INTO `{$GLOBALS['TABLE_sup_workday']}` (`datetime`,`id_user`,`operation`,`ip`,`page`) VALUES (NOW(),'".auth('id')."','{$operation}','".get_user_ip()."','http://".HOST_SUP."{$page}');";
2550 if (empty($id_client)) {
2551 $id_client = 0;
2552 }
2553
2554 if (isset($_SESSION['noworkday']) && $_SESSION['noworkday']) {
2555 }
2556 else {
2557 $page = 'https://' . HOST_SUP . $page;
2558 $substr_page = substr($page, 0, 255);
2559
2560 mysql_query("INSERT INTO `{$GLOBALS['TABLE_sup_workday']}` (`datetime`,`id_user`,`operation`,`ip`,`page`) VALUES (NOW(),'" . $id_client . "','{$operation}','" . get_user_ip() . "','{$substr_page}');") or die(errorDiv(mysql_error()));
2561 }
2562
2563}
2564
2565function get_me_title($email, $text_id = '') {
2566 //include_once "modules/connect_to_sup_db.php";
2567
2568 $email = str_replace(array(
2569 '"',
2570 "'",
2571 '`',
2572 "/",
2573 "\\",
2574 '=',
2575 '?',
2576 '&',
2577 "#",
2578 ':',
2579 ' ',
2580 ), '', $email);
2581 $text_id = str_replace(array(
2582 '"',
2583 "'",
2584 '`',
2585 "/",
2586 "\\",
2587 '=',
2588 '?',
2589 '&',
2590 "#",
2591 ':',
2592 ' ',
2593 ), '', $text_id);
2594
2595 $str = '';
2596 $str = readsql_system("name_company") . " / Интернет-магазин";
2597
2598 if (trim($email) && !trim($text_id)) {
2599 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_users']}` WHERE `id_user_del`='0' AND `type`='5' AND `email_md5`=MD5('{$email}') LIMIT 1;") or die(errorDiv(mysql_error()));
2600 $count = mysql_num_rows($result);
2601
2602 # ФОРМИРУЕМ ЛЕНТУ
2603 if ($count) {
2604 $subj = mysql_fetch_array($result);
2605
2606 $str .= ' / ' . $subj['patronymic'] . ' / ' . $subj['name'];
2607 }
2608
2609 }
2610 elseif (trim($email) && trim($text_id)) {
2611 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_files']}` WHERE `id_user_del`='0' AND `text_id`='{$text_id}' LIMIT 1;") or die(errorDiv(mysql_error()));
2612 $count = mysql_num_rows($result);
2613
2614 # ФОРМИРУЕМ ЛЕНТУ
2615 if ($count) {
2616 $subj = mysql_fetch_array($result);
2617
2618 $str = get_me_title($email) . ' / ' . $subj['titlefile'] . ' - ' . $subj['commentfile'] . ' за ' . addpoint($subj['pricefile']) . ' руб.';
2619 }
2620
2621 }
2622 elseif (!trim($email) && !trim($text_id)) {
2623 }
2624
2625 return $str;
2626}
2627
2628function get_me_description_metateg($email, $text_id) {
2629 $email = str_replace(array(
2630 '"',
2631 "'",
2632 '`',
2633 "/",
2634 "\\",
2635 '=',
2636 '?',
2637 '&',
2638 "#",
2639 ':',
2640 ' ',
2641 ), '', $email);
2642 $text_id = str_replace(array(
2643 '"',
2644 "'",
2645 '`',
2646 "/",
2647 "\\",
2648 '=',
2649 '?',
2650 '&',
2651 "#",
2652 ':',
2653 ' ',
2654 ), '', $text_id);
2655
2656 $str = '';
2657
2658 if (trim($email) && !trim($text_id)) {
2659 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_users']}` WHERE 1 AND `type`='5' AND `email_md5`=MD5('{$email}') LIMIT 1;") or die(errorDiv(mysql_error()));
2660 $count = mysql_num_rows($result);
2661
2662 # ФОРМИРУЕМ ЛЕНТУ
2663 if ($count) {
2664 $subj = mysql_fetch_array($result);
2665
2666 $str = strip_tags(str_replace("'", '', str_replace('"', "'", $subj['magazin_description'])));
2667
2668 }
2669
2670 }
2671 elseif (trim($email) && trim($text_id)) {
2672 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_files']}` WHERE 1 AND `id_user_del`='0' AND `text_id`='{$text_id}' LIMIT 1;") or die(errorDiv(mysql_error()));
2673 $count = mysql_num_rows($result);
2674
2675 # ФОРМИРУЕМ ЛЕНТУ
2676 if ($count) {
2677 $subj = mysql_fetch_array($result);
2678
2679 $str = strip_tags(str_replace('"', "'", str_replace("'", '', $subj['titlefile'] . ' - ' . $subj['commentfile'] . ' за ' . $subj['pricefile'] . ' руб.')));
2680
2681 }
2682 }
2683
2684 $str = trim($str);
2685 if ($str) {
2686 return "<meta name=\"description\" content=\"{$str}\">";
2687 }
2688 else {
2689 return '';
2690 }
2691
2692}
2693
2694function get_me_password_user_by_id_user($id) {
2695 //include_once "modules/connect_to_sup_db.php";
2696
2697 $id = round($id);
2698
2699 $password = '';
2700
2701 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_users']}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
2702 if (mysql_num_rows($result)) {
2703 $subj = mysql_fetch_array($result);
2704 $password = trim($subj['password']);
2705 }
2706
2707 return $password;
2708}
2709
2710function SUM($table, $row, $dop) {
2711 $table = str_replace(array(
2712 '"',
2713 "'",
2714 "/",
2715 "\\",
2716 '=',
2717 '?',
2718 '&',
2719 "#",
2720 ':',
2721 ' ',
2722 ), '', $table);
2723 $row = str_replace(array(
2724 '"',
2725 "'",
2726 "/",
2727 "\\",
2728 '=',
2729 '?',
2730 '&',
2731 "#",
2732 ':',
2733 ' ',
2734 ), '', $row);
2735
2736 $sum = mysql_query("SELECT SUM(`{$row}`) FROM `{$table}` WHERE 1=1 " . $dop) or die(errorDiv(mysql_error()));
2737 //echo "SELECT SUM(`{$row}`) FROM `{$table}` WHERE 1=1 ".$dop;
2738 $ret = mysql_result($sum, 0);
2739
2740 return $ret;
2741}
2742
2743function bonus_operator_this_month_by_id_user($id_user) {
2744 $this_year_month = date('Y-m');
2745
2746 $id_user = round($id_user);
2747
2748 $income_this_month_approve = mysql_query("SELECT SUM(`remuneration_operator`) FROM `{$GLOBALS['TABLE_sup_projects']}` WHERE `id_user_operator`='{$id_user}' AND `remuneration_operator_approve`='1' AND `status` IN ('40','50') AND `closed` LIKE '{$this_year_month}-__ __:__:__';") or die(errorDiv(mysql_error()));
2749 $income_this_month_approve = round(mysql_result($income_this_month_approve, 0));
2750
2751 return $income_this_month_approve;
2752}
2753
2754// возвращаем количество полный дней, прошедших с момента "принятия" заказа, т.е. с момента уведомления клиента
2755function storage_period_project_by_id_project($id_project) {
2756 $id_project = round($id_project);
2757
2758 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_projects']}` WHERE `id`='{$id_project}';") or die(errorDiv(mysql_error()));
2759 $count = mysql_num_rows($result);
2760 if ($count) {
2761 $subj = mysql_fetch_array($result);
2762 $accepted = str_replace(array(' ', ':'), '-', $subj['accepted']);
2763 $accepted_ar = explode('-', $accepted);
2764 $accepted_mktime = mktime($accepted_ar[3], $accepted_ar[4], $accepted_ar[5], $accepted_ar[1], $accepted_ar[2], $accepted_ar[0]);
2765 $storage_period = mktime() - $accepted_mktime;
2766 $storage_period = round($storage_period / 86400 - 0.5);
2767 }
2768
2769 return $storage_period;
2770
2771}
2772
2773function file_get_contents_curl($url) {
2774 $ch = curl_init();
2775
2776 // подставляем заголовок, что нам нужен русский язык
2777 $headers = array
2778 (
2779 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*;q=0.8',
2780 'Accept-Language: ru,en-us;q=0.7,en;q=0.3',
2781 'Accept-Encoding: deflate',
2782 'Accept-Charset: utf-8;q=0.7,*;q=0.7',
2783 );
2784 curl_setopt($ch, CURLOPT_URL, $url);
2785 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
2786 //curl_setopt($ch, CURLOPT_HEADER, 1);
2787 //curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
2788 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
2789 //curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Linux x86_64; rv:17.0) Gecko/17.0 Firefox/17.0');
2790 curl_setopt($ch, CURLOPT_ENCODING, 'utf-8');
2791 curl_setopt($ch, CURLOPT_TIMEOUT, 200);
2792 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
2793 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
2794 $data = curl_exec($ch);
2795 curl_close($ch);
2796 return $data;
2797}
2798
2799function get_me_last_post_in_vk($url) {
2800 // обращаемя специально к мобильной версии сайта
2801 $url = 'm.' . $url;
2802 $url = str_replace(array('"', "'", '`', "#", ' '), '', $url);
2803
2804 $url = 'https://' . trim($url);
2805 if (!$url) {
2806 return '';
2807 }
2808
2809 if (strpos($url, '/topic-')) {
2810 $type = 'topic';
2811 } // определяем по url группа это или топик
2812
2813 if ($type == 'topic') // если топик, то определяем номер последнего сообщения и дописываем url
2814 {
2815 $str0 = utf8_win(file_get_contents_curl($url));
2816
2817 // определяем количество постов в этой теме, чтобы определить последнюю страницу
2818 $countposts_a = explode("<h4 class=\"slim_header\">", $str0);
2819 $countposts_a = explode(" posts</h4>", $countposts_a[1]);
2820 $countposts = $countposts_a[0] - 1;
2821
2822 $url = $url . "?offset=" . $countposts;
2823
2824 }
2825
2826 // дальше принцип действия такой же
2827
2828 // достаем страницу
2829 $str0 = utf8_win(file_get_contents_curl($url));
2830 $str = substr($str0, strpos($str0, 'wall_posts'));
2831
2832 // достаем страницу пользователя
2833 $userpage_a = explode("<a class=\"pi_author\" href=\"", $str0);
2834 $userpage_a = explode("\">", $userpage_a[1]);
2835 $userpage = "https://m.vk.com" . $userpage_a[0];
2836
2837 //echo $str;
2838
2839 //echo $url.'-'.$userpage;
2840 if ($url == $userpage) {
2841 return '';
2842 } // если ссылка на страницу опубликовавшего объявление совпадает со ссылкой на страницу паблика, возвращаем пустой результат
2843
2844 // достаем имя пользователя
2845 $username_a = explode("</a>", $userpage_a[1]);
2846 $username = $username_a[0];
2847
2848 // достаем вопрос пользователя
2849 $usercomment_a = explode("<div class=\"pi_text\">", $str0);
2850 $usercomment_a = explode("</div>", $usercomment_a[1]);
2851 $usercomment = str_replace("<a href=", "<a1 href=", $usercomment_a[0]);
2852
2853 // если вопрос не нашли, возвращаем пустой результат
2854 if (!trim($usercomment)) {
2855 return '';
2856 }
2857
2858 // достаем время публикования вопроса
2859 $usertime_a = explode("<a class=\"wi_date\" href=\"/wall-", $str0);
2860 $usertime_a = explode("\">", $usertime_a[1]);
2861 $usertime_a = explode("</a>", $usertime_a[1]);
2862 $usertime = $usertime_a[0];
2863
2864 // если это топик
2865 if ($type == 'topic') { // определяем родительскую страницу, по которой сможем найти адрес создателя топика
2866 $board_a = explode("<a class=\"hb_wrap mhb_back al_back\" href=\"", $str0);
2867 $board_a = explode("\" accesskey=\"0\">", $board_a[1]);
2868 $board = "https://m.vk.com" . $board_a[0];
2869
2870 $str0board = utf8_win(file_get_contents_curl($board));
2871
2872 // находим на родительской странице адрес создателя топика
2873 $topicauthor_a = explode("<a class=\"hb_wrap mhb_back al_back\" href=\"", $str0board);
2874 $topicauthor_a = explode("\" accesskey=\"0\">", $topicauthor_a[1]);
2875 $topicauthor = "https://m.vk.com" . $topicauthor_a[0];
2876
2877 // сравниваем адрес создателя топика с адресом ответившего
2878 // echo $userpage.'-'.$topicauthor;
2879 if ($userpage == $topicauthor) {
2880 return '';
2881 }
2882 }
2883
2884 // получаем адреса из поля "контакты" в этой группе
2885
2886 $ret = "<div class=\"strong\"><a href=\"" . str_replace('https://m.', 'https://', $userpage) . "\" target=\"_blank\">{$username}</a></div>";
2887 //$ret.="<div class=\"small silver\">{$usertime}</div>"; // не выводим из-за того, что дата вконтакте выводится относительной, а не абсолютной (сегодня, вчера и число), из-за этого система повторно добавляет одни и те же обновления
2888 $ret .= "<div>{$usercomment}</div>";
2889
2890 return $ret;
2891
2892}
2893
2894function get_me_name_vkgroup_by_id_vkgroup($id) {
2895 global $TABLE_sup_vkgroups;
2896
2897 $id = round($id);
2898
2899 $name = '';
2900
2901 $result = mysql_query("SELECT * FROM `{$TABLE_sup_vkgroups}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
2902 if (mysql_num_rows($result)) {
2903 $subj = mysql_fetch_array($result);
2904 $name = trim($subj['name']);
2905 }
2906
2907 return $name;
2908}
2909
2910function get_me_url_vkgroup_by_id_vkgroup($id) {
2911 global $TABLE_sup_vkgroups;
2912
2913 $id = round($id);
2914
2915 $name = '';
2916
2917 $result = mysql_query("SELECT * FROM `{$TABLE_sup_vkgroups}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
2918 if (mysql_num_rows($result)) {
2919 $subj = mysql_fetch_array($result);
2920 $name = trim($subj['url']);
2921 }
2922
2923 return $name;
2924}
2925
2926function get_compliment() {
2927 /*
2928 return ''; // выводим комплименты только для моего сайта
2929
2930 $compliments_a=explode("\n",file_get_contents('compliments.txt'));
2931 return "— ".$compliments_a[mt_rand(0,count($compliments_a)-1)];
2932 */
2933}
2934
2935function bookkeeping_month_result($ymd = '', $open_more = 0) {
2936 if (!in_array(auth('type'), array(1, 2))) {
2937 return '';
2938 }
2939
2940 if (!trim($ymd)) {
2941 $ymd = date("Y-m-d");
2942 }
2943 list($year, $month, $day) = explode('-', $ymd);
2944
2945 $income_one_ok = 0;
2946 $list_bookkeeping = '';
2947
2948 if (auth('type') == 1) // пока что только для админа выводим результаты за месяц
2949 {
2950 if ($year == date("Y") && $month == date("m")) {
2951 $next_month = 0;
2952 }
2953 else {
2954 $next_month = 1;
2955 } // если речь идет о текущем месяце и годе, то стрелку "след.месяц" не выводим.
2956 $list_bookkeeping .= "<div style=\"text-align:center;\" class=\"none-select-text strong\">Выбранный месяц: <span class=\"link dotted blue\" onclick=\"callserver('refresh_bookkeeping_month_result','" . date("Y-m-d", mktime(23, 59, 59, $month - 1, $day, $year)) . "#'+document.getElementById('full_costs').style.display,'bookkeeping_month_result_div','innerHTML');\">←</span> <span id='ym'>" . get_month($month) . ' ' . $year . "</span> " . ($next_month ? "<span class=\"link dotted blue\" onclick=\"callserver('refresh_bookkeeping_month_result','" . date("Y-m-d", mktime(23, 59, 59, $month + 1, $day, $year)) . "#'+document.getElementById('full_costs').style.display,'bookkeeping_month_result_div','innerHTML');\">→</span>" : '') . "</div>";
2957 }
2958 $list_bookkeeping .= "<div class=\"b-result-bookkeeping\"><div class=\"container\"><div class=\"row expanded\"><div class=\"columns small-12 medium-12 large-6\">";
2959
2960 // вычисляем тенденцию за этот месяц, как выручка за этот месяц, деленная на количество прошедших дней в месяце, умноженная на количество дней в месяце всего
2961 $trend = round(total_money_only_cash_positiv($ymd, 'month', 1) / date("d", mktime(23, 59, 59, $month, $day, $year)) * date('t', mktime(23, 59, 59, $month, $day, $year)));
2962 // НО если речь идет не о текущем месяце (а значит о прошедшем), то тенденцию составить невозможно, определеяем ее просто как выручка за тот месяц
2963 if ($month != date('m')) {
2964 $trend = round(total_money_only_cash_positiv($ymd, 'month', 1));
2965 }
2966
2967 $yesterdaymonth = round(total_money_only_cash_positiv(date("Y-m-d", mktime(23, 59, 59, $month - 1, $day, $year)), 'month', 1));
2968 $plan = SUM($GLOBALS['TABLE_sup_users'], 'plan', " AND `id_user_del`=0 AND `type`='2' ");
2969 if (in_array(auth('type'), array(1))) {
2970 $list_bookkeeping .= "<div style='text-align:right;'>Выручка на этот месяц - <u>" . addpoint(total_money_only_cash_positiv($ymd, 'month', 1)) . "</u> руб.</div>";
2971 // выводим тенденцию и минимальный общий план только для этого месяца, потому что для любого прошлого месяца его определить не представляется возможным, т.к. неизвестно какие цифры стояли тогда
2972 if ($year == date("Y") && $month == date("m")) {
2973 $list_bookkeeping .= "<div style='text-align:right;'>Тенденция по выручке на этот месяц - <u>" . addpoint($trend) . "</u> руб.</div>";
2974 $list_bookkeeping .= "<div style='text-align:right;'>План менеджеров - <u>" . addpoint($plan) . "</u> руб.</div>";
2975 }
2976 $list_bookkeeping .= "<div style='text-align:right;'>В прошлом месяце было заработано - <u>" . addpoint($yesterdaymonth) . "</u> руб.</div>";
2977 }
2978
2979 $list_bookkeeping .= "</div><div class=\"columns small-12 medium-12 large-6\">";
2980
2981 if (auth('type') == 2) {
2982 $list_bookkeeping .= "<div><!--↔ --><u>" . addpoint(get_me_plan_user_by_id_user(auth('id'))) . "</u> руб. - Ваш персональный план на месяц</div>";
2983
2984 // вычисляем тенденцию за этот месяц, как выручка за этот месяц, деленная на количество прошедших дней в месяце, умноженная на количество дней в месяце всего
2985 $personaltrend = round(total_money_only_cash_positiv($ymd, 'month', auth('id')) / round(date("d", mktime(23, 59, 59, $month, $day, $year))) * date('t', mktime(23, 59, 59, $month, $day, $year)));
2986 // НО если речь идет не о текущем месяце (а значит о прошедшем), то тенденцию составить невозможно, определеяем ее просто как выручка за тот месяц
2987 if ($month != date('m')) {
2988 $personaltrend = round(total_money_only_cash_positiv($ymd, 'month', auth('id')));
2989 }
2990
2991 $list_bookkeeping .= "<div><!--↔ --><u>" . addpoint($personaltrend) . "</u> руб. - Ваша тендеция на этот месяц</div>";
2992 $personalyesterdaymonth = round(total_money_only_cash_positiv(date("Y-m-d", mktime(23, 59, 59, $month - 1, $day, $year)), 'month', auth('id')));
2993 $list_bookkeeping .= "<div><!--↔ --><u>" . addpoint($personalyesterdaymonth) . "</u> руб. - Выручка, которую Вы сделали прошлом месяце</div>";
2994 $list_bookkeeping .= "</td><td>";
2995 /*$list_bookkeeping .= "<span style='background:#f6f6f6;padding:3px;' >Такой результат обеспечит Вам зарплату в ";
2996 if($personaltrend<get_me_plan_user_by_id_user(auth('id')))
2997 { $list_bookkeeping .= "<u>".addpoint(get_me_salary_user_by_id_user(auth('id')))."</u> руб.<br />";
2998 //$list_bookkeeping .= "Что является самым минимумом.<br />";
2999 } else
3000 { $list_bookkeeping .= "<u>".addpoint(get_me_salary_user_by_id_user(auth('id'))+round(($personaltrend*1-get_me_plan_user_by_id_user(auth('id')))/100*get_me_percent_remuneration_user_by_id_user(auth('id'))))."</u> руб.<br />";
3001 }
3002 $list_bookkeeping .= "</span>";
3003 */
3004
3005
3006 }
3007
3008 if (auth('type') == 1) {
3009 $list_bookkeeping .= "";
3010
3011 // АНАЛИЗИРУЕМ РАСХОДЫ В ЭТОМ МЕСЯЦЕ И ВЫВОДИМ ДАННЫЕ КУДА СКОЛЬКО БЫЛО ПОТРАЧЕНО
3012 $income = SUM($GLOBALS['TABLE_sup_bookkeeping'], 'sum', " AND `id_user_del`=0 AND `sum`>0 AND `date` LIKE '" . $year . '-' . $month . "-%' ");
3013
3014 $list_bookkeeping .= "<table border='0' width='450' class=\"table-default\" style=\"width: 450px;\"><tr><td class='green'>Всего доходов в этом месяце:</td><td width='100' style='text-align:right;' class='green'>" . addpoint($income) . " руб.</td><td width='100' style='text-align:right;' class='green'>100%</td></tr></table>";
3015
3016 $costs = SUM($GLOBALS['TABLE_sup_bookkeeping'], 'sum', " AND `id_user_del`=0 AND `sum`<0 AND `date` LIKE '" . $year . '-' . $month . "-%' ");
3017
3018 $list_bookkeeping .= "<table border='0' width='450' class=\"table-default\" style=\"width: 450px;\"><tr><td><span class='red dotted' onclick=\"javascript:if(document.getElementById('full_costs').style.display=='')document.getElementById('full_costs').style.display='none';else document.getElementById('full_costs').style.display='';\">Всего расходов в этом месяце:</span></td><td width='100' style='text-align:right;'><span class='red'>" . addpoint($costs) . " руб.</span></td><td width='100' style='text-align:right;' class='red'>" . ($income ? abs(round($costs / $income * 100, 2)) : '--- ') . "%</td></tr></table>";
3019
3020 $list_bookkeeping .= "<div id='full_costs' " . (!$open_more ? "style='display:none;'" : '') . ">";
3021
3022 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_costs']}` WHERE 1 AND `id_user_del`=0 AND `position`='1' ORDER BY `id` ASC;") or die(errorDiv(mysql_error()));
3023 $count = mysql_num_rows($result);
3024 # выводим в скрытую форму задолженности по проектам, чтобы подставить ее при выборе проекта
3025 if ($count) {
3026 for ($i = 0; $i < $count; $i++) {
3027 $subj = mysql_fetch_array($result);
3028 $income_one = SUM($GLOBALS['TABLE_sup_bookkeeping'], 'sum', " AND `id_user_del`=0 AND `sum`<0 AND `date` LIKE '" . $year . '-' . $month . "-%' AND `comment` LIKE '{$subj['name']}%' ");
3029 $income_one_ok += $income_one; // учитываем этот расход как выведенный напротив статьи расходов. Нужно, чтобы в конце списка статей расходов общую сумму расходов уменьшить на сумму учтенных расходов (по статьям), получив сумму неучтенных расходов
3030 $list_bookkeeping .= "<table border='0' width='450' class=\"table-default\" style=\"width: 450px;\"><tr><td title='{$subj['comment']}' class='red'>{$subj['name']}</td><td width='100' style='text-align:right;' class='red'>" . addpoint(round($income_one)) . " руб.</td><td width='100' style='text-align:right;' class='red'>" . ($income ? abs(round($income_one / $income * 100, 2)) : '--- ') . "%</td></tr></table>";
3031 }
3032 $income_one = $costs + -$income_one_ok;
3033 $list_bookkeeping .= "<table border='0' width='450' class=\"table-default\" style=\"width: 450px;\"><tr><td class='red' title='Сумма расходов неназначенных ни в одну из вышеперечисленных статей расходов'>* Расходы без назначения</td><td width='100' style='text-align:right;' class='red'>" . addpoint(round($income_one)) . " руб.</td><td width='100' style='text-align:right;' class='red'>" . ($income ? abs(round($income_one / $income * 100, 2)) : '--- ') . "%</td></tr></table>";
3034 }
3035 $list_bookkeeping .= "</div>";
3036
3037 $list_bookkeeping .= "<table border='0' width='450' class=\"table-default\" style=\"width: 450px;\"><tr><td class='strong gray'>Чистая прибыль:</td><td width='100' style='text-align:right;' class='strong gray'>" . addpoint($income + $costs) . " руб.</td><td width='100' class='strong gray' style='text-align:right;'>" . ($income ? round(($income + $costs) / $income * 100, 2) : '--- ') . "%</td></tr></table>";
3038 $list_bookkeeping .= "";
3039 // / АНАЛИЗИРУЕМ РАСХОДЫ В ЭТОМ МЕСЯЦЕ И ВЫВОДИМ ДАННЫЕ КУДА СКОЛЬКО БЫЛО ПОТРАЧЕНО
3040 $list_bookkeeping .= "";
3041 }
3042
3043 $list_bookkeeping .= "</div></div></div></div>";
3044
3045 return $list_bookkeeping;
3046}
3047
3048function notes_mini() // собираем упрощенный список заметок для пользователя, чтобы вывести его в проекты
3049{
3050 global $id_user_from_notes, $id_user_to_notes, $id_notes, $content_notes, $answer_notes, $content_mini_notes;
3051 global $work_time_day_from_notes, $work_time_month_from_notes, $work_time_year_from_notes, $work_time_day_to_notes, $work_time_month_to_notes, $work_time_year_to_notes, $porn_notes;
3052
3053 $list_notes = '';
3054
3055 # ОПРЕДЕЛЯЕМ КОЛИЧЕСТВО СТАТЕЙ И ЕСЛИ СТАТЕЙ БОЛЬШЕ НУЛЯ, НАЧИНАЕМ ФОРМИРОВАНИЕ ЛЕНТЫ
3056 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_notes']}` WHERE 1 AND `id_user_del`=0 " . (in_array(auth('type'), array(
3057 1,
3058 2,
3059 3,
3060 )) ? " AND (`id_user_to`='" . auth('id') . "') " : '') . " AND ( (`id_user_from`!='" . auth('id') . "' AND `activ`=1) OR ((`id_user_from`='" . auth('id') . "' /* OR " . auth('id') . "=1 */ ) AND `activ` IN (0,1)) ) ORDER BY `datetime` DESC;") or die(errorDiv(mysql_error()));
3061 $count = mysql_num_rows($result);
3062
3063 # ФОРМИРУЕМ ЛЕНТУ
3064 if ($count) {
3065 $list_notes .= "Заметки Вам:<table border='0' cellspacing='1' cellpadding='4' style='width:100%;background:#bbb;margin:5px 0;'>";
3066 for ($i = 0; $i < $count; $i++) {
3067 $subj = mysql_fetch_array($result);
3068
3069 $id_notes = $subj['id'];
3070 $activ_notes = $subj['activ'];
3071 $activ_humain_notes = ($subj['activ'] == '0' ? $activ_humain_notes = "<span class='strong red'>Неактивно</span>" : ($subj['activ'] == '1' ? $activ_humain_notes = 'Активно' : $activ_humain_notes = ''));
3072 $datetime_notes = $subj['datetime'];
3073
3074 $content_notes = $subj['content'];
3075 $content_mini_notes = substr($content_notes, 0, 99);
3076 $answer_notes = $subj['answer'];
3077 $porn_notes = $subj['porn'];
3078 $id_user_from_notes = $subj['id_user_from'];
3079 $id_user_to_notes = $subj['id_user_to'];
3080 $work_time_year_from_notes = $subj['work_time_year_from'];
3081 $work_time_month_from_notes = $subj['work_time_month_from'];
3082 $work_time_day_from_notes = $subj['work_time_day_from'];
3083 $work_time_year_to_notes = $subj['work_time_year_to'];
3084 $work_time_month_to_notes = $subj['work_time_month_to'];
3085 $work_time_day_to_notes = $subj['work_time_day_to'];
3086 $datetime_answer_notes = $subj['datetime_answer'];
3087
3088 $from_mktime = mktime(0, 0, 0, $work_time_month_from_notes ? $work_time_month_from_notes : date('m'), $work_time_day_from_notes ? $work_time_day_from_notes : date('d'), $work_time_year_from_notes ? $work_time_year_from_notes : date('Y'));
3089 $to_mktime = mktime(23, 59, 59, $work_time_month_to_notes ? $work_time_month_to_notes : date('m'), $work_time_day_to_notes ? $work_time_day_to_notes : date('d'), $work_time_year_to_notes ? $work_time_year_to_notes : date('Y'));
3090
3091 if (($from_mktime <= mktime() && $to_mktime >= mktime()) || in_array(auth('id'), array(
3092 1,
3093 $id_user_from_notes,
3094 ))) {
3095 $list_notes .= include_virtual("templates/notes_mini_one.html");
3096 }
3097 }
3098 $list_notes .= "</table>";
3099 }
3100 else {
3101 $list_notes = '';
3102 }
3103
3104 return $list_notes;
3105
3106}
3107
3108function mm_in_second_or_m_in_minute_humain($mm_in_second_or_m_in_minute) {
3109 if ($mm_in_second_or_m_in_minute == 'mm_in_second') {
3110 $ret = 'мм/с';
3111 }
3112 if ($mm_in_second_or_m_in_minute == 'm_in_minute') {
3113 $ret = 'м/мин';
3114 }
3115
3116 return $ret;
3117
3118}
3119
3120function select_equipment($id_file) // скрипт подбирает подходящее оборудование под макет для вывода рекомендации оператору
3121{
3122 $id_file = round($id_file);
3123 $equipments = array();
3124
3125 // $id_file - id файла
3126 // получаем размер этого файла и виды работ, содержащиеся в нем, резку, контурную гравировку и гравировку штриховкой
3127 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_files']}` WHERE `id`='{$id_file}';") or die(errorDiv(mysql_error()));
3128 if (mysql_num_rows($result)) {
3129 $file = mysql_fetch_array($result);
3130 }
3131
3132 if (!isset($file)) {
3133 return array(0 => 'Не удалось подобрать оборудование');
3134 }
3135
3136 $unit_speed = mm_in_second_or_m_in_minute_humain(readsql_system("mm_in_second_or_m_in_minute"));
3137
3138 // здесь надо проверить наличие каждой из характеристик и подобрать станок, у которого ширина и высота поля больше, чем у файла при том, что ни одно из этих значений не равно нулю
3139 // и скорости исполнения работ, имеющихся в файле, для этого станка не равны нулю. Выводить список подходящего оборудования начиная с самой большой скорости реза
3140
3141 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_equipment']}`,`{$GLOBALS['TABLE_sup_equipment_label']}` WHERE 1
3142 AND `{$GLOBALS['TABLE_sup_equipment']}`.`position`='1'
3143 AND `{$GLOBALS['TABLE_sup_equipment']}`.`id_user_del`=0
3144 AND `{$GLOBALS['TABLE_sup_equipment']}`.`id`=`{$GLOBALS['TABLE_sup_equipment_label']}`.`id_equipment`
3145 AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`id_label`='{$file['id_label']}'
3146 AND
3147 (
3148 ( `{$GLOBALS['TABLE_sup_equipment']}`.`x` >= '{$file['width']}' AND `{$GLOBALS['TABLE_sup_equipment']}`.`y` >= '{$file['height']}' )
3149 OR
3150 ( `{$GLOBALS['TABLE_sup_equipment']}`.`x` >= '{$file['height']}' AND `{$GLOBALS['TABLE_sup_equipment']}`.`y` >= '{$file['width']}' )
3151 )
3152 AND {$file['width']}!=0
3153 AND {$file['height']}!=0
3154 " . ($file['cut'] ? " AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`speed_cut`>0 " : '') . "
3155 " . ($file['engrave_contur'] ? " AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`speed_engrave_cut`>0 " : '') . "
3156 " . ($file['engrave_scan'] ? " AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`speed_engrave_scan`>0 " : '') . "
3157 ORDER BY `{$GLOBALS['TABLE_sup_equipment_label']}`.`speed_cut` DESC;") or die(errorDiv(mysql_error()));
3158 $count = mysql_num_rows($result);
3159
3160 # ФОРМИРУЕМ ЛЕНТУ
3161 if ($count) {
3162 for ($i = 0; $i < $count; $i++) {
3163 $equipment = mysql_fetch_array($result);
3164 $str = '<nobr><b>⊕ ' . $equipment['name'] . '</b></nobr><br />';
3165 if ($file['cut']) {
3166 $str .= '<u>Рез:</u> ' . $equipment['speed_cut'] . ' ' . $unit_speed . ' - ' . $equipment['power_min_cut'] . '/' . $equipment['power_max_cut'] . '<br />';
3167 }
3168 if ($file['engrave_contur']) {
3169 $str .= '<u>Гр.конт.:</u> ' . $equipment['speed_engrave_cut'] . ' ' . $unit_speed . ' - ' . $equipment['power_min_engrave_cut'] . '/' . $equipment['power_max_engrave_cut'] . '<br />';
3170 }
3171 if ($file['engrave_scan']) {
3172 $str .= '<u>Гр.штрих.:</u> ' . $equipment['speed_engrave_scan'] . ' ' . $unit_speed . ' - ' . $equipment['power_engrave_scan'] . ', Шаг ' . $equipment['interval_engrave_scan'] . ' мм<br />';
3173 }
3174 $equipments[$equipment['id_equipment']] = $str;
3175 }
3176 }
3177
3178 if (!$equipments) {
3179 return array(0 => 'Не удалось подобрать оборудование');
3180 }
3181
3182 return $equipments;
3183}
3184
3185function select_equipment_doppossible($id_file) // скрипт подбирает подходящее оборудование под макет для вывода рекомендации оператору
3186{
3187 $id_file = round($id_file);
3188 $equipments = array();
3189
3190 // $id_file - id файла
3191 // получаем размер этого файла и виды работ, содержащиеся в нем, резку, контурную гравировку и гравировку штриховкой
3192 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_files']}` WHERE `id`='{$id_file}';") or die(errorDiv(mysql_error()));
3193 if (mysql_num_rows($result)) {
3194 $file = mysql_fetch_array($result);
3195 }
3196
3197 if (!$file) {
3198 return array(0 => 'Не удалось подобрать оборудование');
3199 }
3200
3201 $unit_speed = mm_in_second_or_m_in_minute_humain(readsql_system("mm_in_second_or_m_in_minute"));
3202
3203 // здесь надо проверить наличие каждой из характеристик и подобрать станок, у которого ширина и высота поля больше, чем у файла при том, что ни одно из этих значений не равно нулю
3204 // и скорости исполнения работ, имеющихся в файле, для этого станка не равны нулю. Выводить список подходящего оборудования начиная с самой большой скорости реза
3205
3206 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_equipment']}`,`{$GLOBALS['TABLE_sup_equipment_label']}` WHERE 1
3207 AND `{$GLOBALS['TABLE_sup_equipment']}`.`position`='1'
3208 AND `{$GLOBALS['TABLE_sup_equipment']}`.`id_user_del`=0
3209 AND `{$GLOBALS['TABLE_sup_equipment']}`.`id`=`{$GLOBALS['TABLE_sup_equipment_label']}`.`id_equipment`
3210 AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`id_label`='{$file['id_label']}'
3211 AND
3212 (
3213 ( `{$GLOBALS['TABLE_sup_equipment']}`.`x` < '{$file['width']}' OR `{$GLOBALS['TABLE_sup_equipment']}`.`y` < '{$file['height']}' )
3214 AND
3215 ( `{$GLOBALS['TABLE_sup_equipment']}`.`x` < '{$file['height']}' OR `{$GLOBALS['TABLE_sup_equipment']}`.`y` < '{$file['width']}' )
3216 )
3217 AND {$file['width']}!=0
3218 AND {$file['height']}!=0
3219 " . ($file['cut'] ? " AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`speed_cut`>0 " : '') . "
3220 " . ($file['engrave_contur'] ? " AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`speed_engrave_cut`>0 " : '') . "
3221 " . ($file['engrave_scan'] ? " AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`speed_engrave_scan`>0 " : '') . "
3222 ORDER BY `{$GLOBALS['TABLE_sup_equipment_label']}`.`speed_cut` DESC;") or die(errorDiv(mysql_error()));
3223 $count = mysql_num_rows($result);
3224
3225 # ФОРМИРУЕМ ЛЕНТУ
3226 if ($count) {
3227 for ($i = 0; $i < $count; $i++) {
3228 $equipment = mysql_fetch_array($result);
3229 $str = '<nobr><b>⊕ ' . $equipment['name'] . '</b></nobr><br />';
3230 if ($file['cut']) {
3231 $str .= '<u>Рез:</u> ' . $equipment['speed_cut'] . ' ' . $unit_speed . ' - ' . $equipment['power_min_cut'] . '/' . $equipment['power_max_cut'] . '<br />';
3232 }
3233 if ($file['engrave_contur']) {
3234 $str .= '<u>Гр.конт.:</u> ' . $equipment['speed_engrave_cut'] . ' ' . $unit_speed . ' - ' . $equipment['power_min_engrave_cut'] . '/' . $equipment['power_max_engrave_cut'] . '<br />';
3235 }
3236 if ($file['engrave_scan']) {
3237 $str .= '<u>Гр.штрих.:</u> ' . $equipment['speed_engrave_scan'] . ' ' . $unit_speed . ' - ' . $equipment['power_engrave_scan'] . ', Шаг ' . $equipment['interval_engrave_scan'] . ' мм<br />';
3238 }
3239 $equipments[$equipment['id_equipment']] = $str;
3240 }
3241 }
3242
3243 if (!$equipments) {
3244 return array(0 => 'Не удалось подобрать оборудование');
3245 }
3246
3247 return $equipments;
3248}
3249
3250function select_equipment_for_gant($id_files_projects) // здесь мы должны подобрать станок, который быстрее всего выдаст готовое изделие, учитывая свою загруженность
3251{
3252
3253 // $id_files_projects - id записи о связи файла и проекта
3254 // получаем запись о связи, с требуемым количеством,
3255 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_files_projects']}` WHERE `id`='{$id_files_projects}';") or die(errorDiv(mysql_error()));
3256 if (mysql_num_rows($result)) {
3257 $files_projects = mysql_fetch_array($result);
3258 }
3259
3260 if (!$files_projects) {
3261 echo 'Ошибка 1 при построении диаграммы';
3262 die();
3263 }
3264
3265 $id_file = round($files_projects['id_file']);
3266
3267 // $id_file - id файла
3268 // получаем размер этого файла и виды работ, содержащиеся в нем, резку, контурную гравировку и гравировку штриховкой
3269 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_files']}` WHERE `id`='{$id_file}';") or die(errorDiv(mysql_error()));
3270 if (mysql_num_rows($result)) {
3271 $file = mysql_fetch_array($result);
3272 }
3273
3274 if (!$file) {
3275 echo 'Ошибка 2 при построении диаграммы';
3276 die();
3277 }
3278
3279
3280 // надо определить в каких единицах измерения работает производство и подставить соответствующий коэффициент пересчета, т.к. независимо от того, в каких
3281 // единицах измерения работает производство - калькулятор все загружает в мм./с.
3282 $unit_speed = readsql_system("mm_in_second_or_m_in_minute");
3283 if ($unit_speed == "m_in_minute") {
3284 $k_conversion = 16.667;
3285 }
3286 else {
3287 $k_conversion = 1;
3288 } // коэффициент перевода м./мин. в мм./сек.
3289
3290
3291 // если в макете указан предпочтительный станок и в данный момент времени макет уже не определен на какой конкретный станок (что после обнуление в rebuild означает, что на нем кто-то уже работает), то закидывать макеты будем только на него.
3292 if (round($file['id_equipment']) && !round($files_projects['id_equipment'])) {
3293 $files_projects['id_equipment'] = $file['id_equipment'];
3294 }
3295
3296 // проверяем, что станок на котором остановились рабочий и подходит под наше изделие, если не подходит, то сбросить его, дальше сами определим
3297 if (
3298 !in_array($files_projects['id_equipment'], array_keys(select_equipment($id_file))) // если станка нет ни в абсолютно подходящем списке
3299 &&
3300 !in_array($files_projects['id_equipment'], array_keys(select_equipment_doppossible($id_file))) // , ни в списке возможных станков, то обнуляем его. Дальше установим сами
3301 ) {
3302 $files_projects['id_equipment'] = 0;
3303 // также следует сбросить protect с этого макета в этом проекте, в случае, если protect установлен менеджером, НО станок был заменен, чтобы не казалось, что менеджер назначил на другой, ведь это не так
3304 mysql_query("UPDATE `{$GLOBALS['TABLE_sup_files_projects']}` SET `protect`='0' WHERE `id`='{$id_files_projects}';") or die(errorDiv(mysql_error()));
3305 }
3306
3307 // если этот макет УЖЕ определен на какой-то из станков, то мы не будем осуществлять повтороный поиск наиболее подходящего станка и этот же станок и вернем
3308 // КАК ПРАВИЛО, ЭТО СИТУАЦИЯ ВОЗМОЖНА ТОЛЬКО КОГДА ОПЕРАТОР УЖЕ ПРИСТУПИЛ К ВЫПОЛНЕНИЮ ЗАКАЗА, ТОЛЬКО В ЭТОМ СЛУЧАЕ СТАНОК НЕ СБРОСИТСЯ в rebuild
3309
3310 if ($files_projects['id_equipment']) // если указан предпочтительный станок и время производства, ЭТО ЗНАЧИТ, ЧТО ОПЕРАТОР МАКЕТА ТОЖЕ УЖЕ ЕСТЬ
3311 {
3312
3313 $fast_id_equipment = $files_projects['id_equipment'];
3314 $time_production = 0;
3315
3316 // здесь надо проверить наличие каждой из характеристик и подобрать станок, у которого ширина и высота поля больше, чем у файла при том, что ни одно из этих значений у файла не равно нулю
3317 // и скорости исполнения работ, имеющихся в файле, для этого станка не равны нулю. Выводить список подходящего оборудования начиная с самой большой скорости реза
3318 // ЕСЛИ ВНИМАТЕЛЬНО ПРОЧИТАТЬ ЗАПРОС, ТО УВИДИМ, ЧТО ВЫБОР СТАНКОВ ОГРАНИЧИВАЕТСЯ ОДНИМ РЕКОМЕНДУЕМЫМ, НА ОСНОВЕ ЕГО И БУДЕМ ОПРЕДЕЛЯТЬ ОСТАЛЬНЫЕ ПАРАМЕТРЫ, А Т.Е. ВРЕМЯ НЕОБХОДИМОЕ ДЛЯ ИЗГОТОВЛЕНИЯ ИЗДЕЛИЯ
3319 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_equipment']}`,`{$GLOBALS['TABLE_sup_equipment_label']}` WHERE
3320 1
3321 AND `{$GLOBALS['TABLE_sup_equipment']}`.`id`='{$fast_id_equipment}'
3322 AND `{$GLOBALS['TABLE_sup_equipment']}`.`position`='1'
3323 AND `{$GLOBALS['TABLE_sup_equipment']}`.`id_user_del`=0
3324 AND `{$GLOBALS['TABLE_sup_equipment']}`.`id`=`{$GLOBALS['TABLE_sup_equipment_label']}`.`id_equipment`
3325 AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`id_label`='{$file['id_label']}'
3326 /* AND
3327 (
3328 ( `{$GLOBALS['TABLE_sup_equipment']}`.`x` >= '{$file['width']}' AND `{$GLOBALS['TABLE_sup_equipment']}`.`y` >= '{$file['height']}' )
3329 OR
3330 ( `{$GLOBALS['TABLE_sup_equipment']}`.`x` >= '{$file['height']}' AND `{$GLOBALS['TABLE_sup_equipment']}`.`y` >= '{$file['width']}' )
3331 )
3332 */
3333 AND '{$file['width']}'!='0'
3334 AND '{$file['height']}'!='0'
3335 AND ('{$file['cut']}'!='0' OR '{$file['engrave_contur']}'!='0' OR '{$file['engrave_scan']}'!='0')
3336 " . ($file['id_equipment_exception'] ? " AND '{$file['id_equipment_exception']}' NOT LIKE CONCAT('%,',`{$GLOBALS['TABLE_sup_equipment']}`.`id`,',%') " : '') . " /* если для макета указаны станки исключения, то добавляем условия, что id станка не должно быть в списке станков исключений */
3337 " . ($file['cut'] ? " AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`speed_cut`>'0' " : '') . "
3338 " . ($file['engrave_contur'] ? " AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`speed_engrave_cut`>'0' " : '') . "
3339 " . ($file['engrave_scan'] ? " AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`speed_engrave_scan`>'0' AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`interval_engrave_scan`>'0' " : '') . "
3340 ;") or die(errorDiv(mysql_error()));
3341
3342 $count = mysql_num_rows($result);
3343
3344 $files_projects['id_equipment'] = 0; // сбрасываем станок определенный по умолчанию, чтобы переопределить его ниже, если таковой будет по условиям выше
3345
3346 # перебираем станки
3347 if ($count) {
3348 for ($i = 0; $i < $count; $i++) {
3349 $equipment = mysql_fetch_array($result);
3350
3351 // определяем изделие на станок, который достали из запроса
3352 $files_projects['id_equipment'] = $equipment['id_equipment'];
3353 // сначала определим время, которое затратит ЭТОТ станок на изготовление партии этих изделий
3354 // если в файле есть резка, то вычисляем время, которые затратит на резку этот станок
3355 if ($file['cut']) {
3356 $time_cut = $file['cut'] / round($equipment['speed_cut'] * $k_conversion, 1);
3357 }
3358 else {
3359 $time_cut = 0;
3360 } // !!! здесь мы не учитываем время затраченное на переход станка от линии к линии, возможно следует ввести какой-то коэффициент
3361 // если в файле есть контурная гравировка, то вычисляем время, которые затратит на контурную гравировку этот станок
3362 if ($file['engrave_contur']) {
3363 $time_contur = $file['engrave_contur'] / round($equipment['speed_engrave_cut'] * $k_conversion, 1);
3364 }
3365 else {
3366 $time_contur = 0;
3367 } // !!! здесь мы не учитываем время затраченное на переход станка от линии к линии, возможно следует ввести какой-то коэффициент
3368 // если в файле есть гравировка штриховкой, то вычисляем время, которые затратит на гравировку штриховкой этот станок
3369 if ($file['engrave_scan']) {
3370 $time_scan = $file['engrave_scan'] / ($equipment['speed_engrave_scan'] * $equipment['interval_engrave_scan']);
3371 }
3372 else {
3373 $time_scan = 0;
3374 } // !!! здесь мы не учитываем время разгона станка при гравировки, возможно следует ввести какой-то коэффициент
3375
3376 $time_production = round(($time_cut + $time_contur + $time_scan) * $files_projects['count'] * $equipment['kprepare'], 2); // время требуемое для изготовление всей партии
3377 // говорим, что быстрейший станок тот, который достали из запроса
3378 $fast_id_equipment = $files_projects['id_equipment'];
3379 }
3380 }
3381 // если после всех этих вычислений оказалось, что станок не определен (значит назначенный станок не подошел), сбрасываем protect
3382 // ВОЗМОЖНО, НЕ СТОИТ СБРАСЫВАТЬ protect, ЕСЛИ ВЫБРАННЫЙ СТАНОК БОЛЬШЕ НЕ ПОДХОДИТ (ПОПАЛ В СПИСОК ИСКЛЮЧЕНИЙ), ИНАЧЕ ПОЛУЧАЕТСЯ, ЧТО МАКЕТ БЫЛ ВРУЧНУЮ НАЗНАЧЕН НА КАКОЙ-ТО СТАНОК ПЕРВЫМ, ЭТОТ СТАНОК БЫЛ ПОЗЖЕ ДОБАВЛЕН В СПИСОК ИСКЛЮЧЕНИЙ ЭТОГО МАКЕТА, И СИСТЕМА СБРАСЫВАЕТ ЕМУ protect И ПЕРЕОПРЕДЕЛЯЕТ ЕГО НА ДРУГОЙ СТАНОК, НО УЖЕ НЕ ПЕРВЫМ, А В ПОРЯДКЕ ОЧЕРЕДИ, Т.Е. КУДА-ТО ДАЛЕКО. А ЭТО ПЛОХО.
3383 // if(!$files_projects['id_equipment']) mysql_query("UPDATE `{$GLOBALS['TABLE_sup_files_projects']}` SET `protect`='0' WHERE `id`='{$id_files_projects}';") or die(errorDiv(mysql_error()));
3384
3385 }
3386 // если не указан станок, вычисляем
3387 if (!$files_projects['id_equipment']) {
3388 // по умолчанию на случай, если станок подобрать не удастся, выставляем дефолтные параметры
3389 $min_finaltime = 0; // ранее время выхода в свет изделия
3390 $fast_id_equipment = 0; // быстрейший станок
3391 $time_production = 0; // 1 час (не знаю, что такое 1 час, но это время изготовления изделия)
3392
3393 // здесь надо проверить наличие каждой из характеристик и подобрать станок, у которого ширина и высота поля больше, чем у файла при том, что ни одно из этих значений у файла не равно нулю
3394 // и скорости исполнения работ, имеющихся в файле, для этого станка не равны нулю. Выводить список подходящего оборудования начиная с самой большой скорости реза
3395 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_equipment']}`,`{$GLOBALS['TABLE_sup_equipment_label']}` WHERE
3396 1
3397 AND `{$GLOBALS['TABLE_sup_equipment']}`.`position`='1'
3398 AND `{$GLOBALS['TABLE_sup_equipment']}`.`id_user_del`=0
3399 AND `{$GLOBALS['TABLE_sup_equipment']}`.`id`=`{$GLOBALS['TABLE_sup_equipment_label']}`.`id_equipment`
3400 AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`id_label`='{$file['id_label']}'
3401 AND
3402 (
3403 ( `{$GLOBALS['TABLE_sup_equipment']}`.`x` >= '{$file['width']}' AND `{$GLOBALS['TABLE_sup_equipment']}`.`y` >= '{$file['height']}' )
3404 OR
3405 ( `{$GLOBALS['TABLE_sup_equipment']}`.`x` >= '{$file['height']}' AND `{$GLOBALS['TABLE_sup_equipment']}`.`y` >= '{$file['width']}' )
3406 )
3407 AND '{$file['width']}'!='0'
3408 AND '{$file['height']}'!='0'
3409 AND ('{$file['cut']}'!='0' OR '{$file['engrave_contur']}'!='0' OR '{$file['engrave_scan']}'!='0')
3410 " . ($file['id_equipment_exception'] ? " AND '{$file['id_equipment_exception']}' NOT LIKE CONCAT('%,',`{$GLOBALS['TABLE_sup_equipment']}`.`id`,',%') " : '') . " /* если для макета указаны станки исключения, то добавляем условия, что id станка не должно быть в списке станков исключений */
3411 " . ($file['cut'] ? " AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`speed_cut`>'0' " : '') . "
3412 " . ($file['engrave_contur'] ? " AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`speed_engrave_cut`>'0' " : '') . "
3413 " . ($file['engrave_scan'] ? " AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`speed_engrave_scan`>'0' AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`interval_engrave_scan`>'0' " : '') . "
3414 ORDER BY `{$GLOBALS['TABLE_sup_equipment_label']}`.`speed_cut` DESC;") or die(errorDiv(mysql_error()));
3415
3416 $count = mysql_num_rows($result);
3417
3418 # перебираем станки
3419 if ($count) {
3420 for ($i = 0; $i < $count; $i++) {
3421 $equipment = mysql_fetch_array($result);
3422
3423 // сначала определим время, которое затратит ЭТОТ станок на изготовление партии этих изделий
3424 // если в файле есть резка, то вычисляем время, которые затратит на резку этот станок
3425 if ($file['cut']) {
3426 $time_cut = $file['cut'] / round($equipment['speed_cut'] * $k_conversion, 1);
3427 }
3428 else {
3429 $time_cut = 0;
3430 } // !!! здесь мы не учитываем время затраченное на переход станка от линии к линии, возможно следует ввести какой-то коэффициент
3431 // если в файле есть контурная гравировка, то вычисляем время, которые затратит на контурную гравировку этот станок
3432 if ($file['engrave_contur']) {
3433 $time_contur = $file['engrave_contur'] / round($equipment['speed_engrave_cut'] * $k_conversion, 1);
3434 }
3435 else {
3436 $time_contur = 0;
3437 } // !!! здесь мы не учитываем время затраченное на переход станка от линии к линии, возможно следует ввести какой-то коэффициент
3438 // если в файле есть гравировка штриховкой, то вычисляем время, которые затратит на гравировку штриховкой этот станок
3439 if ($file['engrave_scan']) {
3440 $time_scan = $file['engrave_scan'] / ($equipment['speed_engrave_scan'] * $equipment['interval_engrave_scan']);
3441 }
3442 else {
3443 $time_scan = 0;
3444 } // !!! здесь мы не учитываем время разгона станка при гравировки, возможно следует ввести какой-то коэффициент
3445
3446 // теперь нам нужно определить длительность очереди на этот станок только из макетов в запущенных и проблемных проектах
3447 $turn_time = round(SUM($GLOBALS['TABLE_sup_files_projects'], "time", " AND `id_equipment`='{$equipment['id_equipment']}' AND `id_project` IN (SELECT `id` FROM `{$GLOBALS['TABLE_sup_projects']}` WHERE `status` IN ('10','20','21','22') AND `visible`='1' AND `id_user_del`='0') "));
3448
3449
3450 // записываем время, когда станок закончит изготовление этого изделия
3451 $equipments[$equipment['id_equipment']]['finaltime'] = round(($time_cut + $time_contur + $time_scan) * $files_projects['count'] * $equipment['kprepare'] + $turn_time, 2);
3452
3453 // теперь нам следует следить с какого станка это изделия в нужном количестве выйдет раньше всего и если с каждого нового станка время выхода будет меньше, то
3454 // запоминать все новый и новый станок
3455
3456 // если ранее время изготовления изделия не было запомнено, то записываем его, как время выхода изделия с этого станка
3457 if (!$min_finaltime) {
3458 $min_finaltime = $equipments[$equipment['id_equipment']]['finaltime'];
3459 }
3460 // если время выхода с этого станка меньше или равно запомненному минимальному времени, то
3461 if ($equipments[$equipment['id_equipment']]['finaltime'] <= $min_finaltime) { // переустанавливаем новое минимальное время выхода изделия
3462 $min_finaltime = $equipments[$equipment['id_equipment']]['finaltime'];
3463 // перезаписываем id станка, которой выдаст лучший результат
3464 $fast_id_equipment = $equipment['id_equipment'];
3465 // записываем время, которое потребуется на изготовление этого изделия
3466 $time_production = round(($time_cut + $time_contur + $time_scan) * $files_projects['count'] * $equipment['kprepare'], 2);
3467 }
3468
3469 // / теперь нам следует следить с какого станка это изделия в нужном количестве выйдет раньше всего и если с каждого нового станка время выхода будет меньше, то
3470 // / запоминать все новый и новый станок
3471
3472 }
3473 }
3474 }
3475
3476 return array(
3477 "id_equipment" => $fast_id_equipment,
3478 // на какой станок отправляем
3479 "time_production" => $time_production
3480 // сколько будет изготавливаться
3481 );
3482
3483 // echo $fast_id_equipment.': выйдет через: '.$min_finaltime.' с. ; в производстве будет: '.$time_production.' c.<br />';
3484
3485 // if(!$min_id_equipment) return array(0=>'Ошибка 3 при построении диаграммы Ганта');
3486
3487 // return $equipments;
3488}
3489
3490/*
3491 function select_equipment_for_gant($id_files_projects) // здесь мы должны подобрать станок, который быстрее всего выдаст готовое изделие, учитывая свою загруженность
3492 {
3493
3494 // $id_files_projects - id записи о связи файла и проекта
3495 // получаем запись о связи, с требуемым количеством,
3496 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_files_projects']}` WHERE `id`='{$id_files_projects}';") or die(errorDiv(mysql_error()));
3497 if (mysql_num_rows($result))
3498 { $files_projects=mysql_fetch_array($result);
3499 }
3500
3501 if(!$files_projects)
3502 { echo 'Ошибка 1 при построении диаграммы';
3503 die();
3504 }
3505
3506 $id_file=round($files_projects['id_file']);
3507
3508 // $id_file - id файла
3509 // получаем размер этого файла и виды работ, содержащиеся в нем, резку, контурную гравировку и гравировку штриховкой
3510 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_files']}` WHERE `id`='{$id_file}';") or die(errorDiv(mysql_error()));
3511 if (mysql_num_rows($result))
3512 { $file=mysql_fetch_array($result);
3513 }
3514
3515 if(!$file)
3516 { echo 'Ошибка 2 при построении диаграммы';
3517 die();
3518 }
3519
3520
3521 // надо определить в каких единицах измерения работает производство и подставить соответствующий коэффициент пересчета, т.к. независимо от того, в каких
3522 // единицах измерения работает производство - калькулятор все загружает в мм./с.
3523 $unit_speed=readsql_system("mm_in_second_or_m_in_minute");
3524 if($unit_speed=="m_in_minute") $k_conversion=16.667; else $k_conversion=1; // коэффициент перевода м./мин. в мм./сек.
3525
3526
3527
3528 // если в макете указан предпочтительный станок и в данный момент времени макет уже не определен на какой конкретный станок (что после обнуление в rebuil означает, что на нем кто-то уже работает), то закидывать макеты будем только на него.
3529 if($file['id_equipment']&&!$files_projects['id_equipment']) $files_projects['id_equipment']=$file['id_equipment'];
3530
3531 // проверяем, что станок на котором остановились рабочий и подходит под наше изделие, если не подходит, то сбросить его, дальше сами определим
3532 if (
3533 !in_array($files_projects['id_equipment'],array_keys(select_equipment($id_file))) // если станка нет ни в абсолютно подходящем списке
3534 &&
3535 !in_array($files_projects['id_equipment'],array_keys(select_equipment_doppossible($id_file))) // , ни в списке возможных станков, то обнуляем его. Дальше установим сами
3536 )
3537 { $files_projects['id_equipment']=0;
3538 // также следует сбросить protect с этого макета в этом проекте, в случае, если protect установлен менеджером, НО станок был заменен, чтобы не казалось, что менеджер назначил на другой, ведь это не так
3539 mysql_query("UPDATE `{$GLOBALS['TABLE_sup_files_projects']}` SET `protect`='0' WHERE `id`='{$id_files_projects}';") or die(errorDiv(mysql_error()));
3540 }
3541
3542 // если этот макет УЖЕ определен на какой-то из станков, то мы не будем осуществлять повтороный поиск наиболее подходящего станка и этот же станок и вернем
3543 // КАК ПРАВИЛО, ЭТО СИТУАЦИЯ ВОЗМОЖНА ТОЛЬКО КОГДА ОПЕРАТОР УЖЕ ПРИСТУПИЛ К ВЫПОЛНЕНИЮ ЗАКАЗА, ТОЛЬКО В ЭТОМ СЛУЧАЕ СТАНОК НЕ СБРОСИТСЯ в rebuild
3544/* if($files_projects['id_equipment']&&$files_projects['time']) // если указан предпочтительный станок и время производства, ЭТО ЗНАЧИТ, ЧТО ОПЕРАТОР МАКЕТА ТОЖЕ УЖЕ ЕСТЬ
3545 {
3546 $fast_id_equipment=$files_projects['id_equipment'];
3547 $time_production=$files_projects['time'];
3548
3549 } elseif($files_projects['id_equipment']&&!$files_projects['time']) // если указан предпочтительный станок и по каким-то причина НЕ указано время производства, например, если мы вручную перекинули изделие на другой станок (хотя не факт)
3550 {
3551 // высчитываем время производства
3552
3553 $fast_id_equipment=$files_projects['id_equipment'];
3554 $time_production = 0;
3555
3556 // здесь надо проверить наличие каждой из характеристик и подобрать станок, у которого ширина и высота поля больше, чем у файла при том, что ни одно из этих значений у файла не равно нулю
3557 // и скорости исполнения работ, имеющихся в файле, для этого станка не равны нулю. Выводить список подходящего оборудования начиная с самой большой скорости реза
3558 // ЕСЛИ ВНИМАТЕЛЬНО ПРОЧИТАТЬ ЗАПРОС, ТО УВИДИМ, ЧТО ВЫБОР СТАНКОВ ОГРАНИЧИВАЕТСЯ ОДНИМ РЕКОМЕНДУЕМЫМ, НА ОСНОВЕ ЕГО И БУДЕМ ОПРЕДЕЛЯТЬ ОСТАЛЬНЫЕ ПАРАМЕТРЫ, А Т.Е. ВРЕМЯ НЕОБХОДИМОЕ ДЛЯ ИЗГОТОВЛЕНИЯ ИЗДЕЛИЯ
3559 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_equipment']}`,`{$GLOBALS['TABLE_sup_equipment_label']}` WHERE `{$GLOBALS['TABLE_sup_equipment']}`.`position`='1' AND `{$GLOBALS['TABLE_sup_equipment']}`.`id_user_del`=0 AND `{$GLOBALS['TABLE_sup_equipment']}`.`id`=`{$GLOBALS['TABLE_sup_equipment_label']}`.`id_equipment` AND `{$GLOBALS['TABLE_sup_equipment']}`.`id`='{$fast_id_equipment}' AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`id_label`='{$file['id_label']}' AND ( (`{$GLOBALS['TABLE_sup_equipment']}`.`x`>='{$file['width']}' AND `{$GLOBALS['TABLE_sup_equipment']}`.`y`>='{$file['height']}') OR (`{$GLOBALS['TABLE_sup_equipment']}`.`x`>='{$file['height']}' AND `{$GLOBALS['TABLE_sup_equipment']}`.`y`>='{$file['width']}') ) AND '{$file['width']}'!='0' AND '{$file['height']}'!='0' AND ('{$file['cut']}'!='0' OR '{$file['engrave_contur']}'!='0' OR '{$file['engrave_scan']}'!='0') ".($file['cut']?" AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`speed_cut`>'0' ":'').($file['engrave_contur']?" AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`speed_engrave_cut`>'0' ":'').($file['engrave_scan']?" AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`speed_engrave_scan`>'0' AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`interval_engrave_scan`>'0' ":'')." ORDER BY `{$GLOBALS['TABLE_sup_equipment_label']}`.`speed_cut` DESC;") or die(errorDiv(mysql_error()));
3560 $count = mysql_num_rows($result);
3561
3562 # ФОРМИРУЕМ ЛЕНТУ
3563 if ($count)
3564 { for ($i=0; $i<$count; $i++)
3565 { $equipment=mysql_fetch_array($result);
3566
3567 // сначала определим время, которое затратит ЭТОТ станок на изготовление партии этих изделий
3568 // если в файле есть резка, то вычисляем время, которые затратит на резку этот станок
3569 if($file['cut']) $time_cut=$file['cut']/round($equipment['speed_cut']*$k_conversion,1); else $time_cut=0; // !!! здесь мы не учитываем время затраченное на переход станка от линии к линии, возможно следует ввести какой-то коэффициент
3570 // если в файле есть контурная гравировка, то вычисляем время, которые затратит на контурную гравировку этот станок
3571 if($file['engrave_contur']) $time_contur=$file['engrave_contur']/round($equipment['speed_engrave_cut']*$k_conversion,1); else $time_contur=0; // !!! здесь мы не учитываем время затраченное на переход станка от линии к линии, возможно следует ввести какой-то коэффициент
3572 // если в файле есть гравировка штриховкой, то вычисляем время, которые затратит на гравировку штриховкой этот станок
3573 if($file['engrave_scan']) $time_scan=$file['engrave_scan']/($equipment['speed_engrave_scan']*$equipment['interval_engrave_scan']); else $time_scan=0; // !!! здесь мы не учитываем время разгона станка при гравировки, возможно следует ввести какой-то коэффициент
3574
3575 $time_production=round(($time_cut+$time_contur+$time_scan)*$files_projects['count'],2); // время требуемое для изготовление всей партии
3576 }
3577 }
3578
3579 } else // если не указан станок, вычисляем
3580 {
3581 // по умолчанию на случай, если станок подобрать не удастся, выставляем дефолтные параметры
3582 $min_finaltime = 0; // ранее время выхода в свет изделия
3583 $fast_id_equipment = 0; // быстрейший станок
3584 $time_production = 0; // 1 час (не знаю, что такое 1 час, но это время изготовления изделия)
3585
3586 // здесь надо проверить наличие каждой из характеристик и подобрать станок, у которого ширина и высота поля больше, чем у файла при том, что ни одно из этих значений у файла не равно нулю
3587 // и скорости исполнения работ, имеющихся в файле, для этого станка не равны нулю. Выводить список подходящего оборудования начиная с самой большой скорости реза
3588 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_equipment']}`,`{$GLOBALS['TABLE_sup_equipment_label']}` WHERE `{$GLOBALS['TABLE_sup_equipment']}`.`position`='1' AND `{$GLOBALS['TABLE_sup_equipment']}`.`id_user_del`=0 AND `{$GLOBALS['TABLE_sup_equipment']}`.`id`=`{$GLOBALS['TABLE_sup_equipment_label']}`.`id_equipment` AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`id_label`='{$file['id_label']}' AND ( (`{$GLOBALS['TABLE_sup_equipment']}`.`x`>='{$file['width']}' AND `{$GLOBALS['TABLE_sup_equipment']}`.`y`>='{$file['height']}') OR (`{$GLOBALS['TABLE_sup_equipment']}`.`x`>='{$file['height']}' AND `{$GLOBALS['TABLE_sup_equipment']}`.`y`>='{$file['width']}') ) AND '{$file['width']}'!='0' AND '{$file['height']}'!='0' AND ('{$file['cut']}'!='0' OR '{$file['engrave_contur']}'!='0' OR '{$file['engrave_scan']}'!='0') ".($file['cut']?" AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`speed_cut`>'0' ":'').($file['engrave_contur']?" AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`speed_engrave_cut`>'0' ":'').($file['engrave_scan']?" AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`speed_engrave_scan`>'0' AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`interval_engrave_scan`>'0' ":'')." ORDER BY `{$GLOBALS['TABLE_sup_equipment_label']}`.`speed_cut` DESC;") or die(errorDiv(mysql_error()));
3589 $count = mysql_num_rows($result);
3590
3591 # перебираем станки
3592 if ($count)
3593 { for ($i=0; $i<$count; $i++)
3594 { $equipment=mysql_fetch_array($result);
3595
3596 // сначала определим время, которое затратит ЭТОТ станок на изготовление партии этих изделий
3597 // если в файле есть резка, то вычисляем время, которые затратит на резку этот станок
3598 if($file['cut']) $time_cut=$file['cut']/round($equipment['speed_cut']*$k_conversion,1); else $time_cut=0; // !!! здесь мы не учитываем время затраченное на переход станка от линии к линии, возможно следует ввести какой-то коэффициент
3599 // если в файле есть контурная гравировка, то вычисляем время, которые затратит на контурную гравировку этот станок
3600 if($file['engrave_contur']) $time_contur=$file['engrave_contur']/round($equipment['speed_engrave_cut']*$k_conversion,1); else $time_contur=0; // !!! здесь мы не учитываем время затраченное на переход станка от линии к линии, возможно следует ввести какой-то коэффициент
3601 // если в файле есть гравировка штриховкой, то вычисляем время, которые затратит на гравировку штриховкой этот станок
3602 if($file['engrave_scan']) $time_scan=$file['engrave_scan']/($equipment['speed_engrave_scan']*$equipment['interval_engrave_scan']); else $time_scan=0; // !!! здесь мы не учитываем время разгона станка при гравировки, возможно следует ввести какой-то коэффициент
3603
3604 // теперь нам нужно определить длительность очереди на этот станок только из макетов в запущенных и проблемных проектах
3605 $turn_time=round(SUM($GLOBALS['TABLE_sup_files_projects'],"time"," AND `id_equipment`='{$equipment['id_equipment']}' AND `id_project` IN (SELECT `id` FROM `{$GLOBALS['TABLE_sup_projects']}` WHERE `status` IN ('10','20','21','22') AND `visible`=1 AND `id_user_del`='0') "));
3606
3607
3608 // записываем время, когда станок закончит изготовление этого изделия
3609 $equipments[$equipment['id_equipment']]['finaltime']=round(($time_cut+$time_contur+$time_scan)*$files_projects['count']+$turn_time,2);
3610
3611 // теперь нам следует следить с какого станка это изделия в нужном количестве выйдет раньше всего и если с каждого нового станка время выхода будет меньше, то
3612 // запоминать все новый и новый станок
3613
3614 // echo $equipment['id_equipment'].': очередь: '.$turn_time.' с. ; в производстве будет: '.$equipments[$equipment['id_equipment']]['finaltime'].' c.<br />';
3615
3616 //echo '*';
3617 //if($id_file=='11887')echo $equipments[$equipment['id_equipment']]['finaltime'].' ';
3618 //if($id_file=='11887')echo $equipment['id_equipment'].'id ';
3619 //if($id_file=='11887')echo round(($time_cut+$time_contur+$time_scan)*$files_projects['count'],2).'<br />';
3620
3621 // если ранее время изготовления изделия не было запомнено, то записываем его, как время выхода изделия с этого станка
3622 if(!$min_finaltime)$min_finaltime=$equipments[$equipment['id_equipment']]['finaltime'];
3623 // если время выхода с этого станка меньше или равно запомненному минимальному времени, то
3624 if($equipments[$equipment['id_equipment']]['finaltime']<=$min_finaltime)
3625 { // переустанавливаем новое минимальное время выхода изделия
3626 $min_finaltime=$equipments[$equipment['id_equipment']]['finaltime'];
3627 // перезаписываем id станка, которой выдаст лучший результат
3628 $fast_id_equipment=$equipment['id_equipment'];
3629 // записываем время, которое потребуется на изготовление этого изделия
3630 $time_production=round(($time_cut+$time_contur+$time_scan)*$files_projects['count'],2);
3631 }
3632
3633 // / теперь нам следует следить с какого станка это изделия в нужном количестве выйдет раньше всего и если с каждого нового станка время выхода будет меньше, то
3634 // / запоминать все новый и новый станок
3635
3636 }
3637 }
3638 }
3639
3640 return array(
3641 "id_equipment"=>$fast_id_equipment, // на какой станок отправляем
3642 "time_production"=>$time_production // сколько будет изготавливаться
3643 );
3644
3645 // echo $fast_id_equipment.': выйдет через: '.$min_finaltime.' с. ; в производстве будет: '.$time_production.' c.<br />';
3646
3647 // if(!$min_id_equipment) return array(0=>'Ошибка 3 при построении диаграммы Ганта');
3648
3649 // return $equipments;
3650 }
3651 */
3652
3653
3654function turn_on_the_equipment($id_equipment, $deadline = '') {
3655 $str = '';
3656 $deadline_old = '';
3657 $str_days = '';
3658
3659 // определяем список умений этого пользователя
3660 $list_skills_user = get_me_list_skills_by_id_user(auth('id'));
3661
3662 $result = mysql_query("
3663 SELECT *,
3664 `{$GLOBALS['TABLE_sup_files_projects']}`.`status` AS `status_file`,
3665 `{$GLOBALS['TABLE_sup_files_projects']}`.`id` AS `id_files_projects`,
3666 `{$GLOBALS['TABLE_sup_files_projects']}`.`id_user_operator` AS `id_operator`,
3667 `{$GLOBALS['TABLE_sup_files_projects']}`.`ready` AS `ready_files`,
3668 `{$GLOBALS['TABLE_sup_files_projects']}`.`count` AS `count_files`,
3669 `{$GLOBALS['TABLE_sup_files_projects']}`.`protect` AS `protect_files`,
3670 `{$GLOBALS['TABLE_sup_files_projects']}`.`id_equipment` AS `id_equipment_now`,
3671 `{$GLOBALS['TABLE_sup_files_projects']}`.`porn` AS `porn`,
3672 `{$GLOBALS['TABLE_sup_projects']}`.`name` AS `name_project`,
3673 `{$GLOBALS['TABLE_sup_projects']}`.`id_user_manager` AS `id_user_manager_project`,
3674 `{$GLOBALS['TABLE_sup_projects']}`.`deadline` AS `deadline_project`,
3675 `{$GLOBALS['TABLE_sup_projects']}`.`material` AS `material_project`,
3676 `{$GLOBALS['TABLE_sup_label']}`.`id` AS `id_label`,
3677 `{$GLOBALS['TABLE_sup_label']}`.`name` AS `name_label`,
3678 `{$GLOBALS['TABLE_sup_label']}`.`color` AS `color_label`,
3679 `{$GLOBALS['TABLE_sup_files']}`.`id_equipment` AS `id_equipment_recommendations`,
3680 `{$GLOBALS['TABLE_sup_files']}`.`recommendations` AS `recommendations`,
3681 `{$GLOBALS['TABLE_sup_files']}`.`file_preview` AS `file_preview_file`
3682 FROM `{$GLOBALS['TABLE_sup_files_projects']}`,`{$GLOBALS['TABLE_sup_projects']}`,`{$GLOBALS['TABLE_sup_files']}`,`{$GLOBALS['TABLE_sup_label']}` WHERE
3683 1
3684 AND `{$GLOBALS['TABLE_sup_files_projects']}`.`id_equipment`='{$id_equipment}'
3685 AND `{$GLOBALS['TABLE_sup_files_projects']}`.`porn`!='0'
3686 /* AND `{$GLOBALS['TABLE_sup_projects']}`.`status` IN ('10','20','21','22','23','30','40','50') */
3687 AND `{$GLOBALS['TABLE_sup_projects']}`.`status` IN ('10','20','21','22','23')
3688 AND (
3689 `{$GLOBALS['TABLE_sup_files_projects']}`.`status` IN ('10','20','21','22','23')
3690 /* OR
3691 ( `{$GLOBALS['TABLE_sup_files_projects']}`.`status`='23' AND `{$GLOBALS['TABLE_sup_files_projects']}`.`made` LIKE '" . date('Y-m-d ') . "%' )
3692 */
3693 )
3694 " . ($deadline ? " AND `{$GLOBALS['TABLE_sup_projects']}`.`deadline`='{$deadline}' " : '') . "
3695 " . ($GLOBALS['GET_ids_label'] ? " AND `{$GLOBALS['TABLE_sup_label']}`.`id` IN (" . implode(',', $GLOBALS['GET_ids_label']) . ") " : '') . "
3696 " . ($GLOBALS['GET_width'] && $GLOBALS['GET_height'] ? " AND ( (`{$GLOBALS['TABLE_sup_files']}`.`width` <= " . round($GLOBALS['GET_width']) . "*10 AND `{$GLOBALS['TABLE_sup_files']}`.`height` <= " . round($GLOBALS['GET_height']) . "*10) OR (`{$GLOBALS['TABLE_sup_files']}`.`width` <= " . round($GLOBALS['GET_height']) . "*10 AND `{$GLOBALS['TABLE_sup_files']}`.`height` <= " . round($GLOBALS['GET_width']) . "*10) ) " : '') . "
3697 " . ($GLOBALS['GET_priority'] ? " AND `{$GLOBALS['TABLE_sup_projects']}`.`priority`='3' " : '') . "
3698 " . (round($GLOBALS['GET_ready']) ? " AND `{$GLOBALS['TABLE_sup_projects']}`.`ready`>='" . round($GLOBALS['GET_ready']) . "' " : '') . "
3699 " . (trim($list_skills_user) ? " AND `{$GLOBALS['TABLE_sup_label']}`.`id` IN ({$list_skills_user}) " : '') . " /* и id материала должен входить в список умений пользователя */
3700 AND `{$GLOBALS['TABLE_sup_files']}`.`id_user_del`='0'
3701 /*" . (auth('type') == '3' ? " AND ( `{$GLOBALS['TABLE_sup_files_projects']}`.`id_user_operator`='0' OR `{$GLOBALS['TABLE_sup_files_projects']}`.`id_user_operator`='" . auth('id') . "' ) " : '') . "*/
3702 AND `{$GLOBALS['TABLE_sup_projects']}`.`id_user_del`='0'
3703 AND `{$GLOBALS['TABLE_sup_projects']}`.`visible`='1'
3704 AND `{$GLOBALS['TABLE_sup_files_projects']}`.`id_project`=`{$GLOBALS['TABLE_sup_projects']}`.`id`
3705 AND `{$GLOBALS['TABLE_sup_files_projects']}`.`id_file`=`{$GLOBALS['TABLE_sup_files']}`.`id`
3706 AND `{$GLOBALS['TABLE_sup_files']}`.`id_label`=`{$GLOBALS['TABLE_sup_label']}`.`id`
3707 ORDER BY `{$GLOBALS['TABLE_sup_files_projects']}`.`porn` ASC;") or die(errorDiv(mysql_error()));
3708 $count = mysql_num_rows($result);
3709
3710 # ФОРМИРУЕМ ЛЕНТУ
3711 if ($count) {
3712 // выводим дни с коррекцией ширины каждого дня. Коррекцию определяли выше
3713 if (
3714 (
3715 get_me_position_equipment_by_id_equipment($id_equipment) // получаем данные активен (запущен) станок на котором собираемся выводить изделия или нет
3716 &&
3717 get_me_workinghours_equipment_by_id_equipment($id_equipment) // получаем данные о рабочем времени в день этого станка, оно должно быть больше нуля
3718 )
3719 ||
3720 !$id_equipment // или если это станок "не определено"
3721 ) {
3722 $total_minuts = 0;
3723 $correction = array();
3724
3725 $workinghours = round(get_me_workinghours_equipment_by_id_equipment($id_equipment) * 60); // определяем продолжительность рабочего дня этого станка в минутах
3726 $workinghours_total = round(SUM($GLOBALS['TABLE_sup_files_projects'], 'time', " AND `{$GLOBALS['TABLE_sup_files_projects']}`.`porn`!='0' AND `{$GLOBALS['TABLE_sup_files_projects']}`.`id_equipment`='{$id_equipment}' ") / 60); // определяем общую нагрузку на этот станок в минутах
3727
3728 // if($id_equipment) $workinghours=round(get_me_workinghours_equipment_by_id_equipment($id_equipment)*60); // определяем продолжительность рабочего дня этого станка в минутах
3729 $array_id_label = array();
3730
3731 // получаем список доступных для исполнения макетов на этом станке
3732 $possible_array = check_possible_turn_file($id_equipment, WINDOW_POSSIBLE_LAYOUT);
3733 //print_r($possible_array);
3734
3735 $str = "<table border='0' cellspacing='0' cellpadding='0' style='height:67px;'><tr>";
3736 for ($i = 0; $i < $count; $i++) {
3737 $files_projects = mysql_fetch_array($result);
3738
3739
3740 /*
3741 if($deadline_old!=$files_projects['deadline_project']) // проверяем, сменился ли дедлайн, чтобы выводить его только в случае смены
3742 { if(strtotime($files_projects['deadline_project'])<time()) $deadline_end=1; else $deadline_end=0; // проверяем, истек ли дедлайн
3743 //$str.="<td style=\"vertical-align:middle;\"> <span class=\"".($deadline_end?'red ':'')."supersmall strong\">дедлайн<br /> <nobr class=".($deadline_end?'red strong ':'').">".trim(str_replace('-','.',$files_projects['deadline_project'])).":</nobr></span> </td>";
3744 $deadline_old=$files_projects['deadline_project'];
3745 //$array_id_label=array();
3746 }
3747 */
3748
3749 // определяем возможно ли будет этот макет исполнить, попадает ли он в окно
3750 $possible = 0;
3751 // $possible=check_possible_turn_file($files_projects['id_files_projects'],WINDOW_POSSIBLE_LAYOUT);
3752 if (in_array(auth('type'), array(1, 2))) {
3753 $possible = 1;
3754 }
3755 else {
3756 $possible = in_array($files_projects['id_files_projects'], $possible_array) ? 1 : 0;
3757 }
3758
3759 if ($files_projects['priority'] == '3') {
3760 $col_border = "f00";
3761 }
3762 else {
3763 $col_border = "aaa";
3764 }
3765
3766 if ($files_projects['status_file'] == '23') {
3767 $col_bg = "0f0";
3768 $col_border = "aaa";
3769 } // если выполнен
3770 elseif (in_array($files_projects['status_file'], array(
3771 '21',
3772 '22',
3773 ))) {
3774 $col_bg = "f00"; /* $col_border="000"; */
3775 } // если статус трудности или нехватка материала
3776 else // если все остальные статусы
3777 {
3778 if ($files_projects['id_operator']) {
3779 $col_bg = "fff";
3780 } // если взят в работу (или назначен), то белый фон
3781 else {
3782 $col_bg = "ddd";
3783 } // если не взят в работу, то серый фон
3784 }
3785
3786 if ($possible) {
3787 $fontcolor = '000';
3788 }
3789 else {
3790 $fontcolor = 'ccc';
3791 }
3792 if ($possible) {
3793 $height_block = '57';
3794 }
3795 else {
3796 $height_block = '25';
3797 }
3798
3799 $works_type = array();
3800 if ($files_projects['cut']) {
3801 $works_type[] = "Резка";
3802 }
3803 if ($files_projects['engrave_contur']) {
3804 $works_type[] = "Грав.Конт.";
3805 }
3806 if ($files_projects['engrave_scan']) {
3807 $works_type[] = "Грав.Штрих.";
3808 }
3809
3810 //$lastnumericid=substr(strrev($files_projects['id_label']),0,1); // берем последнюю цифру id, чтобы выбрать цвет.
3811
3812 if (count($array_id_label) < 11) {
3813 if (!in_array($files_projects['id_label'], $array_id_label)) {
3814 $array_id_label[] = $files_projects['id_label'];
3815 } // записываем каждый новый цвет в массиве, чтобы потом из него получить номер каждого цвета в этом дне
3816 $lastnumericid = 12 - array_search($files_projects['id_label'], $array_id_label); // номер этого материала в массиве, чтобы потом задать ему определенный цвет
3817 }
3818 else {
3819 $lastnumericid = 0;
3820 }
3821 if (strlen($lastnumericid) == 1) {
3822 $lastnumericid = '0' . $lastnumericid;
3823 } // формируем часть имени для картинки цвета
3824
3825 // $lastnumericid=$lastnumericid;
3826 // $lastnumericid=array_reverse($lastnumericid);
3827 //echo ' '.$lastnumericid;
3828
3829
3830 $minuts = round($files_projects['time'] / 60); // прибавляем 0,5, чтобы не округлять в сторону нуля
3831
3832 $width = round($files_projects['time'] / 60) * 1; // 1 пиксель равен одной минуте, чтобы монитор шириной в 1000 пикселей отобразил работы на 1000 минут, Т.е. на 16 часов
3833 if ($width < 10) {
3834 $width = 10;
3835 } // если ширина блока меньше 10 пикс, то делаем 10
3836 $width = $width - 4 - 1; // вычитаем с ширины блока 4 пикселя, чтобы компенсировать толщину рамки и еще зазор 1 пиксель между блоками
3837 if (!$id_equipment) {
3838 $width = 40;
3839 } // если станок не определен, то ставим ширину изделию 40, чтобы сходу было видно какой там материал хотя бы
3840
3841 if ($id_equipment) {
3842 $total_minuts += $minuts;
3843 // определяем в какой день приходится изготовление этого изделия, чтобы внести в него корректировку
3844 $day = round(($total_minuts / $workinghours) + 0.5); // округляем в большую сторону, чтобы определить к какому дню относится это изделие
3845 if (isset($correction[$day])) {
3846 $correction[$day] += $width + 4 + 1 + -$minuts;
3847 }
3848 else {
3849 $correction[$day] = $width + 4 + 1 + -$minuts;
3850 } // к ширине блока прибавляем рамку и пробел и вычитаем количество минут, чтобы понять разницу между занимаемым на экране количеством минут и реальным. Эта разница и есть коррекция
3851 // if(auth('type')==1) echo (1+$l++).": день {$day}, всего минут {$total_minuts}, ширина блока {$width}, изделие {$minuts}, коррекция {$correction[$day]}<br>";
3852 }
3853
3854 $str .= "
3855 <td style='vertical-align:bottom;'>
3856 " . ($possible ? "<a href=\"/?p=projects_new&all=1" . ($files_projects['status_file'] == '23' ? '&other=1' : '') . "&id_files_projects={$files_projects['id_files_projects']}\" target=\"_blank\">" : '') . "
3857 <div
3858 class=\"small screenshot\"
3859 style=\" border:2px solid #{$col_border};
3860 margin-right:1px;
3861 display:inline-block;
3862 height:{$height_block}px;
3863 background:#{$col_bg};
3864 overflow:hidden;
3865 width:{$width}px;
3866 " . ($possible ? '' : 'cursor:default;') . "
3867 \"
3868 title=\"
3869
3870 <img src='/functions/thumb.php?filename={$GLOBALS['PUTH_files']}{$files_projects['file_preview_file']}&height=100' style='margin-bottom:7px;border:1px solid #777;' /><br />
3871 <span class='small'>";
3872
3873 $str .= "<strong class='red'>Дедлайн: " . humain_date($files_projects['deadline_project']) . "</strong><br /><br />";
3874
3875 $str .= "Проект: №{$files_projects['id_project']} "" . $files_projects['name_project'] . "" (клиент " . get_me_name_user_by_id_user($files_projects['id_user']) . ")<br />";
3876 $str .= "Макет: №{$files_projects['id_file']} " . ($files_projects['titlefile'] ? '"' . upper_premier_char(str_replace(array(
3877 '"',
3878 "'",
3879 ), '', $files_projects['titlefile'])) . '" ' : '') . "(автор " . get_me_name_user_by_id_user($files_projects['id_user_manager']) . ")<br />";
3880 $str .= "<b>{$files_projects['width']}x{$files_projects['height']} мм.</b>, <b>{$files_projects['name_label']}</b>";
3881 $str .= $files_projects['material_project'] ? " (<span class='red strong small'>{$files_projects['material_project']}</span>)" : '';
3882 $str .= "<br /><br />";
3883
3884 $str .= "Готовность: <b>" . $files_projects['ready_files'] . '/' . $files_projects['count_files'] . " шт.</b><br />";
3885 $str .= "Виды работ: " . implode(' + ', $works_type);
3886
3887 $str .= get_me_kprepare_equipment_by_id_equipment($id_equipment) ? (", <nobr>расч.время ~ {$minuts} мин., машин.время ~ " . round($minuts / get_me_kprepare_equipment_by_id_equipment($id_equipment)) . " мин.</nobr>") : '';
3888
3889 $str .= ", S = " . round($files_projects['width'] * $files_projects['height'] / 1000000 * $files_projects['count_files'], 2) . " кв.м.<br /><br />";
3890
3891 $str .= get_me_name_user_by_id_user($files_projects['id_user_manager_project']) . " → " . get_me_name_user_by_id_user($files_projects['id_operator']);
3892 $str .= ' (' . $GLOBALS['order_status_file'][$files_projects['status_file']] . ')<br />';
3893
3894 /*if($files_projects['recommendations']||$files_projects['id_equipment_recommendations']||$files_projects['id_equipment_now'])*/
3895 $str .= "<br /><span class='red small'>*******************************************************************</span><br />";
3896 if ($files_projects['recommendations']) {
3897 $str .= "<span class='red small'>!!! РЕКОМЕНДАЦИИ ПО ИЗГОТОВЛЕНИЮ: {$files_projects['recommendations']}</span><br />";
3898 }
3899 // if($files_projects['id_equipment_recommendations']) $str.="<span class='red small'>!!! ПРЕДПОЧТИТЕЛЬНОЕ ОБОРУДОВАНИЕ: ".get_me_name_equipment_by_id_equipment($files_projects['id_equipment_recommendations'])."</span><br />";
3900 $str .= "<span class='small'>Станок всегда: " . ($files_projects['id_equipment_recommendations'] ? get_me_name_equipment_by_id_equipment($files_projects['id_equipment_recommendations']) : '---') . "</span><br />";
3901 //if($files_projects['id_equipment_now'])
3902 {
3903 $str .= "<span class='red small'>Станок сейчас: " . ($files_projects['id_equipment_now'] ? get_me_name_equipment_by_id_equipment($files_projects['id_equipment_now']) : '---') . "</span><br />";
3904 $str .= "<span class='small'>Очередь: " . $files_projects['porn'] . "</span><br />";
3905 if ($files_projects['id_equipment_now']) {
3906 $equipments_array = select_equipment($files_projects['id_file']); // получаем подходящие станки
3907 $str .= "<span class='gray'>" . $equipments_array[$files_projects['id_equipment_now']] . "</span>"; // выводим параметры подходящего станка
3908 }
3909 }// else $str.="<span class='small'>Очередь: ".$files_projects['porn']."</span><br />";
3910
3911
3912 if ($id_equipment && $files_projects['protect_files']) {
3913 $str .= "<br /><span class='silver'>* макет закреплен за этим станком " . ($files_projects['protect_files'] ? 'менеджером' : ($files_projects['id_operator'] ? 'потому, что уже выполняется оператором' : '')) . "</span>";
3914 }
3915
3916 /* if(auth('type')==1) */
3917 $str .= "<br />Выход в свет через: {$total_minuts} минут";
3918
3919 $str .= "</span>
3920
3921 \"
3922
3923 ><nobr style='color:#{$fontcolor};'>";
3924 if ($id_equipment && $files_projects['protect_files']) {
3925 $str .= "<img src=\"/images/protect_file.png\" style=\"margin-top:2px;height:10px;\" />";
3926 }
3927
3928 $str .= $files_projects['name_label'] . "</nobr><br />";
3929
3930 $str .= get_me_kprepare_equipment_by_id_equipment($id_equipment) ? "<nobr>расч.время ~ {$minuts} мин., машин.время ~ " . round($minuts / get_me_kprepare_equipment_by_id_equipment($id_equipment)) . " мин.</nobr>" : '';
3931
3932 $str .= "<br /><nobr style='color:#{$fontcolor};'>" . $files_projects['ready_files'] . '/' . $files_projects['count_files'] . " шт.</nobr>
3933 </div>
3934 </a>";
3935
3936 if (!simple_interface()) {
3937 $str .= ($files_projects['color_label'] ? "<div style=\"background:url('/images/column_m" . (strlen($files_projects['color_label']) == 1 ? '0' . $files_projects['color_label'] : $files_projects['color_label']) . ".gif');margin-top:2px;height:4px;\"><img src=\"/images/0.gif\" style=\"width:{$width}px;height:4px;\" alt=\"{$files_projects['name_label']}\" title=\"{$files_projects['name_label']}\" /></div>" : "<div style=\"background:url('/images/0.gif');margin-top:2px;height:4px;\"><img src=\"/images/0.gif\" style=\"width:{$width}px;height:4px;\" /></div>");
3938 }
3939
3940 "</td>";
3941
3942 }
3943 $str .= "</tr></table>";
3944
3945 if ($id_equipment) {
3946 $days = round(($workinghours_total / $workinghours) + 0.5);
3947
3948 $str_days = "<table border='0' cellspacing='0' cellpadding='0' style='margin-bottom:5px;'><tr>";
3949 for ($j = 1; $j <= $days; $j++) {
3950 $str_days .= "<td><div title=\"{$workinghours} мин.\" style=\"margin-right:1px;background:#fdfdfd;border:1px solid #ccc;text-align:center;width:" . ($workinghours + (isset($correction[$j]) ? $correction[$j] : 0) - 3) . "px;\"><nobr class=\"gray supersmall\">рабочий день - "; // -3 вычитаем ширину рамки дня и отступ
3951
3952 //$str_days.= "<td><div class=\"gray supersmall\" title=\"{$workinghours} мин.\" style=\"margin-right:1px;background:#fdfdfd;border:1px solid #ccc;text-align:center;width:".($workinghours+$correction[$j]-3)."px;\">"; // -3 вычитаем ширину рамки дня и отступ
3953 //$str_days.= "<td><div class=\"gray supersmall\" title=\"{$workinghours} мин.\" style=\"margin-right:1px;background:#fdfdfd;border:1px solid #ccc;text-align:center;width:".($correction[$j]-3)."px;\">"; // -3 вычитаем ширину рамки дня и отступ
3954 $str_days .= humain_date(date("Y-m-d", mktime(0, 0, 0, date('m'), date('d') + $j - 1, date('Y'))));
3955 $str_days .= "</nobr></div></td>";
3956 }
3957 $str_days .= "</tr></table>";
3958 }
3959 }
3960
3961 }
3962 return $str_days . $str;
3963
3964}
3965
3966/*
3967 function turn_on_the_equipment($id_equipment)
3968 {
3969 $str='';
3970 $deadline_old='';
3971
3972 $result = mysql_query("
3973 SELECT *,
3974 `{$GLOBALS['TABLE_sup_files_projects']}`.`status` AS `status_file`,
3975 `{$GLOBALS['TABLE_sup_files_projects']}`.`id` AS `id_files_projects`,
3976 `{$GLOBALS['TABLE_sup_files_projects']}`.`id_user_operator` AS `id_operator`,
3977 `{$GLOBALS['TABLE_sup_files_projects']}`.`ready` AS `ready_files`,
3978 `{$GLOBALS['TABLE_sup_files_projects']}`.`count` AS `count_files`,
3979 `{$GLOBALS['TABLE_sup_files_projects']}`.`protect` AS `protect_files`,
3980 `{$GLOBALS['TABLE_sup_files_projects']}`.`id_equipment` AS `id_equipment_now`,
3981 `{$GLOBALS['TABLE_sup_projects']}`.`name` AS `name_project`,
3982 `{$GLOBALS['TABLE_sup_projects']}`.`id_user_manager` AS `id_user_manager_project`,
3983 `{$GLOBALS['TABLE_sup_projects']}`.`deadline` AS `deadline_project`,
3984 `{$GLOBALS['TABLE_sup_label']}`.`name` AS `name_label`,
3985 `{$GLOBALS['TABLE_sup_files']}`.`id_equipment` AS `id_equipment_recommendations`,
3986 `{$GLOBALS['TABLE_sup_files']}`.`recommendations` AS `recommendations`,
3987 `{$GLOBALS['TABLE_sup_files']}`.`file_preview` AS `file_preview_file`
3988 FROM `{$GLOBALS['TABLE_sup_files_projects']}`,`{$GLOBALS['TABLE_sup_projects']}`,`{$GLOBALS['TABLE_sup_files']}`,`{$GLOBALS['TABLE_sup_label']}` WHERE
3989 1
3990 AND `{$GLOBALS['TABLE_sup_files_projects']}`.`id_equipment`='{$id_equipment}'
3991 AND `{$GLOBALS['TABLE_sup_files_projects']}`.`porn`!='0'
3992 AND `{$GLOBALS['TABLE_sup_projects']}`.`id_user_del`='0'
3993 AND `{$GLOBALS['TABLE_sup_files']}`.`id_user_del`='0'
3994 AND `{$GLOBALS['TABLE_sup_files_projects']}`.`id_project`=`{$GLOBALS['TABLE_sup_projects']}`.`id`
3995 AND `{$GLOBALS['TABLE_sup_files_projects']}`.`id_file`=`{$GLOBALS['TABLE_sup_files']}`.`id`
3996 AND `{$GLOBALS['TABLE_sup_files']}`.`id_label`=`{$GLOBALS['TABLE_sup_label']}`.`id`
3997 ORDER BY `{$GLOBALS['TABLE_sup_files_projects']}`.`porn` ASC;") or die(errorDiv(mysql_error()));
3998 $count = mysql_num_rows($result);
3999
4000 # ФОРМИРУЕМ ЛЕНТУ
4001 if ($count)
4002 { $str="<table border='0' cellspacing='0' cellpadding='0'><tr>";
4003 for ($i=0; $i<$count; $i++)
4004 { $files_projects=mysql_fetch_array($result);
4005
4006
4007 if($deadline_old!=$files_projects['deadline_project']) // проверяем, сменился ли дедлайн, чтобы выводить его только в случае смены
4008 { if(strtotime($files_projects['deadline_project'])<time()) $deadline_end=1; else $deadline_end=0; // проверяем, истек ли дедлайн
4009 //$str.="<td style=\"vertical-align:middle;\"> <span class=\"".($deadline_end?'red strong ':'')."small\">дедлайн<br /> <nobr class=".($deadline_end?'red strong ':'').">".trim(humain_date($files_projects['deadline_project'])).":</nobr></span> </td>";
4010 $deadline_old=$files_projects['deadline_project'];
4011 $array_id_label=array();
4012 }
4013
4014
4015 if($files_projects['priority']=='3') $col_border="f00"; else $col_border="aaa";
4016
4017 if($files_projects['status_file']=='23') { $col_bg="0f0"; $col_border="aaa"; } // если выполнен
4018 elseif(in_array($files_projects['status_file'],array('21','22'))) { $col_bg="f00"; $col_border="000"; } // если статус трудности или нехватка материала
4019 else // если все остальные статусы
4020 { if($files_projects['id_operator']) $col_bg="fff"; // если взят в работу (или назначен), то белый фон
4021 else $col_bg="eee"; // если не взят в работ, то серый фон
4022 }
4023
4024
4025 $works_type=array();
4026 if($files_projects['cut'])$works_type[]="Резка";
4027 if($files_projects['engrave_contur'])$works_type[]="Грав.Конт.";
4028 if($files_projects['engrave_scan'])$works_type[]="Грав.Штрих.";
4029
4030 //$lastnumericid=substr(strrev($files_projects['id_label']),0,1); // берем последнюю цифру id, чтобы выбрать цвет.
4031
4032 if(!in_array($files_projects['id_label'],$array_id_label))$array_id_label[]=$files_projects['id_label']; // записываем каждый новый цвет в массиве, чтобы потом из него получить номер каждого цвета в этом дне
4033 $lastnumericid=array_search($files_projects['id_label'],$array_id_label)+1; // номер этого материала в массиве, чтобы потом задать ему определенный цвет
4034 $lastnumericid=13-$lastnumericid;
4035 if($lastnumericid>12) $lastnumericid=0; elseif($lastnumericid<10) $lastnumericid='0'.$lastnumericid; // формируем часть имени для картинки цвета
4036 //echo ' '.$lastnumericid;
4037
4038 $width=round($files_projects['time']/60)*1; // 1 пиксель равен одной минуты, чтобы монитор шириной в 1000 пикселей отобразил работы на 1000 минут, Т.е. на 16 часов
4039 $minuts=round($files_projects['time']/60+0.5); // прибавляем 0,5, чтобы не округлять в сторону нуля
4040
4041 if($width<15)$width=15; // если ширина блока меньше 15 пикс, то делаем 15
4042 $width=$width-4-1; // вычитаем с ширины блока 4 пикселя, чтобы компенсировать толщину рамки и зазор 1 пиксель между блоками
4043 $str.= "
4044 <td>
4045 <a href=\"/?p=projects_new&all=1".($files_projects['status_file']=='23'?'&other=1':'')."&id_files_projects={$files_projects['id_files_projects']}\" target=\"_blank\">
4046 <div
4047 class=\"small screenshot\"
4048 style=\" border:2px solid #{$col_border};
4049 margin-right:1px;
4050 display:inline-block;
4051 height:57px;
4052 background:#{$col_bg};
4053 overflow:hidden;
4054 width:{$width}px;
4055 \"
4056 title=\"
4057
4058 <img src='/functions/thumb.php?filename={$GLOBALS['PUTH_files']}{$files_projects['file_preview_file']}&height=100' style='margin-bottom:7px;border:1px solid #777;' /><br />
4059 <span class='small'>";
4060
4061 $str.="<strong class='red'>Дедлайн: ".humain_date($files_projects['deadline_project'])."</strong><br /><br />";
4062
4063 $str.="Проект: №{$files_projects['id_project']} "".$files_projects['name_project']."" (клиент ".get_me_name_user_by_id_user($files_projects['id_user']).")<br />";
4064 $str.="Макет: №{$files_projects['id_file']} ".($files_projects['titlefile']?'"'.upper_premier_char(str_replace(array('"',"'"),'',$files_projects['titlefile'])).'" ':'')."(автор ".get_me_name_user_by_id_user($files_projects['id_user_manager']).")<br />";
4065 $str.="<b>{$files_projects['width']}x{$files_projects['height']} мм.</b>, <b>{$files_projects['name_label']}</b><br /><br />";
4066
4067 $str.="Готовность: <b>".$files_projects['ready_files'].'/'.$files_projects['count_files']." шт.</b><br />";
4068 $str.="Виды работ: ".implode(' + ',$works_type).", ~{$minuts} мин., S = ".round($files_projects['width']*$files_projects['height']/1000000*$files_projects['count_files'],2)." кв.м.<br /><br />";
4069
4070 $str.=get_me_name_user_by_id_user($files_projects['id_user_manager_project'])." → ".get_me_name_user_by_id_user($files_projects['id_operator'])."<br />";
4071
4072 if($files_projects['recommendations']||$files_projects['id_equipment_recommendations']||$files_projects['id_equipment_now']) $str.="<br /><span class='red small'>*******************************************************************</span><br />";
4073 if($files_projects['recommendations']) $str.="<span class='red small'>!!! РЕКОМЕНДАЦИИ ПО ИЗГОТОВЛЕНИЮ: {$files_projects['recommendations']}</span><br />";
4074 // if($files_projects['id_equipment_recommendations']) $str.="<span class='red small'>!!! ПРЕДПОЧТИТЕЛЬНОЕ ОБОРУДОВАНИЕ: ".get_me_name_equipment_by_id_equipment($files_projects['id_equipment_recommendations'])."</span><br />";
4075 $str.="<span class='small'>Станок всегда: ".($files_projects['id_equipment_recommendations']?get_me_name_equipment_by_id_equipment($files_projects['id_equipment_recommendations']):'---')."</span><br />";
4076 if($files_projects['id_equipment_now'])
4077 { $str.="<span class='red small'>Станок сейчас: ".get_me_name_equipment_by_id_equipment($files_projects['id_equipment_now']?$files_projects['id_equipment_now']:$files_projects['id_equipment_recommendations'])."</span><br />";
4078 if($files_projects['id_equipment_now'])
4079 { $equipments_array=select_equipment($files_projects['id_file']); // получаем подходящие станки
4080 $str.="<span class='gray'>".$equipments_array[$files_projects['id_equipment_now']]."</span>"; // выводим параметры подходящего станка
4081 }
4082 }
4083
4084 if($id_equipment&&$files_projects['protect_files']) $str.="<br /><span class='silver'>* макет закреплен за этим станком ".($files_projects['protect_files']?'менеджером':($files_projects['id_operator']?'потому, что уже выполняется оператором':''))."</span>";
4085
4086 $str.="</span>
4087
4088 \"
4089
4090 ><nobr>";
4091 if($id_equipment&&$files_projects['protect_files']) $str.="<img src=\"/images/protect_file.png\" style=\"margin-top:2px;height:10px;\" />";
4092
4093 $str.=$files_projects['name_label']."</nobr><br />
4094 <nobr>{$minuts} мин.</nobr><br />
4095 <nobr>".$files_projects['ready_files'].'/'.$files_projects['count_files']." шт.</nobr>
4096 </div>
4097 </a>
4098 <div style=\"background:url('/images/column_m{$lastnumericid}.gif');border-top:3px #fff solid;height:4px;\"><img src=\"/images/0.gif\" style=\"width:{$width}px;height:4px;\" alt=\"{$files_projects['name_label']}\" title=\"{$files_projects['name_label']}\" /></div>
4099 </td>";
4100
4101 }
4102 $str.="</tr></table>";
4103 }
4104 return $str;
4105
4106 }
4107
4108*/
4109/*
4110 function turn_on_the_equipment0($id_equipment)
4111 {
4112 $str='';
4113 $deadline_old='';
4114
4115 $result = mysql_query("SELECT *,`{$GLOBALS['TABLE_sup_files_projects']}`.`status` AS `status_file`,`{$GLOBALS['TABLE_sup_files_projects']}`.`id` AS `id_files_projects`,`{$GLOBALS['TABLE_sup_files_projects']}`.`id_user_operator` AS `id_operator`,`{$GLOBALS['TABLE_sup_files_projects']}`.`ready` AS `ready_files`,`{$GLOBALS['TABLE_sup_files_projects']}`.`count` AS `count_files`,`{$GLOBALS['TABLE_sup_projects']}`.`name` AS `name_project`,`{$GLOBALS['TABLE_sup_projects']}`.`id_user_manager` AS `id_user_manager_project`,`{$GLOBALS['TABLE_sup_projects']}`.`deadline` AS `deadline_project`,`{$GLOBALS['TABLE_sup_label']}`.`name` AS `name_label`, `{$GLOBALS['TABLE_sup_files']}`.`id_equipment` AS `id_equipment_recommendations`, `{$GLOBALS['TABLE_sup_files']}`.`recommendations` FROM `{$GLOBALS['TABLE_sup_files_projects']}`,`{$GLOBALS['TABLE_sup_projects']}`,`{$GLOBALS['TABLE_sup_files']}`,`{$GLOBALS['TABLE_sup_label']}` WHERE 1 AND `{$GLOBALS['TABLE_sup_files_projects']}`.`id_equipment`='{$id_equipment}' AND `{$GLOBALS['TABLE_sup_files_projects']}`.`porn`!='0' AND `{$GLOBALS['TABLE_sup_projects']}`.`status` IN ('10','20','21','22') AND `{$GLOBALS['TABLE_sup_projects']}`.`id_user_del`='0' AND `{$GLOBALS['TABLE_sup_files']}`.`id_user_del`='0' AND `{$GLOBALS['TABLE_sup_files_projects']}`.`id_project`=`{$GLOBALS['TABLE_sup_projects']}`.`id` AND `{$GLOBALS['TABLE_sup_files_projects']}`.`id_file`=`{$GLOBALS['TABLE_sup_files']}`.`id` AND `{$GLOBALS['TABLE_sup_files']}`.`id_label`=`{$GLOBALS['TABLE_sup_label']}`.`id` ORDER BY `{$GLOBALS['TABLE_sup_files_projects']}`.`porn` ASC;") or die(errorDiv(mysql_error()));
4116 $count = mysql_num_rows($result);
4117
4118 # ФОРМИРУЕМ ЛЕНТУ
4119 if ($count)
4120 { $str="<table border='0' cellspacing='0' cellpadding='0'><tr>";
4121 for ($i=0; $i<$count; $i++)
4122 { $files_projects=mysql_fetch_array($result);
4123
4124 if($deadline_old!=$files_projects['deadline_project'])
4125 { $str.="<td style=\"vertical-align:middle;\"> <b class=\"supersmall\">дедлайн<br /> <nobr>".trim(humain_date($files_projects['deadline_project'])).":<nobr></b> </td>";
4126 $deadline_old=$files_projects['deadline_project'];
4127 $array_id_label=array();
4128 }
4129
4130 $width=round($files_projects['time']/60)*1; // 1 пиксель равен одной минуты, чтобы монитор шириной в 1000 пикселей отобразил работы на 1000 минут, Т.е. на 16 часов
4131 if($files_projects['priority']=='3') $col_border="f00"; else $col_border="aaa";
4132 if($files_projects['status_file']=='23') { $col_bg="0f0"; $col_border="aaa"; }
4133 elseif(in_array($files_projects['status_file'],array('21','22'))) { $col_bg="f00"; $col_border="000"; }
4134 else
4135 { if($files_projects['id_operator']) $col_bg="fff"; else $col_bg="eee";
4136 }
4137
4138 $minuts=round($files_projects['time']/60+0.5);
4139
4140 $works_type=array();
4141 if($files_projects['cut'])$works_type[]="Резка";
4142 if($files_projects['engrave_contur'])$works_type[]="Грав.Конт.";
4143 if($files_projects['engrave_scan'])$works_type[]="Грав.Штрих.";
4144
4145 //$lastnumericid=substr(strrev($files_projects['id_label']),0,1); // берем последнюю цифру id, чтобы выбрать цвет.
4146
4147 if(!in_array($files_projects['id_label'],$array_id_label))$array_id_label[]=$files_projects['id_label']; // записываем каждый новый цвето в массиве, чтобы потом из него получить номер каждого цвета в этом дне
4148 $lastnumericid=array_search($files_projects['id_label'],$array_id_label)+1;
4149 $lastnumericid=13-$lastnumericid;
4150 if($lastnumericid>12) $lastnumericid=0; elseif($lastnumericid<10) $lastnumericid='0'.$lastnumericid;
4151 //echo ' '.$lastnumericid;
4152
4153
4154 if($width<15)$width=15;
4155 $width=$width-5; // вычитаем с ширины блока 4 пикселя, чтобы компенсировать толщину рамки
4156 $str.= "<td><a href=\"/?p=projects_new&all=1".($files_projects['status_file']=='23'?'&other=1':'')."&id_files_projects={$files_projects['id_files_projects']}\" target=\"_blank\"><div
4157 style=\"border:2px solid #{$col_border};margin-right:1px;display:inline-block;height:54px;background:#{$col_bg};overflow:hidden;width:{$width}px;\"
4158 title=\"";
4159
4160 $str.="Дедлайн: ".humain_date($files_projects['deadline_project'])."\n\n";
4161
4162 $str.="Макет: №{$files_projects['id_file']} "".upper_premier_char(str_replace(array('"',"'"),'',$files_projects['titlefile']))."" (автор ".get_me_name_user_by_id_user($files_projects['id_user_manager'])."), {$files_projects['width']}x{$files_projects['height']} мм.\n";
4163 $str.="{$files_projects['name_label']}, S = ".round($files_projects['width']*$files_projects['height']/1000000*$files_projects['count_files'],2)." кв.м.\n\n";
4164 $str.="Клиент: ".get_me_name_user_by_id_user($files_projects['id_user'])."\n";
4165 $str.="Проект: №{$files_projects['id_project']} "".$files_projects['name_project'].""\n\n";
4166
4167 $str.="Виды работ: ".implode(' + ',$works_type).", ~{$minuts} мин.\n";
4168 $str.="Готовность: ".$files_projects['ready_files'].'/'.$files_projects['count_files']." шт.\n\n";
4169
4170 $str.=get_me_name_user_by_id_user($files_projects['id_user_manager_project'])." → ".get_me_name_user_by_id_user($files_projects['id_operator'])."\n\n";
4171
4172 if($files_projects['recommendations']||$files_projects['id_equipment_recommendations']) $str.="*******************************************************************\n";
4173 if($files_projects['recommendations']) $str.="!!! РЕКОМЕНДАЦИИ ПО ИЗГОТОВЛЕНИЮ: {$files_projects['recommendations']}\n";
4174 if($files_projects['id_equipment_recommendations']) $str.="!!! ПРЕДПОЧТИТЕЛЬНОЕ ОБОРУДОВАНИЕ: ".get_me_name_equipment_by_id_equipment($files_projects['id_equipment_recommendations'])."\n";
4175
4176 $str.="\"
4177 class=\"small\"
4178
4179 ><nobr>".$files_projects['name_label']."</nobr><br />
4180 <nobr>{$minuts} мин.</nobr><br />
4181 <nobr>".$files_projects['ready_files'].'/'.$files_projects['count_files']." шт.</nobr>
4182 <div style=\"background:url('/images/column_m{$lastnumericid}.gif');border-top:1px #fff solid;height:5px;margin-bottom:5px;\"><img src=\"/images/0.gif\" style=\"width:1px;height:5px;\" /></div>
4183 </div></a></td>";
4184
4185 }
4186 $str.="</tr></table>";
4187 }
4188 return $str;
4189
4190 }
4191*/
4192
4193function humain_duration_production_order_projects($duration) {
4194
4195 $days = $duration / (24 * 3600);
4196 if ($days > 1) {
4197 $days = round($days - 0.5);
4198 }
4199 else {
4200 $days = 0;
4201 }
4202
4203 $duration = $duration - $days * (24 * 3600);
4204
4205 $hours = $duration / 3600;
4206 if ($hours > 1) {
4207 $hours = round($hours - 0.5);
4208 }
4209 else {
4210 $hours = 0;
4211 }
4212
4213 $duration = $duration - $hours * 3600;
4214
4215 $minuts = $duration / 60;
4216 if ($minuts > 1) {
4217 $minuts = round($minuts - 0.5);
4218 }
4219 else {
4220 $minuts = 0;
4221 }
4222
4223 return ($days ? $days . ' дн. ' : '') . ($hours || $days ? $hours . ' час. ' : '') . $minuts . ' мин. ';
4224
4225}
4226
4227function duration_production_order_projects($date_a, $date_b) {
4228 $date_a_a = explode('-', str_replace(array(' ', ':'), '-', $date_a));
4229 $mktime_a = mktime($date_a_a[3], $date_a_a[4], $date_a_a[5], $date_a_a[1], $date_a_a[2], $date_a_a[0]);
4230
4231 $date_b_a = explode('-', str_replace(array(' ', ':'), '-', $date_b));
4232 $mktime_b = mktime($date_b_a[3], $date_b_a[4], $date_b_a[5], $date_b_a[1], $date_b_a[2], $date_b_a[0]);
4233
4234 return $mktime_b - $mktime_a;
4235}
4236
4237function speed_of_the_work($days) {
4238
4239 $days = round($days);
4240 if (!$days) {
4241 return '---';
4242 }
4243
4244 // смотрим, на какую сумму ПОЛНОСТЬЮ сделано работы за последние N дней
4245 $made = SUM($GLOBALS['TABLE_sup_projects'], 'total_price', " AND `status` IN ('23','30','40','50') AND `made` > NOW() - INTERVAL {$days} DAY AND `id_user_del`='0' ");
4246 // смотрим, на какую сумму частично сделано работы в запущенных проектах
4247 // ТАК НЕВЕРНО СЧИТАТЬ!! ДЕЛО В ТОМ, ЧТО ВНИЗУ СТРОКА УЧИТЫВАЕТ ВСЕ ПРОЕКТЫ, ВЫПОЛНЕННЫЕ ЧАСТИЧНО НЕ ОБРАЩАЯ ВНИМАНИЯ НА ТО, КОГДА ОНИ БЫЛИ ВЫПОЛНЕНЫ. ЕСЛИ ПРОЕКТ НА МИЛЛИОН, БЫЛ ВЫПОЛНЕНА НА 50%, Т.Е. НА ПОЛМИЛЛИОНА ГОД НАЗАД, ТО МЫ ЭТИ ПОЛМИЛЛИОНА БУДЕМ ВСЕГДА ОШИБОЧНО СЧИТАТЬ, КАК НАША СКОРОСТЬ ВЫПОЛНЕНИЯ, ХОТЯ ЭТО БЫЛА СКОРОСТЬ "ТОГДА", А НЕ В ЭТИ НЕСКОЛЬКО ДНЕЙ
4248 // $made+=SUM($GLOBALS['TABLE_sup_projects'], "ready`*0.01*`total_price", " AND `visible`='1' AND `status` IN ('20','21','22') AND `id_user_del`='0' ");
4249
4250 // смотрим, на какую сумму запущено проектов за последние N дней
4251 $start = SUM($GLOBALS['TABLE_sup_projects'], 'total_price', " AND `visible`='1' AND `start` > NOW() - INTERVAL {$days} DAY AND `id_user_del`='0' ");
4252
4253 // считаем коэффициент
4254 if ($start) {
4255 $progress = round($made / $start, 2);
4256 }
4257 else {
4258 $progress = 0;
4259 }
4260
4261 // приписываем разъяснения для админа и менеджера
4262 if (in_array(auth('type'), array(1, 2))) {
4263 $title = " title='Выполнено (статусы: \"Выполнен\", \"Принят, ждем клиента\", \"Закрыт\", \"Отказ\") за последние 7 суток, начиная с этого момента: " . addpoint($made) . " руб. / запущено (нажата кнопка \"Старт\") за последние 7 суток, начиная с этого момента " . addpoint($start) . " руб.' ";
4264 }
4265 else {
4266 $title = '';
4267 }
4268
4269 // выводим коэффициент соответствующим образом в зависимости от его величины
4270 if ($progress < 1) {
4271 $ret = "<u class='gray' title='Отношение сумм проектов со статусами \"Выполнен\", \"Принят, ждем клиента\", \"Закрыт\", \"Отказ\" к суммам запущенных проектов (нажата кнопка \"Старт\").'>Коэффициент производительности за {$days} суток:</span> <span class='big red strong' {$title}>{$progress} - Отстаем от приема заказов</u>";
4272 }
4273 if ($progress == 1) {
4274 $ret = "<u class='gray' title='Отношение сумм проектов со статусами \"Выполнен\", \"Принят, ждем клиента\", \"Закрыт\", \"Отказ\" к суммам запущенных проектов (нажата кнопка \"Старт\").'>Коэффициент производительности за {$days} суток:</span> <span class='big black strong' {$title}>{$progress}</u>";
4275 }
4276 if ($progress > 1) {
4277 $ret = "<u class='gray' title='Отношение сумм проектов со статусами \"Выполнен\", \"Принят, ждем клиента\", \"Закрыт\", \"Отказ\" к суммам запущенных проектов (нажата кнопка \"Старт\").'>Коэффициент производительности за {$days} суток:</span> <span class='big green strong' {$title}>{$progress}</u>";
4278 }
4279
4280 // здесь будем определять сколько операторов работаем на постоянке (с установленным планом), на сколько дней у нас работы при их нормальной работе (соответствуя плану) и на сколько при той работе, как они работают
4281 $ret .= "<div style='margin-top:10px;'>";
4282
4283 // получаем количество операторов на фирме с установленным планом (работающим на постоянке, раз есть план)
4284 $count_operators = COUNTROWS($GLOBALS['TABLE_sup_users'], " AND `id_user_del`=0 AND `type`='3' /* AND `plan`>0 */ AND `id_user_del`='0' ");
4285
4286 // получаем сумму планов операторов
4287 $general_plan = SUM($GLOBALS['TABLE_sup_users'], "plan", " AND `id_user_del`=0 AND `type`='3' AND `id_user_del`='0' ");
4288
4289 // считаем на какую сумму у нас принято и запущено проектов (проектов запущено `visible`=1 и имеющих статус 10, 20, 21, 22)
4290 $count_summ_start_projects = SUM($GLOBALS['TABLE_sup_projects'], "total_price`-0.01*`ready`*`total_price", " AND `visible`='1' AND `status` IN ('10','20','21','22') AND `id_user_del`='0' ");
4291
4292 if (in_array(auth('type'), array(1, 2))) {
4293 $ret .= "В штате работает <b>{$count_operators}</b> исполнителя с общим планом <b>" . addpoint($general_plan) . "</b> руб./мес.<br />";
4294 if ($general_plan) {
4295 $ret .= "При планируемой скорости выполнения заказов в <b>" . addpoint($general_plan / 30) . "</b> руб./день мы имеем работы на <b title=\"" . addpoint($count_summ_start_projects) . " руб. / " . addpoint($general_plan / 30) . " руб.\">" . round($count_summ_start_projects * 30 / $general_plan) . "</b> рабочих дней.<br />";
4296 } // ($days*0.71) - переводим неделю из 7 дней в 5 рабочих дней, так правильнее, т.к. нельзя делить то, что они успели за 7 суток, на 7 суток, т.к. они все-таки еще успевали и по факту работали лишь 5 дней, выполняя план
4297 if ($made) {
4298 $ret .= "При текущей скорости выполнения заказов (за последние {$days} дней) в <b title=\"" . addpoint($made) . " руб. / " . addpoint($days) . " дн.\">" . addpoint(round($made / $days)) . "</b> руб./день мы имеем работы на <b title=\"" . addpoint($count_summ_start_projects) . " руб. / " . addpoint(round($made / $days)) . " руб.\">" . round($count_summ_start_projects * $days / $made) . "</b> рабочих дней.<br />";
4299 }
4300
4301 $ret .= '</div>';
4302 }
4303 if (in_array(auth('type'), array(3))) {
4304 if ($general_plan) {
4305 $ret .= "При планируемой скорости выполнения заказов мы имеем работы на <b>" . round($count_summ_start_projects * 30 / $general_plan) . "</b> рабочих дней.<br />";
4306 }
4307 if ($made) {
4308 $ret .= "При текущей скорости выполнения заказов мы имеем работы на <b>" . round($count_summ_start_projects * $days / $made) . "</b> рабочих дней.<br />";
4309 }
4310
4311 }
4312 // здесь будем определять сколько операторов работаем на постоянке (с установленным планом), на сколько дней у нас работы при их нормальной работе (соответствуя плану) и на сколько при той работе, как они работают
4313
4314 return $ret;
4315}
4316
4317function max_days_turn($days) // загруженность производства от ... до ... дней. Определяем максимальное значение, чтобы не давать ставить дедлайн раньше чем ... дней
4318{
4319
4320 $days = round($days);
4321 if (!$days) {
4322 return '---';
4323 }
4324
4325 // считаем на какую сумму у нас принято и запущено проектов (проектов запущено `visible`=1 и имеющих статус 10, 20, 21, 22)
4326 $count_summ_start_projects = SUM($GLOBALS['TABLE_sup_projects'], "total_price`-0.01*`ready`*`total_price", " AND `visible`='1' AND `status` IN ('10','20','21','22') AND `id_user_del`='0' ");
4327
4328 // столько ДЕЛАЕМ за 1 день
4329 $day_fact = SUM($GLOBALS['TABLE_sup_projects'], 'total_price', " AND `status` IN ('23','30','40','50') AND `made` > NOW() - INTERVAL {$days} DAY AND `id_user_del`='0' ") / $days;
4330 // смотрим, на какую сумму частично сделано работы в запущенных проектах
4331 // ТАК НЕВЕРНО СЧИТАТЬ!! ДЕЛО В ТОМ, ЧТО ВНИЗУ СТРОКА УЧИТЫВАЕТ ВСЕ ПРОЕКТЫ, ВЫПОЛНЕННЫЕ ЧАСТИЧНО НЕ ОБРАЩАЯ ВНИМАНИЯ НА ТО, КОГДА ОНИ БЫЛИ ВЫПОЛНЕНЫ. ЕСЛИ ПРОЕКТ НА МИЛЛИОН, БЫЛ ВЫПОЛНЕНА НА 50%, Т.Е. НА ПОЛМИЛЛИОНА ГОД НАЗАД, ТО МЫ ЭТИ ПОЛМИЛЛИОНА БУДЕМ ВСЕГДА ОШИБОЧНО СЧИТАТЬ, КАК НАША СКОРОСТЬ ВЫПОЛНЕНИЯ, ХОТЯ ЭТО БЫЛА СКОРОСТЬ "ТОГДА", А НЕ В ЭТИ НЕСКОЛЬКО ДНЕЙ
4332 // $day_fact+=SUM($GLOBALS['TABLE_sup_projects'], "ready`*0.01*`total_price", " AND `visible`='1' AND `status` IN ('20','21','22') AND `id_user_del`='0' ");
4333
4334 // столько ДОЛЖНЫ делать за 1 день
4335 $day_plan = SUM($GLOBALS['TABLE_sup_users'], "plan", " AND `id_user_del`=0 AND `type`='3' AND `id_user_del`='0' ") / 30;
4336
4337 if ($day_fact) {
4338 $a = round($count_summ_start_projects / $day_fact);
4339 }
4340 else {
4341 $a = 0;
4342 }
4343 if ($day_plan) {
4344 $b = round($count_summ_start_projects / $day_plan);
4345 }
4346 else {
4347 $b = 0;
4348 }
4349
4350 if ($a > $b) {
4351 return $a;
4352 }
4353 if ($b > $a) {
4354 return $b;
4355 }
4356 if ($a == $b) {
4357 return $a;
4358 }
4359
4360}
4361
4362function current_load() // возвращаем на какое количество дней у нас имеется работы
4363{
4364 // получаем сумму планов операторов
4365 $general_plan = SUM($GLOBALS['TABLE_sup_users'], "plan", " AND `id_user_del`=0 AND `type`='3' AND `id_user_del`='0' ");
4366
4367 // определяем на какую сумму у нас принято и запущено проектов
4368 $summ_start_projects = SUM($GLOBALS['TABLE_sup_projects'], "total_price`-0.01*`ready`*`total_price", " AND `visible`='1' AND `status` IN ('10','20','21','22') AND `id_user_del`='0' ");
4369
4370 // считаем сколько всего у нас принято проектов (проектов запущено `visible`=1 и имеющих статус 10, 20, 21, 22)
4371 $count_start_projects = COUNTROWS($GLOBALS['TABLE_sup_projects'], " AND `visible`='1' AND `status` IN ('10','20','21','22') AND `id_user_del`='0' ");
4372
4373 // получаем "средний чек проекта"
4374 if ($count_start_projects) {
4375 $average_check = $summ_start_projects / $count_start_projects;
4376 }
4377
4378 return $general_plan ? round(($summ_start_projects + $average_check) * 21 / $general_plan, 5) : 0;
4379}
4380
4381function planned_delivery_time($days = 7) // планируемый срок исполнения заказов запущенных в системе при текущей скорости исполнения
4382{
4383
4384 $days = round($days);
4385 if (!$days) {
4386 return '---';
4387 }
4388
4389 // смотрим, на какую сумму сделано работы за последние N дней
4390 $made = SUM($GLOBALS['TABLE_sup_projects'], 'total_price', " AND `status` IN ('23','30','40','50') AND `made` > NOW() - INTERVAL {$days} DAY AND `id_user_del`='0' ");
4391 // смотрим, на какую сумму частично сделано работы в запущенных проектах
4392 // ТАК НЕВЕРНО СЧИТАТЬ!! ДЕЛО В ТОМ, ЧТО ВНИЗУ СТРОКА УЧИТЫВАЕТ ВСЕ ПРОЕКТЫ, ВЫПОЛНЕННЫЕ ЧАСТИЧНО НЕ ОБРАЩАЯ ВНИМАНИЯ НА ТО, КОГДА ОНИ БЫЛИ ВЫПОЛНЕНЫ. ЕСЛИ ПРОЕКТ НА МИЛЛИОН, БЫЛ ВЫПОЛНЕНА НА 50%, Т.Е. НА ПОЛМИЛЛИОНА ГОД НАЗАД, ТО МЫ ЭТИ ПОЛМИЛЛИОНА БУДЕМ ВСЕГДА ОШИБОЧНО СЧИТАТЬ, КАК НАША СКОРОСТЬ ВЫПОЛНЕНИЯ, ХОТЯ ЭТО БЫЛА СКОРОСТЬ "ТОГДА", А НЕ В ЭТИ НЕСКОЛЬКО ДНЕЙ
4393 // $made+=SUM($GLOBALS['TABLE_sup_projects'], "ready`*0.01*`total_price", " AND `visible`='1' AND `status` IN ('10','20','21','22') AND `id_user_del`='0' ");
4394
4395 // получаем сумму планов операторов
4396 $general_plan = SUM($GLOBALS['TABLE_sup_users'], "plan", " AND `id_user_del`=0 AND `type`='3' AND `id_user_del`='0' ");
4397
4398 // считаем на какую сумму у нас принято проектов (проектов запущено `visible`=1 и имеющих статус 10, 20, 21, 22)
4399 $count_summ_start_projects = SUM($GLOBALS['TABLE_sup_projects'], "total_price`-0.01*`ready`*`total_price", " AND `visible`='1' AND `status` IN ('10','20','21','22') AND `id_user_del`='0' ");
4400
4401 // считаем сколько всего у нас принято проектов (проектов запущено `visible`=1 и имеющих статус 10, 20, 21, 22)
4402 $count_start_projects = COUNTROWS($GLOBALS['TABLE_sup_projects'], " AND `visible`='1' AND `status` IN ('10','20','21','22') AND `id_user_del`='0' ");
4403
4404 // получаем "средний чек проекта"
4405 if ($count_start_projects) {
4406 $average_check = $count_summ_start_projects / $count_start_projects;
4407 }
4408
4409 // высчитыаем планируемое время исполнения заказа учитывая количество рабочих дней и план операторам и реальное время исполнения заказа ПРИБАВИВ стоимость еще одну стоимость среднего заказа
4410 $planned_amount_work = round(($count_summ_start_projects + $average_check * 0.5) * 21 / $general_plan);
4411 $actual_amount_work = round(($count_summ_start_projects + $average_check * 0.5) * $days / $made);
4412
4413 return $planned_amount_work > $actual_amount_work ? $planned_amount_work : $actual_amount_work;
4414}
4415
4416
4417function all_operators_this_project($id_project) // этой функцией выводим имя или имена исполнителей этого проекта
4418{
4419 $id_project = round($id_project);
4420
4421 // смотрим назначен ли этот проект одному исполнителю целиком, если да, то выводим его имя ,
4422 $id_user_operator = SUM($GLOBALS['TABLE_sup_projects'], "id_user_operator", " AND `id`='{$id_project}' LIMIT 1;"); // определяем его таким хитрым простым способом
4423 if (!empty($id_user_operator)) {
4424 return "<b><nobr><img src='/images/work.png' height='15' style='height: 15px;' align='left1' title='Исполнитель: ' /> " . get_me_name_user_by_id_user($id_user_operator) . '</nobr></b>';
4425 }
4426
4427 $id_user_operator_a = array();
4428
4429 // получаем массив id и имен всех операторов взявших файлы в этом проекте
4430 $result0 = mysql_query("SELECT `id_user_operator` FROM `{$GLOBALS['TABLE_sup_files_projects']}` WHERE `id_project`='{$id_project}' AND `id_user_operator`!='0' GROUP BY `id_user_operator`;") or die(errorDiv(mysql_error()));
4431
4432 while ($subj0 = mysql_fetch_assoc($result0)) {
4433 if (array_key_exists('id_user_operator', $subj0)) {
4434 $id_user_operator_a[$subj0['id_user_operator']] = "<nobr><img src='/images/work.png' height='15' style='height: 15px;' align='left1' title='Исполнитель: ' /> " . get_me_name_user_by_id_user($subj0['id_user_operator']) . '</nobr>';
4435 }
4436 }
4437
4438 if (count($id_user_operator_a) == 1 && COUNTROWS($GLOBALS['TABLE_sup_files_projects'], " AND `id_user_operator`='0' AND `id_project`='{$id_project}' ")) {
4439 return array_pop(array_values($id_user_operator_a)) . ' + ...';
4440 }
4441
4442 if (count($id_user_operator_a) == 1 && !COUNTROWS($GLOBALS['TABLE_sup_files_projects'], " AND `id_user_operator`='0' AND `id_project`='{$id_project}' ")) {
4443 return array_pop(array_values($id_user_operator_a));
4444 }
4445
4446 if (count($id_user_operator_a) > 1 && COUNTROWS($GLOBALS['TABLE_sup_files_projects'], " AND `id_user_operator`='0' AND `id_project`='{$id_project}' ")) {
4447 return implode(', ', array_values($id_user_operator_a)) . ' + ...';
4448 }
4449
4450 if (count($id_user_operator_a) > 1 && !COUNTROWS($GLOBALS['TABLE_sup_files_projects'], " AND `id_user_operator`='0' AND `id_project`='{$id_project}' ")) {
4451 return implode(', ', array_values($id_user_operator_a));
4452 }
4453
4454 if (!count($id_user_operator_a)) {
4455 return 0;
4456 }
4457
4458}
4459
4460function all_ids_operators_this_project($id_project) // этой функцией выводим id исполнителей этого проекта
4461{
4462 $id_project = round($id_project);
4463
4464 $id_user_operator_a = array();
4465
4466 //echo "SELECT * FROM `{$GLOBALS['TABLE_sup_files_projects']}` WHERE `id_project`='{$id_project}' AND `id_user_operator`!='0' GROUP BY `id_user_operator`;";
4467 // получаем массив id и имен всех операторов взявших файлы в этом проекте
4468 $result0 = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_files_projects']}` WHERE `id_project`='{$id_project}' AND `id_user_operator`!='0' GROUP BY `id_user_operator`;") or die(errorDiv(mysql_error()));
4469 $count0 = mysql_num_rows($result0);
4470 if ($count0) {
4471 for ($i0 = 0; $i0 < $count0; $i0++) {
4472 $subj0 = mysql_fetch_array($result0);
4473
4474 $id_user_operator_a[$subj0['id_user_operator']] = get_me_name_user_by_id_user($subj0['id_user_operator']);
4475 }
4476 }
4477
4478 return count($id_user_operator_a) ? $id_user_operator_a : array();
4479
4480}
4481
4482function all_ids_operators_and_remunerations_this_project($id_project) // этой функцией выводим id исполнителей и их вознаграждения в этом проекте
4483{
4484 $id_project = round($id_project);
4485
4486 $remunerations_a = array();
4487
4488 // получаем массив id и вознаграждений всех операторов взявших файлы в этом проекте
4489 $result0 = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_files_projects']}` WHERE `id_project`='{$id_project}' AND `id_user_operator`!='0' GROUP BY `id_user_operator`;") or die(errorDiv(mysql_error()));
4490 $count0 = mysql_num_rows($result0);
4491 if ($count0) {
4492 for ($i0 = 0; $i0 < $count0; $i0++) {
4493 $subj0 = mysql_fetch_array($result0);
4494
4495 $remunerations_a[$subj0['id_user_operator']] = $subj0['remuneration_operator'] . '#' . $subj0['remuneration_operator_approve'];
4496 }
4497 }
4498
4499 return count($remunerations_a) ? $remunerations_a : array();
4500
4501}
4502
4503function made_todayTEST($id_user, $date = '') // на какую сумму файлам этот оператор сегодня поставил статус выполнен
4504{
4505 $id_user = round($id_user);
4506 $date = str_replace(array(
4507 '"',
4508 "'",
4509 '`',
4510 "/",
4511 "\\",
4512 '=',
4513 '?',
4514 '&',
4515 "#",
4516 ), '', $date);
4517
4518 if (!$date) {
4519 $date = date('Y-m-d');
4520 }
4521 // пока считаем сколько оператор нарезал изделий в рублях, потом будем считать в метрах
4522 $sum = mysql_query("SELECT SUM(`{$GLOBALS['TABLE_sup_files']}`.`pricefile`*`{$GLOBALS['TABLE_sup_files_projects']}`.`count`) FROM `{$GLOBALS['TABLE_sup_files_projects']}`,`{$GLOBALS['TABLE_sup_files']}` WHERE `{$GLOBALS['TABLE_sup_files_projects']}`.`status`='23' AND `{$GLOBALS['TABLE_sup_files_projects']}`.`made` LIKE '{$date}%' " . ($id_user ? " AND `{$GLOBALS['TABLE_sup_files_projects']}`.`id_user_operator`='{$id_user}' " : '') . " AND `{$GLOBALS['TABLE_sup_files']}`.`id`=`{$GLOBALS['TABLE_sup_files_projects']}`.`id_file`;") or die(errorDiv(mysql_error()));
4523 //$sum = mysql_query("SELECT SUM(`{$GLOBALS['TABLE_sup_files']}`.`pricefile`*`{$GLOBALS['TABLE_sup_files_projects']}`.`count`) FROM `{$GLOBALS['TABLE_sup_projects']}`,`{$GLOBALS['TABLE_sup_files_projects']}`,`{$GLOBALS['TABLE_sup_files']}` WHERE `{$GLOBALS['TABLE_sup_files_projects']}`.`status`='23' AND `{$GLOBALS['TABLE_sup_projects']}`.`status` IN ('40','50') AND `{$GLOBALS['TABLE_sup_files_projects']}`.`made` LIKE '{$date}%' ".($id_user?" AND `{$GLOBALS['TABLE_sup_files_projects']}`.`id_user_operator`='{$id_user}' ":'')." AND `{$GLOBALS['TABLE_sup_files']}`.`id`=`{$GLOBALS['TABLE_sup_files_projects']}`.`id_file` AND `{$GLOBALS['TABLE_sup_projects']}`.`id`=`{$GLOBALS['TABLE_sup_files_projects']}`.`id_project`;") or die(errorDiv(mysql_error()));
4524 $sum = mysql_result($sum, 0);
4525
4526 return round($sum);
4527}
4528
4529function made_today_operator($id_user, $date = '') // на какую сумму файлам этот оператор сегодня поставил статус выполнен
4530{
4531 $id_user = round($id_user);
4532 $date = str_replace(array(
4533 '"',
4534 "'",
4535 '`',
4536 "/",
4537 "\\",
4538 '=',
4539 '?',
4540 '&',
4541 "#",
4542 ), '', $date);
4543
4544 if (!$date) {
4545 $date = date('Y-m-d');
4546 }
4547 // пока считаем сколько оператор нарезал изделий в рублях, потом будем считать в метрах
4548 $sum = mysql_query("SELECT SUM(`{$GLOBALS['TABLE_sup_files']}`.`pricefile`*`{$GLOBALS['TABLE_sup_files_projects']}`.`count`) FROM `{$GLOBALS['TABLE_sup_files_projects']}`,`{$GLOBALS['TABLE_sup_files']}`,`{$GLOBALS['TABLE_sup_projects']}` WHERE `{$GLOBALS['TABLE_sup_files_projects']}`.`status`='23' " . (get_me_salary_user_by_id_user($id_user) || !$id_user ? " AND `{$GLOBALS['TABLE_sup_projects']}`.`total_price`>0 " : '') . " AND `{$GLOBALS['TABLE_sup_files_projects']}`.`made`!='0000-00-00 00:00:00' AND `{$GLOBALS['TABLE_sup_files_projects']}`.`made` LIKE '{$date}%' " . ($id_user ? " AND `{$GLOBALS['TABLE_sup_files_projects']}`.`id_user_operator`='{$id_user}' " : '') . " AND `{$GLOBALS['TABLE_sup_files']}`.`id`=`{$GLOBALS['TABLE_sup_files_projects']}`.`id_file` AND `{$GLOBALS['TABLE_sup_projects']}`.`id`=`{$GLOBALS['TABLE_sup_files_projects']}`.`id_project`;") or die(errorDiv(mysql_error()));
4549 $sum = mysql_result($sum, 0);
4550
4551 return round($sum);
4552}
4553
4554function made_month_operator($id_user, $date = '') // на какую сумму файлам этот оператор в этом месяце поставил статус выполнен
4555{
4556 $id_user = round($id_user);
4557 $date = str_replace(array(
4558 '"',
4559 "'",
4560 '`',
4561 "/",
4562 "\\",
4563 '=',
4564 '?',
4565 '&',
4566 "#",
4567 ), '', $date);
4568
4569 if ($date) { // отрезаем дату, оставляем только год и месяц
4570 $date0 = explode('0', $date);
4571 $date = $date0[0] . '-' . $date0[1] . '-';
4572 }
4573 else {
4574 $date = date('Y-m-');
4575 }
4576 // пока считаем сколько оператор нарезал изделий в рублях, потом будем считать в метрах
4577 $sum = mysql_query("SELECT SUM(`{$GLOBALS['TABLE_sup_files']}`.`pricefile`*`{$GLOBALS['TABLE_sup_files_projects']}`.`count`) FROM `{$GLOBALS['TABLE_sup_files_projects']}`,`{$GLOBALS['TABLE_sup_files']}`,`{$GLOBALS['TABLE_sup_projects']}` WHERE `{$GLOBALS['TABLE_sup_files_projects']}`.`status`='23' " . (get_me_salary_user_by_id_user($id_user) || !$id_user ? " AND `{$GLOBALS['TABLE_sup_projects']}`.`total_price`>0 " : '') . " AND `{$GLOBALS['TABLE_sup_files_projects']}`.`made`!='0000-00-00 00:00:00' AND `{$GLOBALS['TABLE_sup_files_projects']}`.`made` LIKE '{$date}%' " . ($id_user ? " AND `{$GLOBALS['TABLE_sup_files_projects']}`.`id_user_operator`='{$id_user}' " : '') . " AND `{$GLOBALS['TABLE_sup_files']}`.`id`=`{$GLOBALS['TABLE_sup_files_projects']}`.`id_file` AND `{$GLOBALS['TABLE_sup_projects']}`.`id`=`{$GLOBALS['TABLE_sup_files_projects']}`.`id_project`;") or die(errorDiv(mysql_error()));
4578 $sum = mysql_result($sum, 0);
4579
4580 return round($sum);
4581}
4582
4583function get_progress_bar($id_user) // статус бара выдается два разных для менеджера/админа и для оператора, для первых как план дневной для компании, для оператора как деньги в его кошелек
4584{
4585 $id_user = round($id_user);
4586
4587 // определяем форму оплаты труда пользователя
4588 // нам нужно выводить статус_бар, показывающий сколько человек выполнил полезной работы для себя или для компании и выводить эту цифру в рублях, если у него есть план и процент или нет плана
4589 $form_payment = get_me_form_payment_user_by_id_user($id_user);
4590 switch ($form_payment) {
4591 case '0': // нет оплаты
4592 {
4593 return ''; // ничего не выводим
4594
4595 };
4596 break;
4597 case '1': // только оклад
4598 {
4599 return ''; // ничего не выводим
4600
4601 };
4602 break;
4603 case '2': // оклад с планом и процентами сверх плана
4604 {
4605 $plan_month = get_me_plan_user_by_id_user($id_user);
4606 $plan_day = $plan_month / get_me_working_days_user_by_id_user($id_user); // дневной план оператора 21 - кол-во рабочих дней
4607 $made_today = made_today_operator($id_user); // выполнено за сегодня оператором
4608 $made_month = made_month_operator($id_user); // выполнено за сегодня оператором
4609 $percent_remuneration_user = get_me_percent_remuneration_user_by_id_user($id_user); // проценты оператора
4610
4611 $k_today = round(($made_today * 100) / $plan_day, 2); // коэффициент успеваемости оператора сегодня в процентах относительно плана или дневного оклада, если есть план или дневной оклад
4612 $k_month = round($made_month * 100 / $plan_month, 2); // коэффициент успеваемости оператора сегодня в процентах относительно плана или дневного оклада, если есть план или дневной оклад
4613
4614 $title = ' за сегодня ' . $k_today . '%';
4615 if (in_array(auth('type'), array(1, 2))) {
4616 $title .= ' (' . addpoint($made_today) . ' руб./' . addpoint($plan_day) . ' руб.)';
4617 }
4618 $title .= ' за месяц ' . $k_month . '%';
4619
4620 if ($k_today < 25) {
4621 $color = getcolorrating(1);
4622 }
4623 if ($k_today >= 25 && $k_today < 50) {
4624 $color = getcolorrating(2);
4625 }
4626 if ($k_today >= 50 && $k_today < 75) {
4627 $color = getcolorrating(3);
4628 }
4629 if ($k_today >= 75 && $k_today < 100) {
4630 $color = getcolorrating(4);
4631 }
4632 if ($k_today >= 100) {
4633 $color = getcolorrating(5);
4634 }
4635
4636 $status_bar = "<a href=\"/?p=stats-made-projects-product&id={$id_user}&type=sum\"><span style=\"display:inline-block;text-align:left;width:200px;background:#ccc;border:1px solid #666;margin:5px;height:10px;\" title=\"{$title}\"><img src=\"/images/0.gif\" style=\"width:" . (round($k_today) > 100 ? 100 * 2 : round($k_today) * 2) . "px;background:{$color}height:10px;\" title=\"{$title}\" /></span></a>";
4637
4638 $ret = '<div><nobr>' . get_me_name_user_by_id_user($id_user) . ' ';
4639 // выводим статус бар, если
4640 $ret .= $status_bar . $k_today . '% ';
4641
4642 if (auth('type') == 3 && $percent_remuneration_user) {
4643 $ret .= 'сегодня = ' . addpoint(round($made_today * get_me_percent_remuneration_user_by_id_user($id_user) / 100)) . ' руб.';
4644 }
4645
4646 $ret .= '</nobr></div>';
4647
4648 return $ret;
4649
4650 };
4651 break;
4652 case '3': // только проценты
4653 {
4654 //$plan_day=get_me_plan_user_by_id_user($id_user)/get_me_working_days_user_by_id_user($id_user); // дневной план оператора 21 - кол-во рабочих дней
4655 //$salary_day=get_me_salary_user_by_id_user($id_user)/get_me_working_days_user_by_id_user($id_user); // дневной оклад оператора
4656 $made_today = made_today_operator($id_user); // выполнено за сегодня оператором
4657 $percent_remuneration_user = get_me_percent_remuneration_user_by_id_user($id_user); // проценты оператора
4658
4659 $k_today = round($made_today * $percent_remuneration_user / 100 * 100); // коэффициент успеваемости оператора сегодня в процентах относительно плана или дневного оклада, если есть план или дневной оклад
4660
4661 $title = $k_today . '%';
4662
4663 $ret = '<div><nobr>' . get_me_name_user_by_id_user($id_user) . ' ';
4664
4665 if (auth('type') == 3) {
4666 $ret .= 'сегодня = ' . addpoint(round($made_today * get_me_percent_remuneration_user_by_id_user($id_user) / 100)) . ' руб.';
4667 }
4668
4669 $ret .= '</nobr></div>';
4670
4671 return $ret;
4672
4673 };
4674 break;
4675 }
4676
4677
4678 /*
4679 if(in_array(auth('type'),array(1,2))) if(!$plan_day) $k_today=0; else $k_today=round(($made_today*100)/$plan_day); // коэффициент успеваемости оператора сегодня в процентах относительно плана или дневного оклада, если есть план или дневной оклад
4680 if(in_array(auth('type'),array(3))) if(!$salary_day) $k_today=0; else $k_today=round(($made_today*$percent_remuneration_user/100*100)/$salary_day); // коэффициент успеваемости оператора сегодня в процентах относительно плана или дневного оклада, если есть план или дневной оклад
4681
4682 $title=$k_today.'%';
4683 if(in_array(auth('type'),array(1,2))) $title.=' ('.addpoint($made_today).' руб./'.addpoint($plan_day).' руб.)';
4684
4685 if($k_today<=24) $color=getcolorrating(1);
4686 if($k_today>=25&&$k_today<=49) $color=getcolorrating(2);
4687 if($k_today>=50&&$k_today<=74) $color=getcolorrating(3);
4688 if($k_today>=75&&$k_today<=99) $color=getcolorrating(4);
4689 if($k_today>=100) $color=getcolorrating(5);
4690
4691 $status_bar="<a href=\"/?p=stats-made-projects-product&id={$id_user}&type=sum\"><span style=\"display:inline-block;text-align:left;width:200px;background:#ccc;border:1px solid #666;margin:5px;height:10px;\" title=\"{$title}\"><img src=\"/images/0.gif\" style=\"width:".($k_today>100?100*2:$k_today*2)."px;background:{$color}height:10px;\" title=\"{$title}\" /></span></a>";
4692
4693 $ret='<div><nobr>'.get_me_name_user_by_id_user($id_user).' ';
4694 // выводим статус бар, если
4695 if (
4696 $plan_day
4697 //||
4698 //$salary_day
4699 )
4700 { $ret.=$status_bar.$k_today.'% ';
4701 }
4702 if(auth('type')==3&&$percent_remuneration_user) $ret.='сегодня ТЕСТИРУЕТСЯ (!) = '.addpoint(round($made_today*get_me_percent_remuneration_user_by_id_user($id_user)/100)).' руб.';
4703 $ret.='</nobr></div>';
4704
4705 //if(!$plan_day) return ''; else return $ret;
4706 return $ret;
4707 */
4708}
4709
4710function decode_full_info_about_materials_in_project_by_id_project($array) // получаем и возвращаем полную информацию о материалах в этом проекте, сколько реза, сколько гравировки, сколько материала
4711{
4712 if (!$array) {
4713 return '';
4714 }
4715
4716 ksort($array);
4717
4718 foreach ($array as $id_label => $params) {
4719 $ret = '<div><u>' . get_me_name_label($id_label) . '</u>:<br />';
4720 $ret .= '<nobr>Рез - ' . round($params['cut'] / 1000) . ' м.</nobr><br />';
4721 $ret .= '<nobr>Конт.грав. - ' . round($params['engrave_contur'] / 1000) . ' м.</nobr><br />';
4722 $ret .= '<nobr>Грав.штрих. - ' . round($params['engrave_scan'] / 100) . ' см.<sup>2</sup></nobr><br />';
4723 $ret .= '<nobr>Материал - ' . round($params['area'] / 1000000, 2) . ' м.<sup>2</sup></nobr>';
4724 $ret .= '</div>';
4725 $ar_ret[] = $ret;
4726
4727 if ($params['cut'] + $params['engrave_contur'] + $params['engrave_scan'] + $params['area'] == 0) {
4728 $no_info = 1;
4729 }
4730 else {
4731 $no_info = 0;
4732 }
4733 }
4734 if ($no_info) {
4735 $ar_ret[] = "<div class='red strong' style='background:#fff;padding:3px;'>Не у всех макетов есть информация (!)</div>";
4736 }
4737 return implode('<br />', $ar_ret);
4738}
4739
4740function get_me_full_info_about_materials_in_project_by_id_project($id_project) // получаем и возвращаем полную информацию о материалах в этом проекте, сколько реза, сколько гравировки, сколько материала
4741{
4742 $id_project = round($id_project);
4743 if (!$id_project) {
4744 return 'Ошибка!';
4745 }
4746
4747 $ar = array();
4748
4749 // получаем массив id и имен всех операторов взявших файлы в этом проекте
4750 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_files_projects']}`,`{$GLOBALS['TABLE_sup_files']}` WHERE `{$GLOBALS['TABLE_sup_files_projects']}`.`id_project`='{$id_project}' AND `{$GLOBALS['TABLE_sup_files_projects']}`.`id_file`=`{$GLOBALS['TABLE_sup_files']}`.`id`;") or die(errorDiv(mysql_error()));
4751 $count = mysql_num_rows($result);
4752 if ($count) {
4753 for ($i = 0; $i < $count; $i++) {
4754 $subj = mysql_fetch_array($result);
4755
4756 // если эти значения не определены, то определяем
4757 if (!isset($ar[$subj['id_label']]['cut'])) {
4758 $ar[$subj['id_label']]['cut'] = 0;
4759 }
4760 if (!isset($ar[$subj['id_label']]['engrave_contur'])) {
4761 $ar[$subj['id_label']]['engrave_contur'] = 0;
4762 }
4763 if (!isset($ar[$subj['id_label']]['engrave_scan'])) {
4764 $ar[$subj['id_label']]['engrave_scan'] = 0;
4765 }
4766 if (!isset($ar[$subj['id_label']]['area'])) {
4767 $ar[$subj['id_label']]['area'] = 0;
4768 }
4769
4770 // суммируем все параметры
4771 $ar[$subj['id_label']]['cut'] += $subj['cut'] * $subj['count'];
4772 $ar[$subj['id_label']]['engrave_contur'] += $subj['engrave_contur'] * $subj['count'];
4773 $ar[$subj['id_label']]['engrave_scan'] += $subj['engrave_scan'] * $subj['count'];
4774 $ar[$subj['id_label']]['area'] += $subj['width'] * $subj['height'] * $subj['count'];
4775 }
4776 }
4777
4778 //print_r($ar);
4779 // В ПРОЕКТЕ ЕСТЬ МАКЕТЫ С НЕУКАЗАННЫМИ ДАННЫМИ
4780 //return '---s';
4781 return ($ar);
4782
4783}
4784
4785function dir_size($dir) // вычисляем объем директории, включая поддиректории
4786{
4787 $totalsize = 0;
4788 if ($dirstream = @opendir($dir)) {
4789 while (FALSE !== ($filename = readdir($dirstream))) {
4790 if ($filename != "." && $filename != "..") {
4791 if (is_file($dir . "/" . $filename)) {
4792 $totalsize += filesize($dir . "/" . $filename);
4793 }
4794
4795 if (is_dir($dir . "/" . $filename)) {
4796 $totalsize += dir_size($dir . "/" . $filename);
4797 }
4798 }
4799 }
4800 }
4801
4802 closedir($dirstream);
4803 return $totalsize;
4804}
4805
4806function db_size() // определяем объем БД
4807{
4808 $result = mysql_query("SHOW TABLE STATUS") or die(errorDiv(mysql_error()));
4809 $dbsize = 0;
4810
4811 while ($row = mysql_fetch_array($result)) {
4812 $dbsize += $row["Data_length"] + $row["Index_length"];
4813 }
4814
4815 return $dbsize;
4816}
4817
4818function formatfilesize($size) // преобразовываем объем данных в байтах в человеческй вид
4819{
4820 if (!$size) {
4821 $format_size = '0 Б';
4822 }
4823
4824 if ($size > 1024) {
4825 $format_size = round($size / 1024, 2) . ' КБ';
4826 }
4827 if ($size > (1024 * 1024)) {
4828 $format_size = round($size / (1024 * 1024), 2) . ' МБ';
4829 }
4830 if ($size > (1024 * 1024 * 1024)) {
4831 $format_size = round($size / (1024 * 1024 * 1024), 2) . ' ГБ';
4832 }
4833
4834 return $format_size;
4835}
4836
4837function get_me_surname_user_by_id_user($id) {
4838 //include_once "modules/connect_to_sup_db.php";
4839
4840 $id = round($id);
4841
4842 $surname = '';
4843
4844 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_users']}` WHERE `id`='{$id}';") or die(errorDiv(mysql_error()));
4845 if (mysql_num_rows($result)) {
4846 $subj = mysql_fetch_array($result);
4847 $surname = trim($subj['surname']);
4848 }
4849
4850 return $surname;
4851}
4852
4853function refresh_basket() {
4854 $sum_basket = 0;
4855 $count_basket = 0;
4856
4857 $query = "SELECT * FROM `{$GLOBALS['TABLE_sup_basket']}`,`{$GLOBALS['TABLE_sup_files']}` WHERE 1 AND `{$GLOBALS['TABLE_sup_files']}`.`id_user_del`='0' AND `{$GLOBALS['TABLE_sup_basket']}`.`session` = '" . session_id() . "' AND `{$GLOBALS['TABLE_sup_basket']}`.`id_file`=`{$GLOBALS['TABLE_sup_files']}`.`id` AND `{$GLOBALS['TABLE_sup_files']}`.`id_user` IN (SELECT `id` FROM `{$GLOBALS['TABLE_sup_users']}` WHERE `type`='5' OR `id`='" . (isset($_SESSION['id_client']) ? $_SESSION['id_client'] : '') . "')";
4858
4859 $result = mysql_query($query) or die(errorDiv(mysql_error()));
4860 $count = mysql_num_rows($result);
4861
4862 if ($count) {
4863 for ($i = 0; $i < $count; $i++) {
4864 $subj = mysql_fetch_array($result);
4865
4866 $sum_basket += $subj['count'] * $subj['pricefile'];
4867 $count_basket += $subj['count'];
4868 }
4869
4870 return "Товаров: {$count_basket} на сумму " . addpoint(str_replace(',', '.', round($sum_basket, 2))) . " руб.";
4871 }
4872 else {
4873 return "Пока пусто";
4874 }
4875
4876}
4877
4878function get_me_ids_user_manager_which_have_competence_for_files_in_basket_by_session_id($session_id) { // функция определяет подходящего менеджера исходя из его компетенций по видам работ файлов добавленных в корзину по session_id();
4879 // т.е. посетитель надобавлял файлов в корзину, оформил заявку, эта заявка должна назначиться какому-то менеджеру, для этого надо определить менеджера, который сможет...
4880 // "обслужить" все виды работ, которые посетитель навыбирал
4881
4882 $session_id = str_replace(array(
4883 '"',
4884 "'",
4885 '`',
4886 "/",
4887 "\\",
4888 '=',
4889 '?',
4890 '&',
4891 "#",
4892 ':',
4893 ' ',
4894 ), '', $session_id);
4895
4896 // получаем все файлы заказанные от этого session_id()
4897 $query = "SELECT * FROM `{$GLOBALS['TABLE_sup_basket']}`,`{$GLOBALS['TABLE_sup_files']}` WHERE 1 AND `{$GLOBALS['TABLE_sup_files']}`.`id_user_del`='0' AND `{$GLOBALS['TABLE_sup_basket']}`.`session` = '" . $session_id . "' AND `{$GLOBALS['TABLE_sup_basket']}`.`id_file`=`{$GLOBALS['TABLE_sup_files']}`.`id` AND `{$GLOBALS['TABLE_sup_files']}`.`id_user` IN (SELECT `id` FROM `{$GLOBALS['TABLE_sup_users']}` WHERE `type`='5' OR (`id`='" . (isset($_SESSION['id_client']) && $_SESSION['id_client'] ? $_SESSION['id_client'] : '0') . "' AND '" . (isset($_SESSION['id_client']) && $_SESSION['id_client'] ? $_SESSION['id_client'] : '0') . "'!='0'))";
4898 $result = mysql_query($query) or die(errorDiv(mysql_error()));
4899 $count = mysql_num_rows($result);
4900 if ($count) {
4901 for ($i = 1; $i <= $count; $i++) {
4902 $subj_files = mysql_fetch_array($result);
4903
4904 $ids_label[] = $subj_files['id_label'];
4905 }
4906 }
4907
4908 $ids_label; // список компетенции заказанных этим session_id
4909 $ids_user = array();
4910
4911 // пробегаемся по менеджерам, у которых флажок "не использовать для заявок с интернет-магазина" выключен (!) и проверяем каждого на соответствие компетенций заказу
4912 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_users']}` WHERE `type`='2' AND `not_use_for_magazin`='0'") or die(errorDiv(mysql_error()));
4913 $count = mysql_num_rows($result);
4914 if ($count) {
4915 for ($i = 1; $i <= $count; $i++) {
4916 $subj_user = mysql_fetch_array($result);
4917
4918 $answer = 1; // по умолчанию ответ на проверку умений (компетенций) 1 - умеет, далее будем проверять каждую компетенцию и если она не принадлежит этому юзеру, то вычеркнем
4919 foreach ($ids_label as $id_label) {
4920 $answer = $answer * COUNTROWS($GLOBALS['TABLE_sup_users_label'], " AND `id_label`='{$id_label}' AND `id_user`='{$subj_user['id']}' "); // если фукнция вернет ноль, то этот менеджер не обладает этой компетенцией
4921 }
4922
4923 if ($answer) {
4924 $ids_user[] = $subj_user['id'];
4925 } // если answer не превратился в ноль, то умения менеджера подтвердились
4926 }
4927 }
4928
4929 return implode(',', $ids_user);
4930 //print_r($ids_label);
4931}
4932
4933function get_me_random_manager() {
4934 // получаем id самого старого менеджера
4935 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_users']}` WHERE `type`='2' AND `not_use_for_magazin`='0' ORDER BY `datetime` ASC LIMIT 1;") or die(errorDiv(mysql_error()));
4936 $count = mysql_num_rows($result);
4937 if ($count) {
4938 $subj_user = mysql_fetch_array($result);
4939 return $subj_user['id'];
4940 }
4941}
4942
4943function send_report_order_from_internetmagazin_by_account_project($account) {
4944 global $user; // достаем из данные о пользователе оптима-ката, нужен логин, чтобы подставить в utm_source_for_...
4945
4946 // print_r($user);
4947
4948 //include_once "modules/connect_to_sup_db.php";
4949
4950 // $account=round($account); // НЕ ВКЛЮЧАТь! ПРЕОБРАЗУЕТ СТРОКУ В НЕПРИГОДНЫЙ ВИД
4951
4952 // получаем данные о проекте по номеру счета $account;
4953 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_projects']}` WHERE `account`='{$account}' LIMIT 1;") or die(errorDiv(mysql_error()));
4954 $count = mysql_num_rows($result);
4955 if ($count) {
4956 $project = mysql_fetch_array($result);
4957 if (!$project) {
4958 return FALSE;
4959 }
4960 }
4961
4962 // получаем данные о клиенте на основе его id_user, записанного к проекту;
4963 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_users']}` WHERE `id`='{$project['id_user']}' LIMIT 1;") or die(errorDiv(mysql_error()));
4964 $count = mysql_num_rows($result);
4965 if ($count) {
4966 $client = mysql_fetch_array($result);
4967 if (!$client) {
4968 return FALSE;
4969 }
4970 }
4971
4972 $name_manager = get_me_name_user_by_id_user($project['id_user_manager']);
4973 $name_client = $client['name'];
4974
4975 $to0 = readsql_system("emailfeedback") ? readsql_system("emailfeedback") : "noreply@optima-cut.ru"; // почта наша
4976 $useremail = decode_db(trim($client['email'])); // почта клиента
4977 $username = $name_client;
4978
4979 $source_order = (isset($_SESSION['id_client']) && $_SESSION['id_client']) ? "через личный кабинет" : "в интернет-магазине"; // если на момент заказа клиент был авторизован, то считаем через личный кабинет, если нет, то через интернет-магазин
4980
4981 $body_to_manager = "Клиент: <strong>{$name_client}</strong><br />\n";
4982 $body_to_manager .= "Менеджер: <strong>{$name_manager}</strong><br /><br />\n\n";
4983
4984 $body_to_manager .= "Пожалуйста, свяжитесь с клиентом и проинформируйте его о дальнейших действиях - <strong>" . get_me_phone_user_by_id_user($project['id_user']) . " {$name_client}</strong>.<br />\n<br />\n";
4985 $body_to_manager .= "Заказ на сумму - <strong>" . addpoint($project['total_price']) . " руб.</strong><br />\n";
4986 $body_to_manager .= "Заказу присвоен номер - <strong><a href=\"https://" . HOST_SUP . "/?p=projects&id={$project['id']}\" target=\"_blank\">{$project['id']}</a></strong><br />\n";
4987 if (isset($_COOKIE["utm_source_for_{$user['login']}"]) && $_COOKIE["utm_source_for_{$user['login']}"]) {
4988 $body_to_manager .= "<br />utm_source: " . $_COOKIE["utm_source_for_{$user['login']}"];
4989 }
4990
4991 $body_to_client = "<strong>Добрый день!</strong> Вы сделали заказ {$source_order} <a href=\"" . readsql_system("url_site") . "\">" . readsql_system("name_company") . "</a><br /><br />\n\n";
4992 $body_to_client .= "Заказ на сумму - <strong>" . addpoint($project['total_price']) . " руб.</strong> Вашему заказу присвоен номер - <strong>{$project['id']}</strong><br />\n";
4993 $body_to_client .= "Ваш заказ можно просмотреть <a href=\"https://" . HOST_SUP . "/client_version_project.php?id={$project['id']}&secure=" . md5($project['id'] . SALT) . "\" target=\"_blank\">по этой ссылке</a><br /><br />\n\n";
4994 $body_to_client .= "Ваш менеджер - <strong>{$name_manager}</strong>.<br />\n";
4995 $body_to_client .= "В ближайшее время {$name_manager} свяжется с Вами.<br /><br />\n\n";
4996 $body_to_client .= "Спасибо, что пользуетесь нашими услугами!";
4997
4998 $subj0 = readsql_system("name_company") . " - заказ {$source_order} " . date("d.m.Y H:i:s");
4999 $charset = "windows-1251";
5000 $type = "text/html";
5001
5002 // заявка нам на почту
5003
5004 $name0 = trim($username);
5005 $from0 = readsql_system("name_company");
5006
5007 if (check_rus($subj0) == TRUE) {
5008 $subj0 = base64_encode($subj0);
5009 $subj0 = "=?{$charset}?B?{$subj0}?=";
5010 }
5011 if (check_rus($from0) == TRUE) {
5012 $from0 = base64_encode($from0);
5013 $from0 = "=?{$charset}?B?{$from0}?=";
5014 }
5015 if (check_rus($name0) == TRUE) {
5016 $name0 = base64_encode($name0);
5017 $name0 = "=?{$charset}?B?{$name0}?=";
5018 }
5019
5020 $headers = "MIME-Version: 1.0\n";
5021 $headers .= "Date: " . date("D, d M Y H:i:s") . " +0300\n";
5022 $headers .= "To: {$from0} <{$to0}>\n";
5023 $headers .= "From: {$name0} <noreply@optima-cut.ru>\n";
5024 $headers .= "Reply-To: {$name0} <{$useremail}>\n";
5025 $headers .= "Content-Type: {$type}; charset={$charset}\n";
5026 $headers .= "Content-Transfer-Encoding: 8bit\n";
5027 $headers .= "X-Mailer: 3 " . HOST_SUP . " WWW.OPTIMA-CUT.RU for {$to0}";
5028
5029 //echo $headers;
5030 mail($to0, $subj0, $body_to_manager, $headers);
5031
5032 // / заявка нам на почту
5033
5034 // заявка юзеру на почту
5035
5036 $name0 = readsql_system("name_company");
5037 $from0 = trim($username);
5038
5039 if (check_rus($subj0) == TRUE) {
5040 $subj0 = base64_encode($subj0);
5041 $subj0 = "=?{$charset}?B?{$subj0}?=";
5042 }
5043 if (check_rus($from0) == TRUE) {
5044 $from0 = base64_encode($from0);
5045 $from0 = "=?{$charset}?B?{$from0}?=";
5046 }
5047 if (check_rus($name0) == TRUE) {
5048 $name0 = base64_encode($name0);
5049 $name0 = "=?{$charset}?B?{$name0}?=";
5050 }
5051
5052 $headers = "MIME-Version: 1.0\n";
5053 $headers .= "Date: " . date("D, d M Y H:i:s") . " +0300\n";
5054 $headers .= "To: {$from0} <{$useremail}>\n";
5055 $headers .= "From: {$name0} <noreply@optima-cut.ru>\n";
5056 $headers .= "Reply-To: {$name0} <{$to0}>\n";
5057 $headers .= "Content-Type: {$type}; charset={$charset}\n";
5058 $headers .= "Content-Transfer-Encoding: 8bit\n";
5059 $headers .= "X-Mailer: 4 " . HOST_SUP . " WWW.OPTIMA-CUT.RU for {$useremail}";
5060
5061 //echo $headers;
5062 mail($useremail, $subj0, $body_to_client, $headers);
5063
5064 // / заявка юзеру на почту
5065
5066}
5067
5068function get_id_parent_file_by_id_file($id) {
5069 //include_once "modules/connect_to_sup_db.php";
5070
5071 $id = round($id);
5072
5073 $id_user = '';
5074
5075 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_files']}` WHERE 1 AND `id_user_del`='0' AND `id`='{$id}';") or die(errorDiv(mysql_error()));
5076 if (mysql_num_rows($result)) {
5077 $subj = mysql_fetch_array($result);
5078 $id_user = trim($subj['id_user']);
5079 }
5080
5081 return $id_user;
5082}
5083
5084function ban($comment = '', $delayed = 0) {
5085 $ip = get_user_ip();
5086
5087 $comment_base64_encode = base64_encode($comment);
5088 $comment = str_replace(array(
5089 '"',
5090 "'",
5091 '`',
5092 "/",
5093 "\\",
5094 '=',
5095 '?',
5096 '&',
5097 '.',
5098 '-',
5099 "#",
5100 ':',
5101 ), '', $comment);
5102
5103 mysql_query("INSERT INTO `{$GLOBALS['TABLE_sup_ban']}` (`datetime`,`ip`,`comment`,`comment_base64`, `datetime_del`) VALUES (NOW()+INTERVAL {$delayed} MINUTE,'{$ip}','{$comment}','{$comment_base64_encode}', NOW());") or die(errorDiv(mysql_error()));
5104}
5105
5106function ban_test($comment = '') // функция добавляет в бан-лист ip
5107{
5108 $shit_codes = array(
5109 '<',
5110 '>',
5111 '*',
5112 "\\",
5113 '`',
5114 '"',
5115 "'",
5116 'http:',
5117 'https:',
5118 'ftp:',
5119 '://',
5120 '/admin/',
5121 '/phpmyadmin/',
5122 '/administrator/',
5123 '/bitrix/',
5124 '/admin.js',
5125 '/wp-admin/',
5126 'script',
5127 'from000',
5128 'char',
5129 '/*',
5130 '*/',
5131 ' or ',
5132 'union',
5133 'select',
5134 'insert',
5135 'update000',
5136 'delete000',
5137 'where',
5138 'join',
5139 'script',
5140 'java',
5141 'onload',
5142 'onerror',
5143 'onmouse',
5144 'onclick',
5145 'object',
5146 'applet',
5147 'iframe',
5148 'frame000',
5149 "'",
5150 '"',
5151 '`',
5152 '<?',
5153 '?>',
5154 'preg_replace',
5155 'require_once',
5156 'include_once',
5157 'include',
5158 'require',
5159 'create_function',
5160 );
5161 foreach ($shit_codes as $key => $value) {
5162 if (strpos(' ' . $_SERVER['REQUEST_URI'], $value)) {
5163 ban("Недопустимые символы в адресной строке: " . $_SERVER['REQUEST_URI'], 2);
5164 }
5165 }
5166
5167
5168 if (get_subdomain() == 'graver43-rf'
5169 ||
5170 get_subdomain() == 'invergroup-ru'
5171 ||
5172 get_subdomain() == 'ooo_art-voyazher'
5173 ||
5174 get_subdomain() == 'artpelikan-ru'
5175 ||
5176 get_subdomain() == 'lazer-grav-ucoz-ru'
5177 ||
5178 get_subdomain() == 'woodenbox-ru'
5179 ||
5180 get_subdomain() == 'skankod'
5181 ||
5182 get_subdomain() == 'lazer_tk'
5183 ||
5184 1 == 1
5185 ) {
5186 }
5187 else {
5188 $ip = get_user_ip();
5189 if (COUNTROWS($GLOBALS['TABLE_sup_ban'], " AND `ip`='{$ip}' AND `datetime_del`='0000-00-00 00:00:00' ")) {
5190 die("Ваш IP временно заблокирован. Свяжитесь с руководством сайта.");
5191 }
5192 }
5193}
5194
5195// определяем выводить или нет помощник-путеводитель по системе со всеми ее справочниками и важными разделами
5196function tour_on_the_system_on() {
5197 // если не админ, не менеджер и не исполнитель, то выключаем подсказку
5198 if (!in_array(auth('type'), array(1, 2, 3))) {
5199 return 0;
5200 }
5201
5202 // если id есть в списке запрещенных, то выключаем подсказку
5203 return round(strpos('. ' . readsql_system("tour_on_the_system_readed") . ' ', ' ' . auth('id') . ' ')) ? 0 : 1;
5204
5205}
5206
5207
5208/*
5209 function get_utm_source($url='') // вручную достаем utm_source из адресной строки, т.к. $_GET[utm_source] работает почему-то не всегда
5210 {
5211 if(!trim($url))$url=$_SERVER['REQUEST_URI'];
5212
5213 if(strpos($url,'utm_source='))
5214 {
5215 $utm_source=array_pop(explode('utm_source=',$url));
5216 if(strpos($utm_source,'&')) $utm_source=array_shift(explode('&',$utm_source));
5217 if(strpos($utm_source,'?')) $utm_source=array_shift(explode('?',$utm_source));
5218 }
5219
5220 return $utm_source;
5221 }
5222*/
5223
5224// читаем письма из почты
5225class mread {
5226
5227 private $mbox = '';
5228
5229 private $htmlmsg = '';
5230
5231 private $plainmsg = '';
5232
5233 private $charset = '';
5234
5235 private $attachments = array();
5236
5237 private $unread;
5238
5239 public function __get($name) {
5240 if ($name == 'mail') {
5241 return $this->unread;
5242 }
5243 else {
5244 return NULL;
5245 }
5246 }
5247
5248 public function getmail() {
5249 return $this->unread;
5250 } /* backwards compatibility for php4*/
5251 public function mread($host, $login, $pwd) { /* backwards compatibility for php 4, __constructor*/
5252 $messages = array();
5253 $folder = "INBOX";
5254 //$folder="[Gmail]/&BCEEPwQwBDw-"; // если вам захочется почитать спам на гугломыле.
5255
5256 $this->mbox = @imap_open("{$host}{$folder}", $login, $pwd); // or die(imap_last_error());
5257 $arr = @imap_search($this->mbox, 'ALL');
5258 if ($arr && $arr !== FALSE) {
5259 foreach ($arr as $i) {
5260 $headerArr = imap_headerinfo($this->mbox, $i);
5261 $mailArr =
5262 array(
5263 'from' => $headerArr->from[0]->mailbox . "@" . $headerArr->from[0]->host,
5264 'to' => $headerArr->to[0]->mailbox . "@" . $headerArr->to[0]->host,
5265 'reply-to' => $headerArr->reply_to[0]->mailbox . "@" . $headerArr->reply_to[0]->host,
5266 'date' => $headerArr->date,
5267 'size' => $headerArr->Size,
5268 'subject' => $headerArr->subject,
5269 );
5270 $this->getmsg($i);
5271 imap_setflag_full($this->mbox, $i, "\\Seen");
5272 // var_dump($this->htmlmsg,$this->plainmsg,$this->charset,$this->attachments);
5273 $messages[] = array(
5274 'from' => $mailArr['from'],
5275 'reply-to' => $mailArr['reply-to'],
5276 'date' => date("Y-m-d H:i:s", strtotime($mailArr['date'])),
5277 'timestamp' => strtotime($mailArr['date']),
5278 'to' => $mailArr['to'],
5279 'name' => $this->decode($headerArr->from[0]->personal),
5280 'subject' => $this->decode($mailArr['subject']),
5281 'charset' => $this->charset,
5282 'plain' => nl2br($this->plainmsg),
5283 'html' => $this->preparetext($this->htmlmsg),
5284 'attach' => $this->decodefilename($this->attachments),
5285 );
5286 imap_delete($this->mbox, $i);
5287 }
5288
5289 $this->unread = $messages;
5290 unset($messages);
5291 }
5292 else {
5293 $this->unread = FALSE;
5294 }
5295
5296 @imap_expunge($this->mbox);
5297 @imap_close($this->mbox);
5298 }
5299
5300 private function decode($enc) {
5301
5302 $parts = imap_mime_header_decode($enc);
5303 $str = '';
5304 for ($p = 0; $p < count($parts); $p++) {
5305 $ch = $parts[$p]->charset;
5306 $part = $parts[$p]->text;
5307 if ($ch !== 'default' && $ch !== 'x-unknown' && $ch !== 'windows-1251') {
5308 $str .= mb_convert_encoding($part, 'windows-1251', $ch);
5309 }
5310 else {
5311 $str .= $part;
5312 }
5313
5314 //$str.=" (кодировка:{$ch})"; // приписываем какую кодировку определил скрипт
5315 }
5316 //return iconv('utf-8', 'windows-1251', $str);
5317 return $str;
5318
5319 }
5320
5321 private function decodefilename($array) // декодируем заголовки прикрепленных файлов
5322 {
5323 $ret = array();
5324
5325 // пробегаемся по массиву и создаем новый массив, где ключами являются декодированные заголовки, а значениями сами файлы
5326 foreach ($array as $filename => $file) {
5327 $ret[$this->decode($filename)] = $file;
5328 }
5329
5330 return $ret;
5331 }
5332
5333 public function preparetext($str) // преобразуем текст их html в текст красиво
5334 {
5335
5336 $str = preg_replace("'<script[^>]*?>.*?</script>'si", '', $str); // сперва вырезаем все скрипты, чтобы не оставить мусора в коде
5337
5338 $str = preg_replace("'<style[^>]*?>.*?</style>'si", '', $str); // вырезаем стили
5339
5340 $str = str_replace(">", "> ", $str);
5341
5342 $str = preg_replace("'<div[^>]*?>'si", '<br />', $str); // все начинающиеся дивы заменяем на перенос, чтобы более-менее сохранить форматирование страницы
5343 $str = str_replace('</div>', '<br />', $str); // все заканчивающиеся дивы заменяем на перенос, чтобы более-менее сохранить форматирование страницы
5344
5345 $str = strip_tags($str, "<a><b><strong><u><i><img><br><br /><br/>"); // потом вырезаем все теги кроме ссылок и переносов
5346
5347 $str = str_replace("<a ", "<a target=\"_blank\" ", $str);
5348
5349 $str = str_ireplace(array(
5350 'onblur',
5351 'onchange',
5352 'onclick',
5353 'ondblclick',
5354 'onerror',
5355 'onfocus',
5356 'onkeydown',
5357 'onkeypress',
5358 'onkeyup',
5359 'onload',
5360 'onmousedown',
5361 'onmousemove',
5362 'onmouseout',
5363 'onmouseover',
5364 'onmouseup',
5365 'onmove',
5366 'onreset',
5367 'onresize',
5368 'onselect',
5369 'onsubmit',
5370 'onunload',
5371 ), '', $str); // вырезаем все события наложенные на объекты
5372
5373 $str = trim($str); // обрезаем концевые пробелы
5374
5375 $str = nl2br($str); // заменяем переносы строки на <br />
5376
5377 $str = str_replace(array(
5378 "\n",
5379 "\r",
5380 ' ',
5381 "style=",
5382 "class=",
5383 ), '', $str); // удаляем переносы каретки, возвраты каретки и символы табуляции
5384
5385 $str = preg_replace("/ +/", " ", $str); // заменяем все повторяющиеся пробелы на один
5386
5387 $str = str_replace(array(
5388 '<br>',
5389 '<br/>',
5390 ), '<br />', $str); // все <br /> приводим к одному виду
5391
5392 while (strpos(' ' . $str, "<br /> ")) {
5393 $str = str_replace("<br /> ", "<br />", $str);
5394 } // удаляем переносы с пробелом
5395
5396 while (strpos(' ' . $str, "<br /><br /><br />")) {
5397 $str = str_replace("<br /><br /><br />", "<br /><br />", $str);
5398 } // удаляем множественные переносы
5399
5400 if (substr($str, 0, 12) == '<br /><br />') {
5401 $str = substr($str, 12);
5402 } // после всех преобразований проверяем, если первые 12 символов это два переноса строки - вырезаем их
5403 if (substr($str, -12, 12) == '<br /><br />') {
5404 $str = substr($str, 0, strlen($str) - 12);
5405 } // после всех преобразований проверяем, если последние 12 символов это два переноса строки - вырезаем их
5406
5407 return $str;
5408
5409 }
5410
5411 private function preparetext0($str) // преобразуем текст их html в текст красиво
5412 {
5413 $search = array(
5414 "'<script[^>]*?>.*?</script>'si", // Вырезает javaScript
5415 "'([\r\n])[\s]+'", // Вырезает пробельные символы
5416 "'&(quot|#34);'i", // Заменяет HTML-сущности
5417 "'&(amp|#38);'i",
5418 "'&(lt|#60);'i",
5419 "'&(gt|#62);'i",
5420 "'&(nbsp|#160);'i",
5421 "'&(iexcl|#161);'i",
5422 "'&(cent|#162);'i",
5423 "'&(pound|#163);'i",
5424 "'&(copy|#169);'i",
5425 "'&#(\d+);'e",
5426 ); // интерпретировать как php-код
5427
5428 $replace = array(
5429 " ",
5430 "<br />",
5431 "\"",
5432 "&",
5433 "<",
5434 ">",
5435 " ",
5436 chr(161),
5437 chr(162),
5438 chr(163),
5439 chr(169),
5440 "chr(\\1)",
5441 );
5442
5443 $str = preg_replace($search, $replace, $str);
5444
5445 $str = preg_replace("/ +/", " ", $str); // заменяем все повторяющиеся пробелы на один
5446 $str = str_replace("<br /> ", "<br />", $str); // заменяем
5447 while (strpos($str, "<br /><br />")) {
5448 $str = str_replace("<br /><br />", "<br />", $str);
5449 } // удаляем множественные переносы
5450
5451 return $str;
5452 }
5453
5454 private function getmsg($mid) {
5455 $this->htmlmsg = $this->plainmsg = $this->charset = '';
5456 $this->attachments = array();
5457
5458 $s = imap_fetchstructure($this->mbox, $mid);
5459 if (!$s->parts) {
5460 $this->getpart($mid, $s, 0);
5461 }
5462 else {
5463 foreach ($s->parts as $partno0 => $p) {
5464 $this->getpart($mid, $p, $partno0 + 1);
5465 }
5466 }
5467 }
5468
5469 private function getpart($mid, $p, $partno) {
5470 $data = ($partno) ? imap_fetchbody($this->mbox, $mid, $partno) : imap_body($this->mbox, $mid);
5471 if ($p->encoding == 4) {
5472 $data = quoted_printable_decode($data);
5473 }
5474 elseif ($p->encoding == 3) {
5475 $data = base64_decode($data);
5476 }
5477
5478 $params = array();
5479 if ($p->parameters) {
5480 foreach ($p->parameters as $x) {
5481 $params[strtolower($x->attribute)] = $x->value;
5482 }
5483 }
5484 if ($p->dparameters) {
5485 foreach ($p->dparameters as $x) {
5486 $params[strtolower($x->attribute)] = $x->value;
5487 }
5488 }
5489
5490 if ((isset($params['filename']) && $params['filename']) || (isset($params['name']) && $params['name'])) {
5491 $filename = (isset($params['filename']) && $params['filename']) ? $params['filename'] : $params['name'];
5492 $this->attachments[$filename] = $data; // если 2 файла с одним именем - тут баг. TODO
5493 }
5494 elseif ($p->type == 0 && $data) {
5495 $autocorrection = '';
5496
5497 if (!trim($params['charset'])) // ЭКСПЕРИМЕНТ (!)
5498 { // если кодировка не определена автоматически, и в тексте находим символы русского алфавита (за исключением Р и С), то принимаем решение, что это windows-1251 текст
5499 // иначе, что это utf-8
5500 if (strpos(' ', $data, array(
5501 'й',
5502 'ф',
5503 'я',
5504 'ц',
5505 'ы',
5506 'ч',
5507 'у',
5508 'в',
5509 'с',
5510 'к',
5511 'а',
5512 'м',
5513 'е',
5514 'п',
5515 'и',
5516 'н',
5517 'р',
5518 'т',
5519 'г',
5520 'о',
5521 'ь',
5522 'ш',
5523 'л',
5524 'б',
5525 'щ',
5526 'д',
5527 'ю',
5528 'з',
5529 'ж',
5530 'х',
5531 'э',
5532 'ъ',
5533 'Й',
5534 'Ф',
5535 'Я',
5536 'Ц',
5537 'Ы',
5538 'Ч',
5539 'У',
5540 'В',
5541 'К',
5542 'А',
5543 'М',
5544 'Е',
5545 'П',
5546 'И',
5547 'Н',
5548 'Т',
5549 'Г',
5550 'О',
5551 'Ь',
5552 'Ш',
5553 'Л',
5554 'Б',
5555 'Щ',
5556 'Д',
5557 'Ю',
5558 'З',
5559 'Ж',
5560 'Х',
5561 'Э',
5562 'Ъ',
5563 ))) {
5564 $params['charset'] = 'windows-1251';
5565 }
5566 else {
5567 $params['charset'] = 'utf-8';
5568 }
5569 $autocorrection = 'auto:';
5570 }
5571
5572 if (strtolower($p->subtype) == 'plain') { // преобразуем кодировку только в том случае, когда она определена
5573 $this->plainmsg .= $params['charset'] ? trim(mb_convert_encoding($data, 'windows-1251', $params['charset'])) : trim($data); // ."\n\n";
5574 }
5575 else { // преобразуем кодировку только в том случае, когда она определена
5576 // опускаем теги
5577 $this->htmlmsg .= $params['charset'] ? trim(mb_convert_encoding($data, 'windows-1251', $params['charset'])) : trim($data); // ."\n\n";
5578 }
5579 $this->charset = $autocorrection . $params['charset']; // прописываем плюсик автокоррекции, чтобы отследить потом такие письма
5580 }
5581 elseif ($p->type == 2 && $data) {
5582 $this->plainmsg .= trim(nl2br($data)); // ."\n\n";
5583 }
5584
5585 if ($p->parts) {
5586 foreach ($p->parts as $partno0 => $p2) {
5587 $this->getpart($mid, $p2, $partno . '.' . ($partno0 + 1));
5588 }
5589 }
5590 }
5591}
5592
5593// выводим превысила ли разница между текущей меткой времени и меткой времени последнего ответа клиенту на его заявку заданное в настройках количество дней
5594function check_delay_answer_email($last_out) {
5595 if (!readsql_system("waiting_response")) {
5596 return 0;
5597 }
5598 $last_out = str_replace(array(' ', ':'), '-', $last_out);
5599 $last_out_ar = explode('-', $last_out);
5600 $last_out_mktime = mktime($last_out_ar[3], $last_out_ar[4], $last_out_ar[5], $last_out_ar[1], $last_out_ar[2], $last_out_ar[0]);
5601 $storage_period = time() - $last_out_mktime;
5602 $storage_period = round($storage_period / 86400, 3);
5603
5604 return $storage_period > readsql_system("waiting_response") ? 1 : 0;
5605}
5606
5607// разница в секундах между двумя датами
5608function difference_time($time1, $time2) {
5609 // echo $time1.' - '.$time2;
5610
5611 $time1 = explode('-', str_replace(array(' ', ':'), '-', $time1));
5612 $mktime1 = mktime($time1[3], $time1[4], $time1[5], $time1[1], $time1[2], $time1[0]);
5613 $time2 = explode('-', str_replace(array(' ', ':'), '-', $time2));
5614 $mktime2 = mktime($time2[3], $time2[4], $time2[5], $time2[1], $time2[2], $time2[0]);
5615
5616 if ($mktime1 > $mktime2) {
5617 return $mktime1 - $mktime2;
5618 }
5619 if ($mktime2 > $mktime1) {
5620 return $mktime2 - $mktime1;
5621 }
5622 if ($mktime1 == $mktime2) {
5623 return $mktime1;
5624 }
5625}
5626
5627function br2nl($string) {
5628 $string = str_replace("\n", '', $string); // предварително удаляем все уже имеющиеся переносы строки
5629 return preg_replace('/\<br(\s*)?\/?\>/i', "\n", $string); // заменяем все <br > на переносы
5630}
5631
5632function prepare_letter_for_anser($string, $dop) // функция подставляет в началой каждой строки угловую скобку, чтобы сделать это письмо "историей" и два переноса строки перед
5633{
5634 $str = '';
5635
5636 $string_a = explode("\n", $string);
5637 foreach ($string_a as $value) {
5638 $str .= ">" . trim($value) . "\n";
5639 }
5640
5641 $str = strftime("%A, %d %B %G, %R", time()) . $dop . "\n" . $str;
5642
5643 $str = "\n\n\n" . $str;
5644
5645 return $str;
5646}
5647
5648
5649/**
5650 * SendMailSmtpClass
5651 *
5652 * Класс для отправки писем через SMTP с авторизацией
5653 * Может работать через SSL протокол
5654 * Тестировалось на почтовых серверах yandex.ru, mail.ru и gmail.com
5655 *
5656 * @author Ipatov Evgeniy <admin@ipatov-soft.ru>
5657 * @version 1.0
5658 */
5659class SendMailSmtpClass {
5660
5661 /**
5662 *
5663 * @var string $smtp_username - логин
5664 * @var string $smtp_password - пароль
5665 * @var string $smtp_host - хост
5666 * @var string $smtp_from - от кого
5667 * @var integer $smtp_port - порт
5668 * @var string $smtp_charset - кодировка
5669 *
5670 */
5671 public $smtp_username;
5672
5673 public $smtp_password;
5674
5675 public $smtp_host;
5676
5677 public $smtp_from;
5678
5679 public $smtp_port;
5680
5681 public $smtp_charset;
5682
5683 public function __construct($smtp_username, $smtp_password, $smtp_host, $smtp_from, $smtp_port = 25, $smtp_charset = "windows-1251") {
5684 $this->smtp_username = $smtp_username;
5685 $this->smtp_password = $smtp_password;
5686 $this->smtp_host = $smtp_host;
5687 $this->smtp_from = $smtp_from;
5688 $this->smtp_port = $smtp_port;
5689 $this->smtp_charset = $smtp_charset;
5690 }
5691
5692 /**
5693 * Отправка письма
5694 *
5695 * @param string $mailTo - получатель письма
5696 * @param string $subject - тема письма
5697 * @param string $message - тело письма
5698 * @param string $headers - заголовки письма
5699 *
5700 * @return bool|string В случаи отправки вернет true, иначе текст ошибки
5701 * *
5702 */
5703 function send($mailTo, $subject, $message, $headers) {
5704 //$contentMail = "Date: " . date("D, d M Y H:i:s") . " UT\r\n";
5705
5706 $contentMail = '';
5707 $contentMail .= 'Subject: ' . $subject . "\r\n"; // не кодируем, т.к. приходит уже закодированным
5708
5709
5710 $contentMail .= $headers . "\r\n";
5711 $contentMail .= $message . "\r\n";
5712
5713// die("<textarea>".$contentMail."</textarea>");
5714
5715 try {
5716 if (!$socket = @fsockopen($this->smtp_host, $this->smtp_port, $errorNumber, $errorDescription, 30)) {
5717 throw new Exception($errorNumber . "." . $errorDescription);
5718 }
5719 if (!$this->_parseServer($socket, "220")) {
5720 throw new Exception('Connection error');
5721 }
5722
5723 $server_name = $_SERVER["SERVER_NAME"];
5724 //fputs($socket, "HELO $server_name\r\n");
5725 fputs($socket, "EHLO $server_name\r\n");
5726 if (!$this->_parseServer($socket, "250")) {
5727 fclose($socket);
5728 throw new Exception('Error of command sending: HELO');
5729 }
5730
5731 fputs($socket, "AUTH LOGIN\r\n");
5732 if (!$this->_parseServer($socket, "334")) {
5733 fclose($socket);
5734 throw new Exception('Autorization error');
5735 }
5736
5737
5738 fputs($socket, base64_encode($this->smtp_username) . "\r\n");
5739 if (!$this->_parseServer($socket, "334")) {
5740 fclose($socket);
5741 throw new Exception('Autorization error (username)');
5742 }
5743
5744 fputs($socket, base64_encode($this->smtp_password) . "\r\n");
5745 if (!$this->_parseServer($socket, "235")) {
5746 fclose($socket);
5747 throw new Exception('Autorization error (password)');
5748 }
5749
5750 fputs($socket, "MAIL FROM: <" . $this->smtp_username . ">\r\n");
5751 if (!$this->_parseServer($socket, "250")) {
5752 fclose($socket);
5753 throw new Exception('Error of command sending: MAIL FROM');
5754 }
5755
5756 $mailTo = ltrim($mailTo, '<');
5757 $mailTo = rtrim($mailTo, '>');
5758 fputs($socket, "RCPT TO: <" . $mailTo . ">\r\n");
5759 if (!$this->_parseServer($socket, "250")) {
5760 fclose($socket);
5761 throw new Exception('Error of command sending: RCPT TO');
5762 }
5763
5764 fputs($socket, "DATA\r\n");
5765 if (!$this->_parseServer($socket, "354")) {
5766 fclose($socket);
5767 throw new Exception('Error of command sending: DATA');
5768 }
5769
5770 fputs($socket, $contentMail . "\r\n.\r\n");
5771 if (!$this->_parseServer($socket, "250")) {
5772 fclose($socket);
5773 throw new Exception("E-mail didn't sent");
5774 }
5775
5776 fputs($socket, "QUIT\r\n");
5777 fclose($socket);
5778 } catch (Exception $e) {
5779 return $e->getMessage();
5780 }
5781 return TRUE;
5782 }
5783
5784 private function _parseServer($socket, $response) {
5785 while (@substr($responseServer, 3, 1) != ' ') {
5786 if (!($responseServer = fgets($socket, 256))) {
5787 return FALSE;
5788 }
5789 }
5790 if (!(substr($responseServer, 0, 3) == $response)) {
5791 return FALSE;
5792 }
5793 return TRUE;
5794
5795 }
5796}
5797
5798/*
5799 function get_me_email_delivery_for_this_client($sub_domain)
5800 {
5801 return $sub_domain;
5802 }
5803 */
5804
5805function rebuild_gant() {
5806 // ТЕПЕРЬ если мы здесь находим записи о макетах, которые находятся в проектах со статусами 30, 40 или 50 и porn!='', то сдвигаем им porn на количество таких макетов в каждом станке
5807 shift_porn();
5808
5809 // удаляем все записи о станках, очередности и времени выполнения каждого изделия
5810 // если никто не взял и менеджер не закрепил макет за этим станком, можем сбросить все
5811 mysql_query("UPDATE `{$GLOBALS['TABLE_sup_files_projects']}` SET `id_equipment`='0', `porn`='0' WHERE `id_user_operator`='0' AND `protect`='0';") or die(errorDiv(mysql_error()));
5812
5813 mysql_query("UPDATE `{$GLOBALS['TABLE_sup_files_projects']}` SET `porn`='0' WHERE `id_user_operator`!='0' AND `protect`='0' AND `status`!='23';") or die(errorDiv(mysql_error()));
5814
5815 mysql_query("UPDATE `{$GLOBALS['TABLE_sup_files_projects']}` SET `porn`='0' WHERE `status`='23' AND DATE_FORMAT(`made`,'%Y-%m-%d') < CURRENT_DATE();") or die(errorDiv(mysql_error()));
5816
5817 // перебираем все макеты всех статусов в запущенных проектах, чтобы каждому подобрать оптимальный станок
5818 $result = mysql_query("SELECT *,`{$GLOBALS['TABLE_sup_files_projects']}`.`id` AS `id_files_projects`
5819 FROM `{$GLOBALS['TABLE_sup_projects']}`,`{$GLOBALS['TABLE_sup_files_projects']}`,`{$GLOBALS['TABLE_sup_files']}`
5820 WHERE 1
5821 AND `{$GLOBALS['TABLE_sup_files_projects']}`.`status` IN ('10','20','21','22')
5822 AND `{$GLOBALS['TABLE_sup_projects']}`.`status` IN ('10','20','21','22')
5823 AND `{$GLOBALS['TABLE_sup_projects']}`.`id_user_del`='0'
5824 AND `{$GLOBALS['TABLE_sup_projects']}`.`visible`='1'
5825 AND `{$GLOBALS['TABLE_sup_projects']}`.`id`=`{$GLOBALS['TABLE_sup_files_projects']}`.`id_project`
5826 AND `{$GLOBALS['TABLE_sup_files_projects']}`.`id_file`=`{$GLOBALS['TABLE_sup_files']}`.`id`
5827 ORDER BY
5828 `{$GLOBALS['TABLE_sup_projects']}`.`deadline` ASC,
5829 `{$GLOBALS['TABLE_sup_files']}`.`id_label` ASC /*, `{$GLOBALS['TABLE_sup_files']}`.`cut` DESC */;") or die(errorDiv(mysql_error()));
5830 $count = mysql_num_rows($result);
5831
5832 # ФОРМИРУЕМ ЛЕНТУ
5833 if ($count) {
5834 for ($i = 0; $i < $count; $i++) {
5835 $subj = mysql_fetch_array($result);
5836
5837 $ar = select_equipment_for_gant($subj['id_files_projects']); // определяем наиболее подходящий станок для этого макета с учетом текущей загрузки производства
5838
5839 mysql_query("UPDATE `{$GLOBALS['TABLE_sup_files_projects']}` SET `id_equipment`='{$ar['id_equipment']}', `time`='{$ar['time_production']}' WHERE `id`='{$subj['id_files_projects']}';") or die(errorDiv(mysql_error()));
5840 mysql_query("UPDATE `{$GLOBALS['TABLE_sup_files_projects']}` SET `porn`='" . free_porn($ar['id_equipment']) . "' WHERE `id`='{$subj['id_files_projects']}' AND `porn`='0';") or die(errorDiv(mysql_error()));
5841 }
5842 }
5843
5844}
5845
5846function rebuild_gant0() {
5847 // удаляем все записи о станках, очередности и времени выполнения каждого изделия
5848 // если никто не взял и менеджер не закрепил макет за этим станком, можем сбросить все
5849 mysql_query("UPDATE `{$GLOBALS['TABLE_sup_files_projects']}` SET `id_equipment`='0', `time`='0', `porn`='0' WHERE `id_user_operator`='0' AND `protect`='0';") or die(errorDiv(mysql_error()));
5850 // во всех остальных случаях скидываем время и очередность
5851 mysql_query("UPDATE `{$GLOBALS['TABLE_sup_files_projects']}` SET `time`='0', `porn`='0' WHERE `id_user_operator`!='0' AND `protect`='0';") or die(errorDiv(mysql_error()));
5852 mysql_query("UPDATE `{$GLOBALS['TABLE_sup_files_projects']}` SET `time`='0', `porn`='0' WHERE `id_user_operator`='0' AND `protect`!='0';") or die(errorDiv(mysql_error()));
5853 mysql_query("UPDATE `{$GLOBALS['TABLE_sup_files_projects']}` SET `time`='0', `porn`='0' WHERE `id_user_operator`!='0' AND `protect`!='0';") or die(errorDiv(mysql_error()));
5854
5855 // время изготовления сбрасываем для всех макетов всегда. Будем всегда его пересчитывать
5856 // mysql_query("UPDATE `{$GLOBALS['TABLE_sup_files_projects']}` SET `porn`='0' WHERE 1;");
5857
5858 // mysql_query("UPDATE `{$GLOBALS['TABLE_sup_files_projects']}` SET `time`='0' WHERE 1;");
5859 // mysql_query("UPDATE `{$GLOBALS['TABLE_sup_files_projects']}` SET `porn`='0' WHERE 1;");
5860
5861 // а если макет уже принят, то сбрасываем только очередность, сохраняя id оператора принявшего макет и id станка, на который этот макет был назначен
5862 // mysql_query("UPDATE `{$GLOBALS['TABLE_sup_files_projects']}` SET `time`='0', `porn`='0' WHERE `id_user_operator`!='0' AND `protect`='0';");
5863 // а если макет кем-то принят и протект стоит, то нельзя трогать очередность, обнуляем только время изготовления, чтобы потом вычислить его заново
5864 // mysql_query("UPDATE `{$GLOBALS['TABLE_sup_files_projects']}` SET `time`='0' WHERE `id_user_operator`!='0' AND `protect`='1';");
5865
5866
5867 // перебираем все макеты всех статусов в запущенных проектах, чтобы каждому подобрать оптимальный станок
5868 $result = mysql_query("SELECT *,`{$GLOBALS['TABLE_sup_files_projects']}`.`id` AS `id_files_projects` FROM `{$GLOBALS['TABLE_sup_projects']}`,`{$GLOBALS['TABLE_sup_files_projects']}`,`{$GLOBALS['TABLE_sup_files']}` WHERE `{$GLOBALS['TABLE_sup_projects']}`.`status` IN ('10','20','21','22') AND `{$GLOBALS['TABLE_sup_projects']}`.`id_user_del`='0' AND `{$GLOBALS['TABLE_sup_projects']}`.`visible`='1' AND `{$GLOBALS['TABLE_sup_projects']}`.`id`=`{$GLOBALS['TABLE_sup_files_projects']}`.`id_project` AND `{$GLOBALS['TABLE_sup_files_projects']}`.`id_file`=`{$GLOBALS['TABLE_sup_files']}`.`id` ORDER BY `{$GLOBALS['TABLE_sup_projects']}`.`deadline` ASC, `{$GLOBALS['TABLE_sup_files']}`.`id_label` ASC, `{$GLOBALS['TABLE_sup_files']}`.`cut` DESC;") or die(errorDiv(mysql_error()));
5869 $count = mysql_num_rows($result);
5870
5871 # ФОРМИРУЕМ ЛЕНТУ
5872 if ($count) {
5873 for ($i = 0; $i < $count; $i++) {
5874 $subj = mysql_fetch_array($result);
5875
5876 //echo $subj['id_files_projects']." - ";
5877 $ar = select_equipment_for_gant($subj['id_files_projects']); // определяем наиболее подходящий станок для этого макета с учетом текущей загрузки производства
5878 //echo "<br />";
5879 // mysql_query("UPDATE `{$GLOBALS['TABLE_sup_files_projects']}` SET `id_equipment`='{$ar['id_equipment']}', `time`='{$ar['time_production']}' WHERE `id`='{$subj['id_files_projects']}';");
5880 // mysql_query("UPDATE `{$GLOBALS['TABLE_sup_files_projects']}` SET `porn`='".(MAXITEM($GLOBALS['TABLE_sup_files_projects'],"porn"," AND `id_equipment`='{$ar['id_equipment']}' ")+1)."' WHERE `id`='{$subj['id_files_projects']}';");
5881
5882 mysql_query("UPDATE `{$GLOBALS['TABLE_sup_files_projects']}` SET `id_equipment`='{$ar['id_equipment']}', `time`='{$ar['time_production']}', `porn`='" . (MAXITEM($GLOBALS['TABLE_sup_files_projects'], "porn", " AND `id_equipment`='{$ar['id_equipment']}' ") + 1) . "' WHERE `id`='{$subj['id_files_projects']}';") or die(errorDiv(mysql_error()));
5883 // mysql_query("UPDATE `{$GLOBALS['TABLE_sup_files_projects']}` SET WHERE `id`='{$subj['id_files_projects']}';");
5884 }
5885 }
5886
5887}
5888
5889function free_porn($id_equipment) // функция получает свободный порядковый номер на этом станке. Например, если уже есть номера 1, 2, 3 и 5, то функция вернет 4
5890{
5891 // получаем из имеющегося массива чисел первое отсутствующее значение, чтобы в это место поставить (этой очередностью) изготовление изделия
5892 // а если свободных нет, то возвращаем следующее изделие, т.е. max+1, чтобы на этот номер назначить макет
5893
5894 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_files_projects']}` WHERE 1
5895 AND `id_equipment`='{$id_equipment}'
5896 /* AND `id_project` IN (SELECT `id` FROM `{$GLOBALS['TABLE_sup_projects']}` WHERE `status` IN ('10','20','21','22') AND `id_user_del`='0' AND `visible`='1') */
5897 AND
5898 ( `status` IN ('10','20','21','22','23')
5899 /*OR
5900 (
5901 `status`='23' AND `protect`='1'
5902 )*/
5903 )
5904
5905 ;") or die(errorDiv(mysql_error()));
5906 $count = mysql_num_rows($result);
5907
5908 # ФОРМИРУЕМ ЛЕНТУ
5909 if ($count) {
5910 for ($i = 0; $i < $count; $i++) {
5911 $subj = mysql_fetch_array($result);
5912
5913 $ar[] = $subj['porn']; // определяем наиболее подходящий станок для этого макета с учетом текущей загрузки производства
5914 }
5915 }
5916
5917 if (!$ar) {
5918 return 1;
5919 } // если массив значений не определился, то возвращаем позицию 1
5920
5921 // $ar=array(1,2,4,5,3);
5922
5923 ksort($ar); // сортируем массив
5924
5925 $max = max($ar); // определяем бОльшее значение в массиве
5926 $min = min($ar); // определяем меньшее значение в массиве
5927 $null = 0; // по умолчанию говорим, что дырка равна нулю
5928
5929 // перебираем все значения от меньшего к большего по пути ищя дырку, если находим значение, которого нет в массиве, то говорим, что это и есть дырка
5930 for ($i = $min; $i <= $max; $i++) {
5931 if (!in_array($i, $ar) && !$null) {
5932 $null = $i;
5933 }
5934 }
5935
5936 // если перебрали весь массив и дырки не нашли, выводим новый порядковый номер, как максимальное значение +1
5937 if (!$null) {
5938 $null = $max + 1;
5939 }
5940
5941 return $null;
5942
5943}
5944
5945function shift_porn() {
5946 // будем сдвигать очередь только для тех макетов, которые еще находятся в очереди, НЕ ЗАЩИЩЕНЫ ПРОТЕКТОМ, и находятся в уже не рабочих проектах
5947 // а если макет защищен протектом, то потенциально он еще находится в очереди на своем месте и свое место занять не дает, т.к. он может быть снова вернут в очередь и тогда он должен встать на свое место
5948 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_files_projects']}` WHERE 1
5949 AND `porn`!='0'
5950 AND `status`='23'
5951 AND DATE_FORMAT(`made`,'%Y-%m-%d') < CURRENT_DATE() /* при сдвигании протектных изделий сдвигаем только для выполненных за вчерашний день */
5952 ORDER BY `porn` ASC;") or die(errorDiv(mysql_error()));
5953 $count = mysql_num_rows($result);
5954
5955 # ФОРМИРУЕМ ЛЕНТУ
5956 if ($count) {
5957 for ($i = 0; $i < $count; $i++) {
5958 $subj = mysql_fetch_array($result);
5959
5960 // сдвигаем только макеты с protect = 1, т.к. другие сами расставятся как нужно, а с protect не пересчитываются
5961 mysql_query("UPDATE `{$GLOBALS['TABLE_sup_files_projects']}` SET `porn`=`porn`-1 WHERE `porn`>'{$subj['porn']}' AND `protect`!='0' AND `id_equipment`='{$subj['id_equipment']}' AND `porn`>1;") or die(errorDiv(mysql_error()));
5962
5963 }
5964 }
5965
5966
5967}
5968
5969function select_equipment_for_one_file($id_file, $id_label = 0) // определяем список станков, подходящих для изготовления этого изделия по этому макету. Нужно для задания предпочтительного станка
5970{
5971
5972 // $id_label - если передаем сюда вид материала, то находим станки подходящие под этот вид материала, если не передаем, то под тот, что указан у файла
5973
5974 // проверяем, чтобы приходило не отличное от цифры значение
5975 if (round($id_file) != $id_file) {
5976 die('Ошибка 0615070815');
5977 }
5978
5979 // $id_file - id файла
5980 // получаем размер этого файла и виды работ, содержащиеся в нем, резку, контурную гравировку и гравировку штриховкой
5981 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_files']}` WHERE `id`='{$id_file}';") or die(errorDiv(mysql_error()));
5982 if (mysql_num_rows($result)) {
5983 $file = mysql_fetch_array($result);
5984 }
5985
5986 if (!$file) {
5987 die('Ошибка 0715070815');
5988 } // если вдруг не удалось получить макет по какой-то причине
5989
5990 $equipments = array();
5991
5992 // здесь надо проверить наличие каждой из характеристик и подобрать станок, у которого ширина и высота поля больше, чем у файла при том, что ни одно из этих значений у файла не равно нулю
5993 // и скорости исполнения работ, имеющихся в файле, для этого станка не равны нулю. Выводить список подходящего оборудования начиная с самой большой скорости реза
5994 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_equipment']}`,`{$GLOBALS['TABLE_sup_equipment_label']}` WHERE 1
5995 AND `{$GLOBALS['TABLE_sup_equipment']}`.`id_user_del`=0
5996 AND `{$GLOBALS['TABLE_sup_equipment']}`.`position`='1'
5997 AND `{$GLOBALS['TABLE_sup_equipment']}`.`id`=`{$GLOBALS['TABLE_sup_equipment_label']}`.`id_equipment`
5998 AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`id_label`='" . ($id_label ? $id_label : $file['id_label']) . "'
5999 AND (
6000 ( `{$GLOBALS['TABLE_sup_equipment']}`.`x` >= '{$file['width']}' AND `{$GLOBALS['TABLE_sup_equipment']}`.`y` >= '{$file['height']}' )
6001 OR
6002 ( `{$GLOBALS['TABLE_sup_equipment']}`.`x` >= '{$file['height']}' AND `{$GLOBALS['TABLE_sup_equipment']}`.`y` >= '{$file['width']}' )
6003 )
6004 AND '{$file['width']}'!='0'
6005 AND '{$file['height']}'!='0'
6006 AND ('{$file['cut']}'!='0' OR '{$file['engrave_contur']}'!='0' OR '{$file['engrave_scan']}'!='0')
6007 " . ($file['cut'] ? " AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`speed_cut`>'0' " : '') . "
6008 " . ($file['engrave_contur'] ? " AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`speed_engrave_cut`>'0' " : '') . "
6009 " . ($file['engrave_scan'] ? " AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`speed_engrave_scan`>'0' AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`interval_engrave_scan`>'0' " : '') . "
6010 ORDER BY `{$GLOBALS['TABLE_sup_equipment_label']}`.`speed_cut` DESC;") or die(errorDiv(mysql_error()));
6011
6012 $count = mysql_num_rows($result);
6013
6014 # ФОРМИРУЕМ ЛЕНТУ
6015 if ($count) {
6016 for ($i = 0; $i < $count; $i++) {
6017 $equipment = mysql_fetch_array($result);
6018
6019 // записываем время, когда станок закончит изготовление этого изделия
6020 $equipments[$equipment['id_equipment']] = $equipment['name'];
6021 }
6022 }
6023
6024 return $equipments;
6025}
6026
6027function select_equipment_for_one_file_doppossible($id_file, $id_label = 0) // определяем ДОПОЛНИТЕЛЬНЫЙ ВОЗМОЖНЫЙ список станков, подходящих для изготовления этого изделия по этому макету, НО КОТОРЫЕ НЕ ПОДХОДЯТ ПО РАЗМЕРАМ
6028{
6029
6030 // $id_label - если передаем сюда вид материала, то находим станки подходящие под этот вид материала, если не передаем, то под тот, что указан у файла
6031
6032 // проверяем, чтобы приходило не отличное от цифры значение
6033 if (round($id_file) != $id_file) {
6034 die('Ошибка 1500151115');
6035 }
6036
6037 // $id_file - id файла
6038 // получаем размер этого файла и виды работ, содержащиеся в нем, резку, контурную гравировку и гравировку штриховкой
6039 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_files']}` WHERE `id`='{$id_file}';") or die(errorDiv(mysql_error()));
6040 if (mysql_num_rows($result)) {
6041 $file = mysql_fetch_array($result);
6042 }
6043
6044 if (!$file) {
6045 die('Ошибка 0715070815');
6046 } // если вдруг не удалось получить макет по какой-то причине
6047
6048 $equipments = array();
6049
6050 // здесь надо проверить наличие каждой из характеристик и подобрать станок, у которого ширина и высота поля больше, чем у файла при том, что ни одно из этих значений у файла не равно нулю
6051 // и скорости исполнения работ, имеющихся в файле, для этого станка не равны нулю. Выводить список подходящего оборудования начиная с самой большой скорости реза
6052 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_equipment']}`,`{$GLOBALS['TABLE_sup_equipment_label']}` WHERE 1
6053 AND `{$GLOBALS['TABLE_sup_equipment']}`.`id_user_del`=0
6054 AND `{$GLOBALS['TABLE_sup_equipment']}`.`position`='1'
6055 AND `{$GLOBALS['TABLE_sup_equipment']}`.`id`=`{$GLOBALS['TABLE_sup_equipment_label']}`.`id_equipment`
6056 AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`id_label`='" . ($id_label ? $id_label : $file['id_label']) . "'
6057 AND (
6058 ( `{$GLOBALS['TABLE_sup_equipment']}`.`x` < '{$file['width']}' OR `{$GLOBALS['TABLE_sup_equipment']}`.`y` < '{$file['height']}' )
6059 AND
6060 ( `{$GLOBALS['TABLE_sup_equipment']}`.`x` < '{$file['height']}' OR `{$GLOBALS['TABLE_sup_equipment']}`.`y` < '{$file['width']}' )
6061 )
6062 AND '{$file['width']}'!='0'
6063 AND '{$file['height']}'!='0'
6064 AND ('{$file['cut']}'!='0' OR '{$file['engrave_contur']}'!='0' OR '{$file['engrave_scan']}'!='0')
6065 " . ($file['cut'] ? " AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`speed_cut`>'0' " : '') . "
6066 " . ($file['engrave_contur'] ? " AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`speed_engrave_cut`>'0' " : '') . "
6067 " . ($file['engrave_scan'] ? " AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`speed_engrave_scan`>'0' AND `{$GLOBALS['TABLE_sup_equipment_label']}`.`interval_engrave_scan`>'0' " : '') . "
6068 ORDER BY `{$GLOBALS['TABLE_sup_equipment_label']}`.`speed_cut` DESC;") or die(errorDiv(mysql_error()));
6069
6070 $count = mysql_num_rows($result);
6071
6072 # ФОРМИРУЕМ ЛЕНТУ
6073 if ($count) {
6074 for ($i = 0; $i < $count; $i++) {
6075 $equipment = mysql_fetch_array($result);
6076
6077 // записываем время, когда станок закончит изготовление этого изделия
6078 $equipments[$equipment['id_equipment']] = '(' . $equipment['name'] . ')';
6079 }
6080 }
6081
6082 return $equipments;
6083}
6084
6085function check_possible_turn_file($id_equipment, $window = 1) {
6086 //return 1;
6087 // менеджеру открыты все макеты
6088 if (in_array(auth('type'), array(1, 2))) {
6089 return 1;
6090 }
6091
6092 $possible = array();
6093 //$dop=array();
6094 $counter = 0;
6095
6096 // на этом станке получаем список макетов, которые находятся в очереди на исполнение (`porn`!=0), сортируя их по возрастанию `porn`
6097 $result = mysql_query("SELECT *,
6098 `{$GLOBALS['TABLE_sup_files_projects']}`.`status` AS `status_fp`,
6099 `{$GLOBALS['TABLE_sup_files_projects']}`.`id_user_operator` AS `id_user_operator_fp`,
6100 `{$GLOBALS['TABLE_sup_files_projects']}`.`id` AS `id_fp`,
6101 `{$GLOBALS['TABLE_sup_files_projects']}`.`protect` AS `protect_fp`,
6102 `{$GLOBALS['TABLE_sup_files_projects']}`.`id_file` AS `id_file_fp`
6103 FROM `{$GLOBALS['TABLE_sup_files_projects']}`,`{$GLOBALS['TABLE_sup_projects']}` WHERE
6104
6105 `{$GLOBALS['TABLE_sup_files_projects']}`.`id_project`=`{$GLOBALS['TABLE_sup_projects']}`.`id`
6106 AND
6107 `{$GLOBALS['TABLE_sup_projects']}`.`visible`!='0'
6108 AND
6109 `{$GLOBALS['TABLE_sup_files_projects']}`.`id_equipment`='{$id_equipment}'
6110 AND
6111 `{$GLOBALS['TABLE_sup_files_projects']}`.`porn`!=0
6112
6113 ORDER BY `{$GLOBALS['TABLE_sup_files_projects']}`.`porn` ASC;") or die(errorDiv(mysql_error()));
6114
6115 $count = mysql_num_rows($result);
6116 if ($count) {
6117 for ($i = 0; $i < $count; $i++) {
6118 $a = mysql_fetch_array($result);
6119
6120 // записываем массив с возможными файлами таким хитрым алгоритмом
6121 // ищем первый подходящий макет и как только его нашли, запускаем счетчик макетов, который не должен превысить $window-1
6122 // соот-но, как только счетчик запустился, то считаем и добавляем в окно все макеты подряд, до тех пор, пока счетчик не достигнет ширины окна
6123 if (
6124 (
6125 (
6126 (in_array($a['status_fp'], array('10')) && !$a['id_user_operator_fp']) // либо макет "ждет очереди" ни под кем
6127 ||
6128 (in_array($a['status_fp'], array('10')) && $a['id_user_operator_fp'] == auth('id')) // либо макет "ждет очереди" назначенным мне
6129 ||
6130 (in_array($a['status_fp'], array('20')) && $a['id_user_operator_fp'] == auth('id')) // либо "в процессе" назначенным или взятым мной
6131 )
6132 ||
6133 $counter
6134 )
6135 && ($counter < $window)
6136 ) {
6137 if
6138 (
6139 (in_array($a['status_fp'], array('10')) && !$a['id_user_operator_fp']) // либо макет "ждет очереди" ни под кем
6140 ||
6141 (in_array($a['status_fp'], array('10')) && $a['id_user_operator_fp'] == auth('id')) // либо макет "ждет очереди" назначенным мне
6142 ||
6143 (in_array($a['status_fp'], array('20')) && $a['id_user_operator_fp'] == auth('id')) // либо "в процессе" назначенным или взятым мной
6144 ||
6145 (in_array($a['status_fp'], array('21')) && !$a['id_user_operator_fp']) // либо "трудности с выполнением" ни под кем
6146 ||
6147 (in_array($a['status_fp'], array('21')) && $a['id_user_operator_fp'] == auth('id')) // либо "трудности с выполнением" подо мной
6148 ||
6149 (in_array($a['status_fp'], array('22')) && !$a['id_user_operator_fp']) // либо "нехватка материала" ни под кем
6150 ||
6151 (in_array($a['status_fp'], array('22')) && $a['id_user_operator_fp'] == auth('id')) // либо "нехватка материала" подо мной
6152 ||
6153 (in_array($a['status_fp'], array('23')) && $a['id_user_operator_fp'] == auth('id')) // либо выполнен подо мной
6154 ) {
6155 $possible[] = $a['id_fp'];
6156
6157 // ДОП-1
6158 // если макет не установлен "вручную", то дополняем массив доступных к исполнению макетов макетами такого же материала такой же даты сдачи, чтобы можно было закомпановать
6159 if (!$a['protect_fp']) {
6160 $dop[get_me_id_label_by_id_file($a['id_file_fp']) . '#' . get_me_deadline_project(get_me_id_project_by_id_files_project($a['id_fp']))] = 1;
6161 } // запоминаем материал попавший в окно и дедлайн для него. Позже дополним окно этими материаламм при этом сроке сдачи
6162
6163 $counter++;
6164 }
6165 }
6166 }
6167 }
6168
6169 // ДОП-2
6170 // надо определить id макетов, которые УЖЕ делаются и разрешить их делать. Это нужно в тех случаях, когда окно было шире и его решили сузить, оставив часть макетов "за бортом", так вот к ним должен быть доступ
6171 $result = mysql_query("SELECT *, `{$GLOBALS['TABLE_sup_files_projects']}`.`id` AS `id_fp` FROM `{$GLOBALS['TABLE_sup_files_projects']}`,`{$GLOBALS['TABLE_sup_projects']}` WHERE `{$GLOBALS['TABLE_sup_files_projects']}`.`id_project`=`{$GLOBALS['TABLE_sup_projects']}`.`id` AND `{$GLOBALS['TABLE_sup_projects']}`.`visible`!='0' AND `{$GLOBALS['TABLE_sup_files_projects']}`.`id_equipment`='{$id_equipment}' AND `{$GLOBALS['TABLE_sup_files_projects']}`.`porn`!='0' AND
6172 (
6173 (`{$GLOBALS['TABLE_sup_files_projects']}`.`status`='20' AND `{$GLOBALS['TABLE_sup_files_projects']}`.`id_user_operator`='" . auth('id') . "' )
6174 OR
6175 (`{$GLOBALS['TABLE_sup_files_projects']}`.`status`='21' AND `{$GLOBALS['TABLE_sup_files_projects']}`.`id_user_operator`='" . auth('id') . "' )
6176 OR
6177 (`{$GLOBALS['TABLE_sup_files_projects']}`.`status`='21' AND `{$GLOBALS['TABLE_sup_files_projects']}`.`id_user_operator`='0' )
6178 OR
6179 (`{$GLOBALS['TABLE_sup_files_projects']}`.`status`='22' AND `{$GLOBALS['TABLE_sup_files_projects']}`.`id_user_operator`='" . auth('id') . "' )
6180 OR
6181 (`{$GLOBALS['TABLE_sup_files_projects']}`.`status`='22' AND `{$GLOBALS['TABLE_sup_files_projects']}`.`id_user_operator`='0' )
6182 OR
6183 (`{$GLOBALS['TABLE_sup_files_projects']}`.`status`='23' AND `{$GLOBALS['TABLE_sup_files_projects']}`.`id_user_operator`='" . auth('id') . "' )
6184 );") or die(errorDiv(mysql_error()));
6185 $count = mysql_num_rows($result);
6186 if ($count) {
6187 for ($i = 0; $i < $count; $i++) {
6188 $a = mysql_fetch_array($result);
6189
6190 // записываем массив с возможными файлами
6191 $possible[] = $a['id_fp'];
6192 }
6193 }
6194
6195 // здесь нужно докампоновать массив допустимых id макетов id макетов того же материала тех же сроков сдачи
6196 if (isset($dop) && $dop) {
6197 foreach ($dop as $str => $value) {
6198 list($id_label, $deadline) = explode('#', $str);
6199
6200 // echo "<br/>SELECT *,`{$GLOBALS['TABLE_sup_files_projects']}`.`id` AS `id_files_projects` FROM `{$GLOBALS['TABLE_sup_projects']}`,`{$GLOBALS['TABLE_sup_files']}`,`{$GLOBALS['TABLE_sup_files_projects']}` WHERE `{$GLOBALS['TABLE_sup_files_projects']}`.`id_file`=`{$GLOBALS['TABLE_sup_files']}`.`id` AND `{$GLOBALS['TABLE_sup_files_projects']}`.`id_project`=`{$GLOBALS['TABLE_sup_projects']}`.`id` AND `{$GLOBALS['TABLE_sup_files_projects']}`.`id_equipment`='{$id_equipment}' AND `{$GLOBALS['TABLE_sup_files']}`.`id_label`='{$id_label}' AND `{$GLOBALS['TABLE_sup_projects']}`.`deadline`='{$deadline}' AND `{$GLOBALS['TABLE_sup_files_projects']}`.`porn`!='0' AND `{$GLOBALS['TABLE_sup_files_projects']}`.`status` IN ('10');";
6201
6202 $result = mysql_query("SELECT *,`{$GLOBALS['TABLE_sup_files_projects']}`.`id` AS `id_files_projects` FROM `{$GLOBALS['TABLE_sup_projects']}`,`{$GLOBALS['TABLE_sup_files']}`,`{$GLOBALS['TABLE_sup_files_projects']}` WHERE `{$GLOBALS['TABLE_sup_files_projects']}`.`id_file`=`{$GLOBALS['TABLE_sup_files']}`.`id` AND `{$GLOBALS['TABLE_sup_files_projects']}`.`id_project`=`{$GLOBALS['TABLE_sup_projects']}`.`id` AND `{$GLOBALS['TABLE_sup_files_projects']}`.`id_equipment`='{$id_equipment}' AND `{$GLOBALS['TABLE_sup_files']}`.`id_label`='{$id_label}' AND `{$GLOBALS['TABLE_sup_projects']}`.`visible`!='0' AND `{$GLOBALS['TABLE_sup_projects']}`.`deadline`='{$deadline}' AND `{$GLOBALS['TABLE_sup_files_projects']}`.`porn`!='0' AND
6203 (
6204 ( `{$GLOBALS['TABLE_sup_files_projects']}`.`status`='10' AND `{$GLOBALS['TABLE_sup_files_projects']}`.`id_user_operator`='0' ) /* дополняем другими макетами того же материала и того же дедлайна в статусе ЖДЕТ ОЧЕРЕДИ, которые не назначены никому */
6205 OR
6206 ( `{$GLOBALS['TABLE_sup_files_projects']}`.`status`='10' AND `{$GLOBALS['TABLE_sup_files_projects']}`.`id_user_operator`='" . auth('id') . "' ) /* или которые назначены мне, чтобы случайно не захватить макет, назначенный Васе, но стоящий в ЖДЕТ ОЧЕРЕДИ, но подходящий по макету и дедлайну */
6207 );
6208 ") or die(errorDiv(mysql_error()));
6209 $count = mysql_num_rows($result);
6210 if ($count) {
6211 for ($j = 0; $j < $count; $j++) {
6212 $a = mysql_fetch_array($result);
6213
6214 // записываем массив с возможными файлами
6215 $possible[] = $a['id_files_projects'];
6216 }
6217 }
6218
6219 }
6220 }
6221
6222 //print_r($possible);
6223 // возвращаем массив доступных для исполнения
6224 return $possible;
6225
6226}
6227
6228function copy_layout($id_file, $id_user) {
6229 if ($id_file != round($id_file)) {
6230 die('Ошибка 1756011115');
6231 }
6232 if ($id_user != round($id_user)) {
6233 die('Ошибка 1757011115');
6234 }
6235
6236 $id_newfile = 0;
6237
6238 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_files']}` WHERE `id`='{$id_file}' LIMIT 1;") or die(errorDiv(mysql_error()));
6239 $count = mysql_num_rows($result);
6240 if ($count) {
6241 $subj = mysql_fetch_array($result);
6242
6243 // СОЗДАТЬ КОПИИ ВСЕХ ЧЕТЫРЕХ ФАЙЛОВ С НОВЫМИ ИМЕНАМИ
6244
6245 // КОПИРУЕМ FILE_PREVIEW
6246 $filename_new = date('Y-m-d-H-i-s_') . mt_rand(10000000, 99999999) . '.' . get_me_file_type($subj['file_preview']); // получаем новое имя
6247 if (@copy($GLOBALS['PUTH_files'] . $subj['file_preview'], $GLOBALS['PUTH_files'] . $filename_new)) {
6248 $file_preview = $filename_new;
6249 }
6250 else {
6251 $file_preview = '';
6252 }
6253 //
6254
6255 // КОПИРУЕМ FILE_PREVIEW_MINI
6256 $filename_new = date('Y-m-d-H-i-s_') . mt_rand(10000000, 99999999) . '_mini.' . get_me_file_type($subj['file_preview_mini']); // получаем новое имя
6257 if (@copy($GLOBALS['PUTH_files'] . $subj['file_preview_mini'], $GLOBALS['PUTH_files'] . $filename_new)) {
6258 $file_preview_mini = $filename_new;
6259 }
6260 else {
6261 $file_preview_mini = '';
6262 }
6263 //
6264
6265 // КОПИРУЕМ FILE_CDR
6266 $filename_new = date('Y-m-d-H-i-s_') . mt_rand(10000000, 99999999) . '.' . get_me_file_type($subj['file_cdr']); // получаем новое имя
6267 if (@copy($GLOBALS['PUTH_files'] . $subj['file_cdr'], $GLOBALS['PUTH_files'] . $filename_new)) {
6268 $file_cdr = $filename_new;
6269 }
6270 else {
6271 $file_cdr = '';
6272 }
6273 //
6274
6275 // КОПИРУЕМ FILE_DXF
6276 $filename_new = date('Y-m-d-H-i-s_') . mt_rand(10000000, 99999999) . '.' . get_me_file_type($subj['file_dxf']); // получаем новое имя
6277 if (@copy($GLOBALS['PUTH_files'] . $subj['file_dxf'], $GLOBALS['PUTH_files'] . $filename_new)) {
6278 $file_dxf = $filename_new;
6279 }
6280 else {
6281 $file_dxf = '';
6282 }
6283 //
6284
6285 // / СОЗДАТЬ КОПИИ ВСЕХ ЧЕТЫРЕХ ФАЙЛОВ С НОВЫМИ ИМЕНАМИ
6286
6287 // СОЗДАТЬ ЗАПИСЬ В БД С ИЗМЕННЫМ ID, TEXT_ID И НОВЫМИ ИМЕНАМИ ФАЙЛОВ
6288
6289 $now = date('Y-m-d H:i:s');
6290 // записываем в таблицу скопированные файлы
6291 mysql_query("INSERT INTO `{$GLOBALS['TABLE_sup_files']}` (`datetime`,`id_user`,`last_used`,`titlefile`,`template`,`id_label`,`pricefile`,`descriptionfile`,`commentfile`,`articlefile`,`id_user_manager`,`file_preview`,`file_preview_mini`,`file_cdr`,`file_dxf`,`width`,`height`,`cut`,`engrave_contur`,`engrave_scan`,`recommendations`,`id_equipment`,`legend`, `text_id`, `file_source`, `id_equipment_exception`, `bending`, `id_user_del`, `datetime_del`) VALUES ('{$now}','{$id_user}','{$now}','{$subj['titlefile']}','{$subj['template']}','{$subj['id_label']}','{$subj['pricefile']}','{$subj['descriptionfile']}','{$subj['commentfile']}','{$subj['articlefile']}','{$subj['id_user_manager']}','{$file_preview}','{$file_preview_mini}','{$file_cdr}','{$file_dxf}','{$subj['width']}','{$subj['height']}','{$subj['cut']}','{$subj['engrave_contur']}','{$subj['engrave_scan']}','{$subj['recommendations']}','{$subj['id_equipment']}','{$subj['legend']}', '', '', '', '{$subj['bending']}', 0, '{$subj['datetime_del']}');") or die(errorDiv(mysql_error()));
6292
6293 // получаем id свежесозданного файла
6294 if (!($id_newfile = SUM($GLOBALS['TABLE_sup_files'], 'id', " AND `datetime`='{$now}' AND `file_dxf`='{$file_dxf}' AND `file_cdr`='{$file_cdr}' AND `file_preview_mini`='{$file_preview_mini}' AND `file_preview`='{$file_preview}' AND `id_user_manager`='{$subj['id_user_manager']}' AND `descriptionfile`='{$subj['descriptionfile']}' AND `id_label`='{$subj['id_label']}' AND `template`='{$subj['template']}' AND `titlefile`='{$subj['titlefile']}' AND `commentfile`='{$subj['commentfile']}' AND `articlefile`='{$subj['articlefile']}' AND `id_user`='{$id_user}' "))) {
6295 die('Ошибка 5-1. Обратитесь к менеджерам компании-разработчика');
6296 }
6297
6298 // прописываем text_id отдельным запросом, т.к. для этого нам надо было получить id добавленной записи
6299 mysql_query("UPDATE `{$GLOBALS['TABLE_sup_files']}` SET `text_id`='{$id_newfile}-" . translit($subj['titlefile']) . "' WHERE `id`='{$id_newfile}'; ") or die(errorDiv(mysql_error()));
6300
6301 // / СОЗДАТЬ ЗАПИСЬ В БД С ИЗМЕННЫМ ID, TEXT_ID И НОВЫМИ ИМЕНАМИ ФАЙЛОВ
6302
6303 }
6304
6305 return $id_newfile;
6306}
6307
6308function kazan() {
6309 //if(strpos(' '.get_subdomain(),'kazan-laser')) return 1; else return 0;
6310 if (strpos(' ' . get_subdomain(), 'demo-ru')) {
6311 return 1;
6312 }
6313 else {
6314 return 0;
6315 }
6316}
6317
6318function demo() {
6319 //if(strpos(' '.get_subdomain(),'kazan-laser')) return 1; else return 0;
6320 if (strpos(' ' . get_subdomain(), 'demo-ru')) {
6321 return 1;
6322 }
6323 else {
6324 return 0;
6325 }
6326}
6327
6328function lateness($start_time, $visit_time) // функция вычисляющая разницу в минутах между временем $time в формате 00:00 и текущей меткой времени
6329{
6330 if (!strpos($start_time, ':')) {
6331 return 0;
6332 } // если в заданном времени прихода сотрудника на работу не нашли двоеточия, значит формат времени не задан
6333 if (!strpos($visit_time, ':')) {
6334 return 0;
6335 } // если в заданном времени прихода сотрудника на работу не нашли двоеточия, значит формат времени не задан
6336
6337 $start_time_a = explode(':', $start_time);
6338 $start_time = round($start_time_a[0]) * 60 + round($start_time_a[1]);
6339
6340 $visit_time_a = explode(':', $visit_time);
6341 $visit_time = round($visit_time_a[0]) * 60 + round($visit_time_a[1]);
6342
6343 if ($visit_time + -$start_time >= 0) {
6344 return $visit_time + -$start_time;
6345 }
6346 else {
6347 return 0;
6348 }
6349}
6350
6351function simple_interface() // определяем упрощенный или обычный интерфейс включен у пользователя. Возвращаем 1, если упрощенный
6352{
6353 // if(strpos(' '.get_subdomain(),'demo-ru')) return 1; else return 0;
6354
6355 // if(strpos(' '.get_subdomain(),'demo-ru')) return readsql_system("simple_interface"); else return 0;
6356
6357 return readsql_system("simple_interface");
6358}
6359
6360function tasklist() // функция генерирует и сохраняет список заданий, которые нужно реализовать на случай крушения системы
6361{
6362 global $TABLE_sup_projects, $TABLE_sup_files_projects, $TABLE_sup_files, $PUTH_files, $order_status_file, $order_status, $user;
6363
6364 $list_projects = "Последнее обновление: " . humain_date(date('Y-m-d H:i:s')) . "<br /><br />";
6365
6366 $query_dop = '';
6367
6368 $query_dop .= " AND
6369 (
6370 (
6371 `status` IN ('00','10','20','21','22','23','30')
6372 )
6373 OR
6374 (
6375 `status` IN ('40','50') AND `closed` > CURRENT_DATE() - INTERVAL " . TRUST_LIMIT_DAY_MANAGER . " DAY
6376 )
6377 )
6378 AND `id_user_del`=0
6379 AND `visible`!=0
6380 ";
6381
6382
6383 $query0 = "SELECT * FROM `{$TABLE_sup_projects}` WHERE 1 {$query_dop} ";
6384
6385 // сначала выводим с высоким приоритетом проблемные
6386 $query_a[] = "{$query0} AND `priority`='3' AND `status` IN ('21') ORDER BY `deadline` ASC LIMIT 10000";
6387 // сначала выводим с высоким приоритетом проблемные
6388 $query_a[] = "{$query0} AND `priority`='3' AND `status` IN ('22') ORDER BY `deadline` ASC LIMIT 10000";
6389 // сначала выводим с высоким приоритетом в "в процессе"
6390 $query_a[] = "{$query0} AND `priority`='3' AND `status` IN ('20') ORDER BY `deadline` ASC LIMIT 10000";
6391 // сначала выводим с высоким приоритетом в "ждет очереди"
6392 $query_a[] = "{$query0} AND `priority`='3' AND `status` IN ('10') ORDER BY `deadline` ASC LIMIT 10000";
6393 // затем выводим с высоким приоритетом замороженные
6394 $query_a[] = "{$query0} AND `priority`='3' AND `status` IN ('00') ORDER BY `deadline` ASC LIMIT 10000";
6395 // затем выводим с высоким приоритетом выполненные
6396 $query_a[] = "{$query0} AND `priority`='3' AND `status` IN ('23') ORDER BY `deadline` ASC LIMIT 10000";
6397
6398 // потом выводим с низким приоритетом с "нехваткой материала"
6399 $query_a[] = "{$query0} AND `priority`='2' AND `status`='21' ORDER BY `datetime` ASC LIMIT 10000";
6400 // потом выводим с низким приоритетом с "трудностями с выполнением"
6401 $query_a[] = "{$query0} AND `priority`='2' AND `status`='22' ORDER BY `datetime` ASC LIMIT 10000";
6402 // потом выводим с низким приоритетом c "в процессе"
6403 $query_a[] = "{$query0} AND `priority`='2' AND `status`='20' ORDER BY `datetime` ASC LIMIT 10000";
6404 // потом выводим с низким приоритетом в "ждет очереди"
6405 $query_a[] = "{$query0} AND `priority`='2' AND `status`='10' ORDER BY `datetime` ASC LIMIT 10000";
6406 // потом выводим с низким приоритетом замороженные
6407 $query_a[] = "{$query0} AND `priority`='2' AND `status`='00' ORDER BY `datetime` ASC LIMIT 10000";
6408 // потом выводим с низким приоритетом выполненные, упорядочив по убыванию даты выполнения
6409 $query_a[] = "{$query0} AND `priority`='2' AND `status`='23' ORDER BY `made` DESC LIMIT 10000";
6410 // потом выводим с низким приоритетом принятые, упорядочив по убыванию даты принятия
6411 $query_a[] = "{$query0} AND `priority`='2' AND `status`='30' ORDER BY `accepted` DESC LIMIT 10000";
6412 // потом выводим с низким приоритетом закрытые, упорядочив по убыванию даты принятия
6413 $query_a[] = "{$query0} AND `priority`='2' AND `status`='40' ORDER BY `closed` DESC LIMIT 10000";
6414 // потом выводим с низким приоритетом отказные, упорядочив по убыванию даты принятия
6415 $query_a[] = "{$query0} AND `priority`='2' AND `status`='50' ORDER BY `closed` DESC LIMIT 10000";
6416
6417 // объеднияем все эти запросы в один
6418 $query = "(" . implode(") UNION (", $query_a) . ")";
6419
6420 $result = mysql_query($query) or die(errorDiv(mysql_error()));
6421 $count = mysql_num_rows($result);
6422
6423 # ФОРМИРУЕМ ЛЕНТУ
6424 if ($count) {
6425 for ($i = 0; $i < $count; $i++) {
6426 $subj = mysql_fetch_array($result);
6427
6428 $id_projects = $subj['id'];
6429 $datetime_projects = $subj['datetime'];
6430
6431 $name_projects = $subj['name'];
6432 $content_projects = $subj['content'];
6433 $deadline_projects = $subj['deadline'];
6434 $priority_projects = $subj['priority'];
6435 $id_user_projects = $subj['id_user'];
6436 $id_user_manager_projects = $subj['id_user_manager'];
6437 $total_price_projects = $subj['total_price'];
6438 $ready_projects = $subj['ready'];
6439 //$remuneration_operator_projects=$subj['remuneration_operator'];
6440 //$remuneration_operator_approve_projects=$subj['remuneration_operator_approve'];
6441 $remuneration_manager_projects = $subj['remuneration_manager'];
6442 $remuneration_manager_approve_projects = $subj['remuneration_manager_approve'];
6443 $material_projects = $subj['material'];
6444 $place_projects = $subj['place'];
6445 //$start_projects=$subj['start'];
6446 //$duration_projects=$subj['duration'];
6447 $made_projects = $subj['made'];
6448 $accepted_projects = $subj['accepted'];
6449 $closed_projects = $subj['closed'];
6450 $visible_projects = $subj['visible'];
6451 //$visible_client_projects=$subj['visible_client'];
6452 //$start_client_projects=$subj['start_client'];
6453 $status_projects = $subj['status'];
6454 $comment_projects = $subj['comment'];
6455 $tn_projects = $subj['tn'];
6456 $delivery_projects = $subj['delivery'];
6457 $deadline_delivery_projects = $subj['delivery_deadline'];
6458 $paid_projects = paid($id_projects);
6459
6460 // вносим поправку на положительность остатока оплаты $paid_projects, чтобы "сливные" проекты, куда менеджеры сваливают оплату мелких заказов не перетягивали на себя общую задолженность клиентов - ???
6461 // if(in_array($status_projects,array(23,30))&&$visible_projects) $rest_payment_ready+=$total_price_projects-$paid_projects; // записываем остаток общей оплаты всех клиентов за готовые проекты (статус "23 - Выполнен" и "30 - Принят, ждем клиента")
6462 // if(in_array($status_projects,array('00',10,20,21,22))&&$visible_projects) $rest_payment_not_ready+=$total_price_projects-$paid_projects; // записываем остаток общей оплаты всех клиентов за пока не готовые проекты (статусы Приостановлен, Ждет очереди, В процессе, Трудности и Нехватка)
6463
6464 // $list_projects.=include_virtual("templates/projects_one.html");
6465 $list_projects .= "<u>ПРОЕКТ №{$id_projects}:</u> <b>" . get_me_name_project($id_projects) . "</b> (" . get_me_name_user_by_id_user($id_user_projects) . " -> " . get_me_name_user_by_id_user($id_user_manager_projects) . "), <i>" . $order_status[$status_projects] . "</i> {$ready_projects}%, ";
6466 if ($paid_projects >= $total_price_projects) {
6467 $list_projects .= "ОПЛАЧЕНО";
6468 }
6469 elseif ($paid_projects < $total_price_projects && $paid_projects) {
6470 $list_projects .= "ОПЛАЧЕНО ЧАСТИЧНО: {$paid_projects} / {$total_price_projects} руб.";
6471 }
6472 elseif (!$paid_projects) {
6473 $list_projects .= "НЕ ОПЛАЧЕНО: {$total_price_projects} руб.";
6474 }
6475 $list_projects .= "<br />";
6476 $list_projects .= "Дедлайн: " . trim(humain_date($deadline_projects));
6477 if ($content_projects) {
6478 $list_projects .= ". Описание: \"{$content_projects}\"";
6479 }
6480 $list_projects .= "<br />";
6481 if (trim($delivery_projects)) {
6482 $list_projects .= "Доставка: \"{$delivery_projects}\" до " . trim(humain_date($deadline_delivery_projects)) . ", ТН: \"{$tn_projects}\"<br />";
6483 }
6484 $list_projects .= "<br />";
6485 $list_projects .= "<u>МАКЕТЫ:</u><br />";
6486
6487 $query00 = "SELECT * FROM `{$TABLE_sup_files_projects}`,`{$TABLE_sup_files}` WHERE `{$TABLE_sup_files_projects}`.`id_project`='{$id_projects}' AND `{$TABLE_sup_files_projects}`.`id_file`=`{$TABLE_sup_files}`.`id` ";
6488 $result00 = mysql_query($query00) or die(errorDiv(mysql_error()));
6489 $count00 = mysql_num_rows($result00);
6490 if ($count00) {
6491 for ($i00 = 1; $i00 <= $count00; $i00++) {
6492 $subj00 = mysql_fetch_array($result00);
6493 $list_projects .= "{$i00}. ";
6494 if (trim($subj00['file_dxf'])) {
6495 $list_projects .= "\"<a href='https://{$_SERVER['HTTP_HOST']}/{$PUTH_files}{$subj00['file_dxf']}'>" . upper_premier_char($subj00['titlefile']) . "</a>\"";
6496 }
6497 else {
6498 $list_projects .= "\"<u>" . upper_premier_char($subj00['titlefile']) . "</u>\"";
6499 }
6500 $list_projects .= " из \"" . get_me_name_label($subj00['id_label']) . "\", <i>" . $order_status_file[$subj00['status']] . "</i>: {$subj00['ready']}/{$subj00['count']} шт., Исполнитель: " . get_me_name_user_by_id_user($subj00['id_user_operator']) . ($subj00['id_equipment'] ? ", назначен на " . get_me_name_equipment_by_id_equipment($subj00['id_equipment']) : '');
6501 $list_projects .= ", Ш*В: {$subj00['width']}*{$subj00['height']} мм.";
6502 $list_projects .= "<br />";
6503
6504 // $id_files_projects[$subj00[id_file]]=$subj0['id'];
6505 //$ready_files_projects[$subj00[id_file]]=$subj0['ready'];
6506 // $id_user_operator_files_projects[$subj00[id_file]]=$subj0['id_user_operator']; // записываем id как ключ и требуемое количество как значение
6507 // $status_files_projects[$subj00[id_file]]=$subj0[status]; // статус файла
6508 // $accepted_files_projects[$subj00[id_file]]=$subj0[accepted]; // статус файла
6509 //$made_files_projects[$subj00[id_file]]=$subj0[made]; // статус файла
6510 //$porn_files_projects[$subj00[id_file]]=$subj0['porn']; // статус файла
6511 //$id_equipment_now_files_projects[$subj00['id_file']]=$subj0['id_equipment']; // станок для файла в этом проекте
6512 }
6513 }
6514
6515 $list_projects .= "<hr />";
6516 }
6517
6518 }
6519
6520 // file_put_contents('tasklist.html',$list_projects);
6521
6522 // echo $list_projects;
6523
6524 file_put_contents('tasklists/' . $user['license'] . '-' . substr($user['salt'], 0, 4) . '.html', $list_projects);
6525}
6526
6527function legend($legend) {
6528 if (!trim($legend)) {
6529 return '';
6530 }
6531
6532 $legend_a = explode('##', $legend); // бьем на строки
6533 $ret = '';
6534
6535 for ($i = 0; $i < count($legend_a) - 1; $i++) // пробегаемся по каждой строке. Вычитаем 1 потому что в конце строки всегда стоит еще один ненужный разделитель ##
6536 {
6537 list($color, $work) = explode('#', $legend_a[$i]); // бьем строку на цвет и вид обработки
6538
6539 if ($color == '99999999') {
6540 $color_hex = 'контур не задан';
6541 $bg = "url('/images/nobg.jpg')";
6542 }
6543 else // переводим в hex
6544 {
6545 $r = dechex($color % 256);
6546 if (strlen($r) == 1) {
6547 $r = "{$r}0";
6548 }
6549
6550 $g = dechex(($color / 256) % 256);
6551 if (strlen($g) == 1) {
6552 $g = "{$g}0";
6553 }
6554
6555 $b = dechex(($color / 256 / 256) % 256);
6556 if (strlen($b) == 1) {
6557 $b = "{$b}0";
6558 }
6559
6560 $color_hex = '#' . $r . $g . $b;
6561 $bg = $color_hex;
6562 }
6563
6564 $ret .= "<div><nobr><img src='/images/0.gif' style=\"border:1px #666 solid;width:15px;height:15px;background:{$bg};\" title='{$color_hex}' /> {$work}</nobr></div>";
6565 }
6566 return $ret;
6567}
6568
6569function legend_price($legend) {
6570 $ret = 'нет сведений';
6571
6572 if (!trim($legend)) {
6573 return $ret;
6574 }
6575
6576 $prices = array_pop(explode('##', $legend)); // бьем на строки
6577
6578 if (!trim($prices)) {
6579 return $ret;
6580 }
6581
6582 $ret = str_replace('#', " руб.; ", $prices);
6583 return $ret;
6584}
6585
6586
6587function get_child_magazin($id) {
6588 $ret = '';
6589 // Здесь выводим подразделы для этого раздела
6590 $q = "SELECT * FROM `{$GLOBALS['TABLE_sup_users']}` WHERE `id_user_del`='0' AND `type`='5' AND `name`!='' AND `patronymic`!='' AND `email`!='' AND `parent_id`='{$id}' AND `not_use_for_magazin`='0' ORDER BY `surname` ASC, `name` ASC;";
6591 $result = mysql_query($q) or die(errorDiv(mysql_error()));
6592 $count = mysql_num_rows($result);
6593
6594 # ФОРМИРУЕМ ЛЕНТУ
6595 if ($count) {
6596 for ($i = 0; $i < $count; $i++) {
6597 $subj = mysql_fetch_array($result);
6598
6599
6600 $strong = ($GLOBALS['login'] == decode_db($subj['email']) ? "class='strong'" : '');
6601 $ret .= "<div class=\"small\">" . '-' . ' ' . "<a href=\"/internet-magazin/" . decode_db($subj['email']) . ".html\" {$strong}>" . $subj['name'] . "</a></div>";
6602 $ret .= get_child_magazin2($subj['id']);
6603 }
6604 }
6605
6606 return $ret;
6607}
6608
6609function get_child_magazin2($id) {
6610 $ret = '';
6611 // Здесь выводим подразделы для этого раздела
6612 $q = "SELECT * FROM `{$GLOBALS['TABLE_sup_users']}` WHERE `id_user_del`='0' AND `type`='5' AND `name`!='' AND `patronymic`!='' AND `email`!='' AND `parent_id`='{$id}' AND `not_use_for_magazin`='0' ORDER BY `surname` ASC, `name` ASC;";
6613 $result = mysql_query($q) or die(errorDiv(mysql_error()));
6614 $count = mysql_num_rows($result);
6615
6616 # ФОРМИРУЕМ ЛЕНТУ
6617 if ($count) {
6618 for ($i = 0; $i < $count; $i++) {
6619 $subj = mysql_fetch_array($result);
6620
6621
6622 $strong = ($GLOBALS['login'] == decode_db($subj['email']) ? "class='strong'" : '');
6623 $ret .= "<div class=\"small\">" . '--' . ' ' . "<a href=\"/internet-magazin/" . decode_db($subj['email']) . ".html\" {$strong}>" . $subj['name'] . "</a></div>";
6624 $ret .= get_child_magazin3($subj['id']);
6625 }
6626 }
6627
6628 return $ret;
6629}
6630
6631function get_child_magazin3($id) {
6632 $ret = '';
6633 // Здесь выводим подразделы для этого раздела
6634 $q = "SELECT * FROM `{$GLOBALS['TABLE_sup_users']}` WHERE `id_user_del`='0' AND `type`='5' AND `name`!='' AND `patronymic`!='' AND `email`!='' AND `parent_id`='{$id}' AND `not_use_for_magazin`='0' ORDER BY `surname` ASC, `name` ASC;";
6635 $result = mysql_query($q) or die(errorDiv(mysql_error()));
6636 $count = mysql_num_rows($result);
6637
6638 # ФОРМИРУЕМ ЛЕНТУ
6639 if ($count) {
6640 for ($i = 0; $i < $count; $i++) {
6641 $subj = mysql_fetch_array($result);
6642
6643
6644 $strong = ($GLOBALS['login'] == decode_db($subj['email']) ? "class='strong'" : '');
6645 $ret .= "<div class=\"small\">" . '---' . ' ' . "<a href=\"/internet-magazin/" . decode_db($subj['email']) . ".html\" {$strong}>" . $subj['name'] . "</a></div>";
6646 //$ret.=get_child_magazin3($subj['id']);
6647 }
6648 }
6649
6650 return $ret;
6651}
6652
6653
6654function get_me_list_filters() // получаем список возможных ярлыков и тегов к ним
6655{
6656 $ret = array();
6657
6658 // Создаем таблицу, если ее нет.
6659 $create_table = "CREATE TABLE IF NOT EXISTS `{$GLOBALS['TABLE_sup_filters']}` (`id` int(11) NOT NULL AUTO_INCREMENT,`name` varchar(256) NOT NULL,`color` int(11) NOT NULL,`tags` text NOT NULL,`position` enum('0','1') NOT NULL,`last_update` datetime NOT NULL,`id_user_del` int(11) NOT NULL,`datetime_del` datetime NOT NULL,PRIMARY KEY (`id`),UNIQUE KEY `name` (`name`,`datetime_del`), KEY `datetime_del` (`datetime_del`), KEY `position` (`position`)) ENGINE=INNODB DEFAULT CHARSET=utf8;";
6660
6661 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_filters']}` WHERE 1 AND `position`='1' AND `id_user_del`='0' ORDER BY `name` ASC;") or die(mysql_query($create_table) or die(errorDiv(mysql_error())));
6662 $count = mysql_num_rows($result);
6663
6664 if ($count) {
6665 for ($i = 0; $i < $count; $i++) {
6666 $a = mysql_fetch_array($result);
6667 $ret[$a['name']] = explode("\r\n", $a['tags']);
6668 }
6669 }
6670
6671 return $ret;
6672}
6673
6674function get_me_color_filter_by_name_filter($name) {
6675
6676 $result = mysql_query("SELECT * FROM `{$GLOBALS['TABLE_sup_filters']}` WHERE `name`='{$name}' AND `position`='1' AND `id_user_del`='0' LIMIT 1;") or die(errorDiv(mysql_error()));
6677 $count = mysql_num_rows($result);
6678
6679 if ($count) {
6680 $a = mysql_fetch_array($result);
6681 $ret = $a['color'];
6682 }
6683
6684 return $ret;
6685}