bash_sync_perms.php 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504
  1. <?php
  2. //author Arkadiusz Binder 2013-07-30
  3. //todo do przepisania na PHP i dodania opcji generowania Symlinkow
  4. //todo @2013-08-04 do skonczenia funkcja
  5. //if(file_exists(".config.php")) require_once(".config.php");
  6. /**
  7. * by plabudda 2013-10-09:
  8. *
  9. * 1. install:
  10. * - create *.plist file:
  11. * # php /Library/Server/Web/Data/Sites/Default/SE/se-dev-pl/bash_sync_perms.php biuro.biall-net.pl addToLaunchctl
  12. * # php /Library/Server/Web/Data/Sites/Default/SE/bash_sync_perms.php biuro.medical-opakowania.pl addToLaunchctl
  13. * - load by launchctl:
  14. * # launchctl load /Library/LaunchDaemons/pl.biallnet.sync_perms.php.plist
  15. *
  16. * 2. uninstall:
  17. * - unload from launchctl:
  18. * # launchctl unload /Library/LaunchDaemons/pl.biallnet.sync_perms.php.plist
  19. *
  20. * 3. debug:
  21. * - debug by www:
  22. * /SE/se-dev-pl/bash_sync_perms.php?DBG=1
  23. * - more verbose debug:
  24. * /SE/se-dev-pl/bash_sync_perms.php?DBG=6
  25. * - task:
  26. * /SE/se-dev-pl/bash_sync_perms.php?task=task
  27. * /SE/se-dev-pl/bash_sync_perms.php?task=newFiles
  28. * /SE/se-dev-pl/bash_sync_perms.php?task=testParse
  29. * /SE/se-dev-pl/bash_sync_perms.php?task=task&PROJ_ID={projID} -- force update project
  30. *
  31. *
  32. * 4. Sync users: `ADMIN_USERS`.`A_STATUS`
  33. * 'WAITING' - Kandydaci
  34. * 'NORMAL' - Aktywni pracownicy
  35. * 'DELETED' - Wy‘?Ž?czone konta
  36. * 'OFF_SOFT' - ?
  37. * 'OFF_HARD' - ?
  38. *
  39. * @2014-01 recomended by A.Binder migration to separate dirs of koresp scripts:
  40. * robienie katalogow dla korespondencji przy migracji na nowy typ pism
  41. #read PASSWORD
  42. #for a in `echo "select concat(ID,';---;',K_OD_KOGO,K_ZAWARTOS) from IN7_DZIENNIK_KORESP" |mysql -p$PASSWORD -uroot -Damssystem -h127.0.0.1 | sed 's/[^a-zA-Z0-9;-]/_/g' |sed 's/;---;/\./g' ` ;
  43. #do
  44. #echo mkdir $a
  45. #mkdir $a
  46. #done
  47. *do wywolania w katalogach IN/OUT:
  48. # cd IN
  49. # for a in `ls |awk -F'.' '{ print $1 }' ` ; do mv $a.* ../$a.*; done
  50. *
  51. *
  52. *
  53. * DONE: koresp format: PISMA/ID/...
  54. * DONE: projekty -> koresp hardlink PROJEKTY/ID..../_PISMA/{HL:pismo.pdf}
  55. * TODO: PROJEKTY/ID..../_PISMA/ permy tylko read/listing
  56. * TODO: hardlink druki: mkdir DRUKI/ID.{DESC}/_PROJEKT/{proj_folder}/{HL:pliki z proj bez podkatalogƈw}
  57. * TODO: DRUKI/ID.{DESC}/_PROJEKT/{proj_folder} permy tylko read/listing
  58. * -- TODO: DRUKI/ID.{DESC}/ - permy z bazy danych A_ADM_COMPANY, A_CLASSIFIED
  59. *
  60. *
  61. * DONE: Trigger po update/insert Koresp po aktualizacji permƈw plikƈw projektu
  62. */
  63. ini_set('max_execution_time', 300);
  64. ini_set('memory_limit', '512M');
  65. define('DS', DIRECTORY_SEPARATOR);
  66. define('APP_PATH_ROOT', dirname(__FILE__));
  67. define('APP_PATH_WWW', dirname(__FILE__));
  68. define('APP_PATH_CONFIG', APP_PATH_ROOT . DS . 'config');
  69. // set ini to log errors into error log file
  70. ini_set('display_startup_errors', '0');
  71. ini_set('log_errors', '1');
  72. ini_set('error_log', '/var/log/apache2/error_log');// TODO: php.ini ?
  73. require_once APP_PATH_ROOT . DS . 'se-lib' . DS . 'Lib.php';
  74. Lib::loadClass('V');
  75. Lib::loadClass('Config');
  76. Lib::loadClass('DB');
  77. Lib::loadClass('User');
  78. Lib::loadClass('FoldersConfig');
  79. Lib::loadClass('FileUploader');
  80. if (isset($_SERVER["argv"][1])) {
  81. $_SERVER['SERVER_NAME'] = $_SERVER["argv"][1];
  82. }
  83. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'info') {
  84. $info = array();
  85. $info['max_execution_time'] = ini_get('max_execution_time');
  86. $info['memory_limit'] = ini_get('memory_limit');
  87. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">info (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($info);echo'</pre>';
  88. ini_set('max_execution_time', 300);
  89. ini_set('memory_limit', '512M');
  90. $info = array();
  91. $info['max_execution_time'] = ini_get('max_execution_time');
  92. $info['memory_limit'] = ini_get('memory_limit');
  93. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">info (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($info);echo'</pre>';
  94. }
  95. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'users') {
  96. SyncPerms::run(null, null, 'users', null);
  97. }
  98. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'usersAll') {
  99. SyncPerms::run(null, null, 'usersAll', null);
  100. }
  101. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'task') {
  102. SyncPerms::run(null, null, 'nextTask', null);
  103. }
  104. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'newFiles') {
  105. SyncPerms::run(null, null, 'newFiles', null);
  106. }
  107. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'testParse') {
  108. $cmd = " ls -Rlea . ";
  109. //exec("cd \"/Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY/1970.Rekrutacja_z_dnia_2013-02-22_na_stanowisko_Specjalista_ds_pozyskiwania_klientow/6/\"; {$cmd} ", $filesWithPerms);
  110. //exec("cd \"/Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY/1983.Rekrutacja_z_dnia_2013-03-12_na_stanowisko_Przedstawiciel_Handlowy_(D2D)/24/\"; {$cmd} ", $filesWithPerms);
  111. //exec("cd '/Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY/816.2012-01-01.INNE.Siec_Szerokopasmowa_w_ramach_dofinansowania_unii_dla_woj_pomorskiego__Sprint/2013-06-14.Dokumenty_do_wysylki_po_wysylce_usunac!_AB_co_to_za_katlog_TODO/Zalacznik 1 Studium wykonalnosci/'; {$cmd} ", $filesWithPerms);
  112. exec("cd '/Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY/1657.Rekrutacja_z_dnia_2012-06_25_na_stanowisko_Przedstawiciel_Handlowy/1/'; {$cmd} ", $filesWithPerms);
  113. //$line = "-rwxrwx---+ 1 _www workgroup 212367 Feb 25 2013 Cv Malwina Szczepaniec.docx";
  114. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPerms);echo'</pre>';
  115. $filesWithPermsTree = array();
  116. $lastName = '';
  117. $folderParent = '';
  118. foreach ($filesWithPerms as $line) {
  119. if (substr($line, 0, 1) == '-' || substr($line, 0, 1) == 'd') {// file name
  120. $fileParts = array();
  121. $filePartsArr = explode(' ', $line);
  122. $lastInd = 0;
  123. foreach ($filePartsArr as $vPart) {
  124. if ($lastInd > 7) {// file name
  125. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  126. $lastInd++;
  127. }
  128. else if (!empty($vPart) || $vPart === '0') {
  129. $fileParts[] = $vPart;
  130. $lastInd++;
  131. }
  132. }
  133. if (end($fileParts) == '..' || (end($fileParts) == '.' && $folderParent)) {
  134. $lastName = '..';
  135. continue;
  136. }
  137. $file = new stdClass();
  138. if (!isset($fileParts[8])) {
  139. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
  140. //continue;
  141. } else {
  142. // fix file name from bad chars
  143. // [8] => CV_Kowalski Mariusz`.pdf
  144. // "-$Model Bialnet .xlsm" in /Users/plabudda/se-dev-pl/SE/bash_sync_perms.php on line 1518
  145. // [11-Oct-2013 21:00:28 UTC] PHP Notice: Error-cmd: chmod -a# 3 "/Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY/500.2009-12-01.INNE.DOFINANSOWANIE_PROJEKT_KOLBUDY/2013-02-26_harmonogram_EDORADCA_Aktualny/-$harmonogram 01.2013.xlsx" in /Users/plabudda/se-dev-pl/SE/bash_sync_perms.php on line 1518
  146. // [11-Oct-2013 21:00:27 UTC] PHP Notice: Error-cmd: chmod -a# 3 "/Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY/500.2009-12-01.INNE.DOFINANSOWANIE_PROJEKT_KOLBUDY/2012-04-19_oferta_gpon_sprint_po_poprawkach/-$Wycena GPON 2012 Biall-Net_spr v1.xlsx" in /Users/plabudda/se-dev-pl/SE/bash_sync_perms.php on line 1518
  147. // [11-Oct-2013 20:56:25 UTC] PHP Notice: Error-cmd: chmod +a "user:prejsi allow write,append,writeattr,writeextattr,writesecurity,chown,read,execute,readattr,readextattr,readsecurity" "/Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY/1695.Projekt_glowny_dzialu_rozwoju_biznesu_oraz_dystrybucji_informacji/HANDLOWY/HANDLOWY_2012/OTOMIN/-$Otomin.xlsx" in /Users/plabudda/se-dev-pl/SE/bash_sync_perms.php on line 1517
  148. //$fileParts[8] = str_replace('\\', '\\\\', $fileParts[8]);
  149. //$fileParts[8] = str_replace(array('`', '$'), array('\`', '\$'), $fileParts[8]);
  150. }
  151. echo'<pre style="max-height:230px;overflow:auto;border:1px solid red;text-align:left;">line/$fileParts/$filePartsArr (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($line, $fileParts, $filePartsArr));echo'</pre>';
  152. $file->name = end($fileParts);
  153. $file->path = array();
  154. if ($folderParent) $file->path[] = $folderParent;
  155. $file->path[] = end($fileParts);
  156. $file->path = implode('/', $file->path);
  157. //$file->owner = $fileParts[2];
  158. //$file->group = $fileParts[3];
  159. //$file->perms = $fileParts[0];
  160. $file->isDir = (substr($line, 0, 1) == 'd');
  161. $file->permsExt = array();
  162. $filesWithPermsTree[$file->name] = $file;
  163. $lastName = $file;
  164. }
  165. else if (substr($line, 0, 1) == ' ') {// extended perm line
  166. if ($lastName == '..') {
  167. continue;
  168. }
  169. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  170. }
  171. else if (substr($line, 0, 2) == './' && substr($line, -1) == ':') {// folder
  172. $folderParent = substr($line, 2, -1);
  173. }
  174. else if (substr($line, 0, 5) == 'total') {
  175. continue;
  176. }
  177. else if (empty($line)) {
  178. $folderParent = '';
  179. continue;
  180. }
  181. }
  182. echo'<pre style="max-height:400px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPermsTree (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPermsTree);echo'</pre>';
  183. }
  184. else if (empty($_SERVER["argv"]) && V::get('DBG', '', $_GET, 'int') > 0) {
  185. SyncPerms::run(null, null);
  186. }
  187. else {
  188. die("\n The second argument should be server domain - e.g. biuro.kike.pl \n");
  189. }
  190. if (!empty($_SERVER["argv"][0]) && !empty($_SERVER["argv"][1])) {
  191. $arg2 = (!empty($_SERVER["argv"][2]))? $_SERVER["argv"][2] : null;
  192. $arg3 = (!empty($_SERVER["argv"][3]))? $_SERVER["argv"][3] : null;
  193. //bash_perms_make_se($_SERVER["argv"][0], $_SERVER["argv"][1], $arg2, $arg3);
  194. SyncPerms::run($_SERVER["argv"][0], $_SERVER["argv"][1], $arg2, $arg3);
  195. }
  196. //require(APP_PATH_ROOT."/superedit-SEF.php");
  197. class SyncPerms {
  198. public static function installTable() {
  199. $db = DB::getDB();
  200. if (!$db) {
  201. die("DB Error: No DB!");
  202. }
  203. // @due to bug in medical trigger install we now install tables using function SQIX_STRUCTURE_SYNC @2014-01-22
  204. $sql = "
  205. CREATE TABLE IF NOT EXISTS `_SYNC_FILE_PERMS` (
  206. `ID` int(11) NOT NULL AUTO_INCREMENT,
  207. `ID_PROJECT` int(11) NOT NULL,
  208. `L_APPOITMENT_USER` varchar(64) DEFAULT '',
  209. `A_ADM_COMPANY` varchar(64) NOT NULL DEFAULT '',
  210. `A_CLASSIFIED` varchar(64) NOT NULL DEFAULT '',
  211. `PARENT_L_APPOITMENT_USER` varchar(64) NOT NULL DEFAULT '',
  212. `A_LAST_SYNC` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  213. `A_SYNCHRONIZED` tinyint(4) NOT NULL DEFAULT '0',
  214. `A_SYNC_RESULT` varchar(255) NOT NULL DEFAULT '',
  215. PRIMARY KEY (`ID`),
  216. UNIQUE KEY `ID_PROJECT` (`ID_PROJECT`)
  217. ) ENGINE=MyISAM DEFAULT CHARSET=latin2 ;
  218. ";
  219. $db->query($sql);
  220. $sql = " DROP TRIGGER IF EXISTS `KORESP_change_ID_PROJECT`; ";
  221. $db->query($sql);
  222. $sql = "
  223. CREATE TRIGGER `KORESP_change_ID_PROJECT` AFTER UPDATE ON `IN7_DZIENNIK_KORESP`
  224. FOR EACH ROW BEGIN
  225. IF (NEW.`ID_PROJECT` != OLD.`ID_PROJECT` and NEW.`ID_PROJECT` > 0) or OLD.`M_DIST_FILES`!=NEW.`M_DIST_FILES` THEN
  226. update `_SYNC_FILE_PERMS` as s set
  227. s.`A_SYNCHRONIZED`=0
  228. where
  229. s.`ID_PROJECT`=NEW.`ID_PROJECT`
  230. or s.`ID_PROJECT`=OLD.`ID_PROJECT`;
  231. END IF;
  232. END
  233. ";
  234. $db->query($sql);
  235. $sql = " DROP TRIGGER IF EXISTS `KORESP_add_ID_PROJECT`; ";
  236. $db->query($sql);
  237. $sql = "
  238. CREATE TRIGGER `KORESP_add_ID_PROJECT` AFTER INSERT ON `IN7_DZIENNIK_KORESP`
  239. FOR EACH ROW BEGIN
  240. IF NEW.`ID_PROJECT` > 0 THEN
  241. update `_SYNC_FILE_PERMS` as s set
  242. s.`A_SYNCHRONIZED`=0
  243. where
  244. s.`ID_PROJECT`=NEW.`ID_PROJECT`;
  245. END IF;
  246. END
  247. ";
  248. $db->query($sql);
  249. if (V::get('DBG', '', $_GET, 'int') > 0) {
  250. if ($db->has_errors()) {
  251. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">DB errors (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($db->get_errors());echo'</pre>';
  252. }
  253. }
  254. }
  255. public static function run($script_name, $domain, $arg2 = null, $arg3 = null) {
  256. if ($arg2 == 'addToLaunchctl') {
  257. system("echo \"<?xml version=\"1.0\" encoding=\"UTF-8\"?>
  258. <!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">
  259. <plist version=\"1.0\">
  260. <dict>
  261. <key>Disabled</key>
  262. <false/>
  263. <key>Label</key>
  264. <string>pl.biallnet.sync_perms.php</string>
  265. <key>UserName</key>
  266. <string>root</string>
  267. <key>ProgramArguments</key>
  268. <array>
  269. <string>php</string>
  270. <string>{$_SERVER["argv"][0]}</string>
  271. <string>{$_SERVER["argv"][1]}</string>
  272. </array>
  273. <key>StartInterval</key>
  274. <integer>60</integer>
  275. </dict>
  276. </plist>
  277. \" > /Library/LaunchDaemons/pl.biallnet.sync_perms.php.plist");
  278. echo "Run By Root: launchctl load /Library/LaunchDaemons/pl.biallnet.sync_perms.php.plist\n";
  279. }
  280. else if ($arg2 == 'newFiles') {
  281. $time = new stdClass();
  282. $time->start = time();
  283. self::newFilesAction();
  284. $time->end = time();
  285. // TODO: print operation time if DBG
  286. }
  287. else if ($arg2 == 'nextTask') {
  288. $time = new stdClass();
  289. $time->start = time();
  290. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">nextTask</pre>';}
  291. self::installTable();
  292. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">installTable DONE</pre>';}
  293. self::generateTasksNewRecords();
  294. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">generateTasksNewRecords DONE</pre>';}
  295. self::generateTasksUpdated();
  296. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">generateTasksUpdated DONE</pre>';}
  297. $limit = V::get('_limit', 1, $_GET, 'int');
  298. for ($i = 0; $i < $limit; $i++) {
  299. $time->cur = time();
  300. if ($time->cur - $time->start > 60 * 5) {
  301. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">Force-break time('.($time->cur - $time->start).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';echo'</pre>';}
  302. break;
  303. }
  304. $task = self::nextTaskAction();
  305. if (!$task) {
  306. break;
  307. }
  308. }
  309. }
  310. else if ($arg2 == 'testErrorLog') {
  311. echo "display_errors: " . ini_get("display_errors") . "\n";
  312. echo "display_startup_errors: " . ini_get("display_startup_errors") . "\n";
  313. echo "log_errors: " . ini_get("log_errors") . "\n";
  314. echo "error_reporting: " . ini_get("error_reporting") . "\n";
  315. echo "error_log: " . ini_get("error_log") . "\n";
  316. trigger_error("Notice: Test Error Log", E_USER_NOTICE);
  317. }
  318. else if ($arg2 == 'users') {
  319. self::usersAction();
  320. }
  321. else if ($arg2 == 'usersAll') {
  322. self::usersAllAction();
  323. }
  324. else {
  325. $DBG_MEMORY = false;
  326. $time = new stdClass();
  327. $time->start = time();
  328. self::installTable();
  329. self::generateTasksNewRecords();
  330. if($DBG_MEMORY)trigger_error("DBG:mem usage after-generateTasksNewRecords " . memory_get_usage(true) . ".", E_USER_NOTICE);
  331. self::generateTasksUpdated();
  332. if($DBG_MEMORY)trigger_error("DBG:mem usage after-generateTasksUpdated " . memory_get_usage(true) . ".", E_USER_NOTICE);
  333. $time->cur = time();
  334. if ($time->cur - $time->start > 60 * 5) {
  335. trigger_error("Error: time end after-init " . ($time->cur - $time->start) . " !", E_USER_NOTICE);
  336. return;
  337. }
  338. self::newFilesAction();
  339. if($DBG_MEMORY)trigger_error("DBG:mem usage after-newFilesAction " . memory_get_usage(true) . ".", E_USER_NOTICE);
  340. $limit = 100;
  341. for ($i = 0; $i < $limit; $i++) {
  342. $time->cur = time();
  343. if ($time->cur - $time->start > 60 * 5) {
  344. trigger_error("Error: time end after-nextTaskAction(loop:{$i}) " . ($time->cur - $time->start) . " !", E_USER_NOTICE);
  345. return;
  346. }
  347. $task = self::nextTaskAction();
  348. if($DBG_MEMORY)trigger_error("DBG:mem usage after-nextTaskAction (loop:{$i}) " . memory_get_usage(true) . ".", E_USER_NOTICE);
  349. if (!$task) {
  350. $time->cur = time();
  351. trigger_error("Notice: sync end OK no-task " . ($time->cur - $time->start) . "", E_USER_WARNING);
  352. return;
  353. }
  354. }
  355. $time->cur = time();
  356. trigger_error("Notice: sync end OK " . ($time->cur - $time->start) . " !", E_USER_NOTICE);
  357. }
  358. }
  359. public static function newFilesAction() {
  360. $task = self::getTaskNewFiles();
  361. $taskResult = self::fixLastModifiedFiles($task);
  362. self::saveTask(-1);
  363. }
  364. public static function nextTaskAction() {
  365. $task = self::getTask();
  366. if (!$task) {
  367. return false;
  368. }
  369. self::executeTask($task);
  370. /*
  371. if (isset($task->A_SYNC_RESULT->total)
  372. && isset($task->A_SYNC_RESULT->lastDone)
  373. && $task->A_SYNC_RESULT->lastDone < $task->A_SYNC_RESULT->total
  374. ) {
  375. self::saveTask($task->ID_PROJECT, 0, $task->A_SYNC_RESULT);
  376. } else {
  377. self::saveTask($task->ID_PROJECT);
  378. }
  379. */
  380. self::saveTask($task->ID_PROJECT);
  381. return $task;
  382. }
  383. public static function generateTasksUpdated() {
  384. $db = DB::getDB();
  385. if (!$db) {
  386. die("DB Error: No DB!");
  387. }
  388. $sqlTest = "select p.ID, p.`L_APPOITMENT_USER`, p.`A_ADM_COMPANY`, p.`A_CLASSIFIED`, s. *
  389. from `_SYNC_FILE_PERMS` as s, `IN7_MK_BAZA_DYSTRYBUCJI` as p, `IN7_MK_BAZA_DYSTRYBUCJI` as pp
  390. where
  391. s.`ID_PROJECT`=p.`ID` and pp.`ID`=p.`P_ID`
  392. and (
  393. s.`L_APPOITMENT_USER`!=p.`L_APPOITMENT_USER`
  394. or s.`A_ADM_COMPANY`!=p.`A_ADM_COMPANY`
  395. or s.`A_CLASSIFIED`!=p.`A_CLASSIFIED`
  396. or s.`PARENT_L_APPOITMENT_USER`!=pp.`L_APPOITMENT_USER`
  397. )
  398. ";
  399. $sql = "update `_SYNC_FILE_PERMS` as s, `IN7_MK_BAZA_DYSTRYBUCJI` as p, `IN7_MK_BAZA_DYSTRYBUCJI` as pp
  400. set
  401. s.`L_APPOITMENT_USER`=p.`L_APPOITMENT_USER`
  402. , s.`A_ADM_COMPANY`=p.`A_ADM_COMPANY`
  403. , s.`A_CLASSIFIED`=p.`A_CLASSIFIED`
  404. , s.`PARENT_L_APPOITMENT_USER`=pp.`L_APPOITMENT_USER`
  405. , s.`A_SYNCHRONIZED`=0
  406. where
  407. s.`ID_PROJECT`=p.`ID` and pp.`ID`=p.`P_ID`
  408. and (
  409. s.`L_APPOITMENT_USER`!=p.`L_APPOITMENT_USER`
  410. or s.`A_ADM_COMPANY`!=p.`A_ADM_COMPANY`
  411. or s.`A_CLASSIFIED`!=p.`A_CLASSIFIED`
  412. or s.`PARENT_L_APPOITMENT_USER`!=pp.`L_APPOITMENT_USER`
  413. )
  414. ";
  415. $res = $db->query($sql);
  416. }
  417. public static function generateTasksNewRecords() {
  418. $db = DB::getDB();
  419. if (!$db) {
  420. die("DB Error: No DB!");
  421. }
  422. $sql = "insert ignore into `_SYNC_FILE_PERMS` (`ID_PROJECT`, `L_APPOITMENT_USER`, `A_ADM_COMPANY`, `A_CLASSIFIED`, `PARENT_L_APPOITMENT_USER`)
  423. values (-1, '', '', '', '');
  424. ";
  425. $res = $db->query($sql);
  426. $sql = "insert ignore into `_SYNC_FILE_PERMS` (`ID_PROJECT`, `L_APPOITMENT_USER`, `A_ADM_COMPANY`, `A_CLASSIFIED`, `PARENT_L_APPOITMENT_USER`)
  427. select p.`ID`, p.`L_APPOITMENT_USER`, p.`A_ADM_COMPANY`, p.`A_CLASSIFIED`, pp.`L_APPOITMENT_USER`
  428. from `IN7_MK_BAZA_DYSTRYBUCJI` as p
  429. left join `IN7_MK_BAZA_DYSTRYBUCJI` as pp on (pp.`ID`=p.`P_ID`)
  430. where p.`A_STATUS`!='DELETED'
  431. ";
  432. $res = $db->query($sql);
  433. }
  434. /**
  435. * Znajd‘­ najstarszy aktualizowany projekt.
  436. */
  437. public static function getTask() {
  438. $task = null;
  439. $db = DB::getDB();
  440. if (!$db) {
  441. die("DB Error: No DB!");
  442. }
  443. $sqlWhereProjID = " s.`A_SYNCHRONIZED`=0 ";
  444. if (($projID = V::get('PROJ_ID', '', $_GET, 'int')) > 0){
  445. $sqlWhereProjID = " s.`ID_PROJECT`='{$projID}' ";
  446. }
  447. $sql = "select s.*
  448. , p.`L_APPOITMENT_USER` as p__L_APPOITMENT_USER
  449. , p.`A_ADM_COMPANY` as p__A_ADM_COMPANY
  450. , p.`A_CLASSIFIED` as p__A_CLASSIFIED
  451. , pp.`L_APPOITMENT_USER` as p__PARENT_L_APPOITMENT_USER
  452. , p.`M_DIST_DESC` as p__M_DIST_DESC
  453. , p.`M_DISTRIBUTOR` as p__M_DISTRIBUTOR
  454. , p.`CRM_LISTA_ZASOBOW_ID` as p__CRM_LISTA_ZASOBOW_ID
  455. from `_SYNC_FILE_PERMS` as s
  456. left join `IN7_MK_BAZA_DYSTRYBUCJI` as p on(p.`ID`=s.`ID_PROJECT`)
  457. left join `IN7_MK_BAZA_DYSTRYBUCJI` as pp on(pp.`ID`=p.`P_ID`)
  458. where
  459. {$sqlWhereProjID}
  460. order by s.`A_LAST_SYNC` asc, s.`ID` asc
  461. limit 1
  462. ";
  463. $res = $db->query($sql);
  464. if ($r = $db->fetch($res)) {
  465. $r->A_SYNC_RESULT = (!$r->A_SYNC_RESULT)? new stdClass() : json_decode($r->A_SYNC_RESULT);
  466. $task = $r;
  467. }
  468. return $task;
  469. }
  470. public static function getTaskNewerUsers() {
  471. $task = null;
  472. $db = DB::getDB();
  473. if (!$db) {
  474. die("DB Error: No DB!");
  475. }
  476. $sql = "select s.*
  477. from `_SYNC_FILE_PERMS` as s
  478. where s.`ID_PROJECT`=-2
  479. ";
  480. $res = $db->query($sql);
  481. if ($r = $db->fetch($res)) {
  482. $task = $r;
  483. }
  484. if (!$task) {
  485. $task = new stdClass();
  486. $task->ID_PROJECT = -2;
  487. $task->A_SYNC_RESULT = new stdClass();
  488. $task->A_LAST_SYNC = '';//mktime(date("H"), date("i") - 10, date("s"), date("n"), date("j"), date("Y"));
  489. //$task->A_LAST_SYNC = date("Y-m-d H:i", $task->A_LAST_SYNC);
  490. }
  491. return $task;
  492. }
  493. public static function getTaskNewFiles() {
  494. $task = null;
  495. $db = DB::getDB();
  496. if (!$db) {
  497. die("DB Error: No DB!");
  498. }
  499. $sql = "select s.*
  500. from `_SYNC_FILE_PERMS` as s
  501. where s.`ID_PROJECT`=-1
  502. ";
  503. $res = $db->query($sql);
  504. if ($r = $db->fetch($res)) {
  505. $task = $r;
  506. }
  507. if (!$task) {
  508. $task = new stdClass();
  509. $task->ID_PROJECT = -1;
  510. $task->A_SYNC_RESULT = new stdClass();
  511. $task->A_LAST_SYNC = mktime(date("H"), date("i") - 10, date("s"), date("n"), date("j"), date("Y"));
  512. $task->A_LAST_SYNC = date("Y-m-d H:i", $task->A_LAST_SYNC);
  513. }
  514. return $task;
  515. }
  516. public static function saveTask($idProject, $taskDone = 1, $result = null) {
  517. $task = null;
  518. $db = DB::getDB();
  519. if (!$db) {
  520. die("DB Error: No DB!");
  521. }
  522. $sqlResult = '';
  523. if ($result) {
  524. $resultJson = json_encode($result);
  525. $resultJson = $db->_($resultJson);
  526. $sqlResult .= " , s.`A_SYNC_RESULT`='{$resultJson}' ";
  527. }
  528. $sql = "update `_SYNC_FILE_PERMS` as s
  529. set
  530. s.`A_LAST_SYNC`=NOW()
  531. , s.`A_SYNCHRONIZED`={$taskDone}
  532. {$sqlResult}
  533. where s.`ID_PROJECT`={$idProject}
  534. ";
  535. $res = $db->query($sql);
  536. return $task;
  537. }
  538. public static function executeTask(&$task) {
  539. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">executeTask (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($task);echo'</pre>';}
  540. $confTblName = 'IN7_MK_BAZA_DYSTRYBUCJI_COLUMN';
  541. $PROJ_mount_point = FoldersConfig::get($confTblName, 'mount_point');
  542. $project = new stdClass();
  543. $project->ID = $task->ID_PROJECT;
  544. $project->L_APPOITMENT_USER = $task->p__L_APPOITMENT_USER;
  545. $project->A_ADM_COMPANY = $task->p__A_ADM_COMPANY;
  546. $project->A_CLASSIFIED = $task->p__A_CLASSIFIED;
  547. $project->PARENT_L_APPOITMENT_USER = $task->p__PARENT_L_APPOITMENT_USER;
  548. $project->M_DIST_DESC = $task->p__M_DIST_DESC;
  549. $project->M_DISTRIBUTOR = $task->p__M_DISTRIBUTOR;
  550. $project->CRM_LISTA_ZASOBOW_ID = $task->p__CRM_LISTA_ZASOBOW_ID;
  551. $folderConf = FoldersConfig::getAll($confTblName);
  552. $uploader = new FileUploader($confTblName, $project);
  553. $errMsg = '';
  554. if (!$uploader->setConfig($folderConf, $errMsg)) {
  555. trigger_error("Error: folders config!", E_USER_NOTICE);
  556. die("Error: folders config!");
  557. }
  558. $uploader->findFolder();
  559. $mainFolder = $uploader->getDestFolder();
  560. if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">generated folderName('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';var_dump($uploader);echo'</pre>';}
  561. if (!$mainFolder) {
  562. $mainFolder = $uploader->generateFolderName();
  563. $mainFolderPath = rtrim($PROJ_mount_point, '/') . '/' . $mainFolder;
  564. if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">generated folderName('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($mainFolder, $mainFolderPath));echo'</pre>';}
  565. mkdir($mainFolderPath, 0770, true);
  566. @chmod($mainFolderPath, 0770);
  567. if (!file_exists($mainFolderPath)) {
  568. trigger_error("Error: Nie uda‘?o siŽ? utworzyŽ? folderu! ({$mainFolder})", E_USER_NOTICE);
  569. return false;
  570. }
  571. $requirePermsExt = self::getRequiredPermsExtByRecord($project);
  572. $file = new stdClass();
  573. $file->name = '.';
  574. $file->path = '.';
  575. //$file->owner = '';
  576. //$file->group = '';
  577. //$file->perms = '';
  578. $file->isDir = true;
  579. $file->permsExt = array();
  580. $cmdList = self::fixFilePerms($file, $requirePermsExt, "{$PROJ_mount_point}/{$mainFolder}", $project);
  581. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">cmdList-P('.$project->ID.') fixFilePerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  582. }
  583. else {
  584. $cmdList = self::fixProject($project, $mainFolder, $PROJ_mount_point, $task);
  585. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">cmdList-P('.$project->ID.') fixProject (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  586. $mainFolderPath = rtrim($PROJ_mount_point, '/') . '/' . $mainFolder;
  587. $folderPismaPath = "{$mainFolderPath}/_PISMA";
  588. // if folder _PISMA not exists then create
  589. $cmdList[] = "if [ ! -d '{$folderPismaPath}' ] ; then mkdir '{$folderPismaPath}'; chmod 0770 '{$folderPismaPath}'; fi;";
  590. $cmdKorepList = self::fixProjectKoresp($project, $folderPismaPath);
  591. if (!empty($cmdKorepList)) {
  592. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">cmdList-P('.$project->ID.') fixProjectKoresp (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdKorepList);echo'</pre>';}
  593. foreach ($cmdKorepList as $vCmd) {
  594. $cmdList[] = $vCmd;
  595. }
  596. }
  597. if (V::get('TEST_DRUKI', '', $_GET, 'int') > 0) {
  598. // $project->CRM_LISTA_ZASOBOW_ID
  599. if ($project->CRM_LISTA_ZASOBOW_ID > 0) {
  600. }
  601. // TODO: $cmdDrukiList = self::fixProjectDruki($project, $mainFolder, $PROJ_mount_point);
  602. }
  603. }
  604. if (!empty($cmdList)) {
  605. foreach ($cmdList as $vCmd) {
  606. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Exec-cmdList-P('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vCmd);echo'</pre>';}
  607. exec($vCmd, $out, $outValue);
  608. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Done-cmdList-P('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($outValue, $out));echo'</pre>';}
  609. if ($outValue != 0) {
  610. trigger_error("Error-cmd: {$vCmd}", E_USER_NOTICE);
  611. }
  612. }
  613. }
  614. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">';print_r("executeTask finished OK");echo'</pre>';}
  615. }
  616. public static function getActiveLoginList() {
  617. static $activeLoginList;
  618. if (!is_array($activeLoginList)) {
  619. $activeLoginList = array();
  620. $db = DB::getDB();
  621. if (!$db) {
  622. die('DB Error!');
  623. }
  624. $sql = "select u.`ADM_ACCOUNT`
  625. from `ADMIN_USERS` as u
  626. where u.`A_STATUS` = 'NORMAL'
  627. ";
  628. $res = $db->query($sql);
  629. while ($r = $db->fetch($res)) {
  630. $activeLoginList[] = $r->ADM_ACCOUNT;
  631. }
  632. }
  633. return $activeLoginList;
  634. }
  635. public static function isActiveUser($login) {
  636. $activeLoginList = self::getActiveLoginList();
  637. return in_array($login, $activeLoginList);
  638. }
  639. public static function getRequiredPermsExtByRecord($project) {
  640. // TODO: need to check if user is correct in field L_APPOITMENT_USER
  641. $requirePermsExt = array();
  642. if (!$project->L_APPOITMENT_USER && !$project->A_ADM_COMPANY) {// no owner, no write group
  643. // TODO: group PODMIOT
  644. $requirePermsExt["group:workgroup"] = array('write', 'read');
  645. }
  646. else {
  647. if ($project->L_APPOITMENT_USER) {
  648. if (self::isActiveUser($project->L_APPOITMENT_USER)) {
  649. $requirePermsExt["user:{$project->L_APPOITMENT_USER}"] = array('write', 'read');
  650. } else {
  651. // TODO: trigger error $project->L_APPOITMENT_USER is not active user!
  652. }
  653. }
  654. if (!empty($project->A_ADM_COMPANY) && $project->A_ADM_COMPANY == $project->A_CLASSIFIED) {
  655. $requirePermsExt["group:{$project->A_ADM_COMPANY}"] = array('read', 'write');
  656. }
  657. else if (empty($project->A_ADM_COMPANY) && empty($project->A_CLASSIFIED)) {
  658. $requirePermsExt["group:workgroup"] = array('write', 'read');
  659. }
  660. else {
  661. if ($project->A_ADM_COMPANY) {
  662. $requirePermsExt["group:{$project->A_ADM_COMPANY}"] = array('write');
  663. }
  664. if ($project->A_CLASSIFIED) {
  665. $requirePermsExt["group:{$project->A_CLASSIFIED}"] = array('read');
  666. }
  667. }
  668. }
  669. // add parent owner
  670. if (!empty($project->PARENT_L_APPOITMENT_USER) && $project->PARENT_L_APPOITMENT_USER != $project->L_APPOITMENT_USER) {
  671. if (self::isActiveUser($project->PARENT_L_APPOITMENT_USER)) {
  672. $requirePermsExt["user:{$project->PARENT_L_APPOITMENT_USER}"] = array('write', 'read');
  673. } else {
  674. // TODO: trigger error $project->PARENT_L_APPOITMENT_USER is not active user!
  675. }
  676. }
  677. // add user:_www perms read, write
  678. $requirePermsExt["user:_www"] = array('write', 'read');
  679. return $requirePermsExt;
  680. }
  681. /**
  682. * Used for files added/modified by samba/afp.
  683. *
  684. * @return TODO: object to store in task->A_SYNC_RESULT
  685. */
  686. public static function fixLastModifiedFiles($task) {
  687. $db = DB::getDB();
  688. if (!$db) {
  689. die("DB Error: No DB!");
  690. }
  691. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fixLastModifiedFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("fixLastModifiedFiles");echo'</pre>';}
  692. $PROJ_mount_point = FoldersConfig::get('IN7_MK_BAZA_DYSTRYBUCJI_COLUMN', 'mount_point');
  693. $PISMA_mount_point = FoldersConfig::get('IN7_DZIENNIK_KORESP_COLUMN', 'mount_point');
  694. $foundProjectFiles = array();
  695. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$lastRunDate (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($task->A_LAST_SYNC);echo'</pre>';}
  696. //exec("cd {$PROJ_mount_point}; find . -newermt '{$task->A_LAST_SYNC}' ", $foundPaths);
  697. exec("cd {$PROJ_mount_point}; find . -newermt '{$task->A_LAST_SYNC}' -type f -exec ls -le '{}' \;", $filesWithPerms);// TODO: head -{$lastTotal + 10000}| tail
  698. if (!empty($filesWithPerms)) {
  699. $filesWithPermsTree = array();
  700. $lastName = '';
  701. foreach ($filesWithPerms as $line) {
  702. if (substr($line, 0, 1) == '-') {// file name
  703. $fileParts = array();
  704. $filePartsArr = explode(' ', $line);
  705. $lastInd = 0;
  706. foreach ($filePartsArr as $vPart) {
  707. if ($lastInd > 7) {// file name
  708. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  709. $lastInd++;
  710. }
  711. else if (!empty($vPart) || $vPart === '0') {
  712. $fileParts[] = $vPart;
  713. $lastInd++;
  714. }
  715. }
  716. $file = new stdClass();
  717. if (!isset($fileParts[8])) {
  718. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
  719. //continue;
  720. }
  721. $file->name = end($fileParts);
  722. $file->path = end($fileParts);
  723. //$file->owner = $fileParts[2];
  724. //$file->group = $fileParts[3];
  725. //$file->perms = $fileParts[0];
  726. $file->isDir = (substr($line, 0, 1) == 'd');
  727. $file->permsExt = array();
  728. $filesWithPermsTree[$file->name] = $file;
  729. $lastName = $file->name;
  730. }
  731. else if (substr($line, 0, 1) == ' ') {// extended perm line
  732. if ($lastName == '..') {
  733. continue;
  734. }
  735. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  736. }
  737. else {// parse error
  738. $lastName = '..';
  739. }
  740. }
  741. foreach ($filesWithPermsTree as $vFile) {
  742. $vFile->path = ltrim($vFile->path, './');
  743. $vFile->path = explode('/', $vFile->path);
  744. $vFile->projectFolder = array_shift($vFile->path);
  745. $vFile->path = implode('/', $vFile->path);
  746. $projId = explode('.', $vFile->projectFolder);
  747. $projId = reset($projId);
  748. if (is_numeric($projId) && $projId > 0) {
  749. $foundProjectFiles[$projId][] = $vFile;
  750. }
  751. }
  752. }
  753. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">filesWithPerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PROJ_mount_point}\n";print_r($filesWithPerms);echo'</pre>';}
  754. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">foundProjectFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PROJ_mount_point}\n";print_r($foundProjectFiles);echo'</pre>';}
  755. if (!empty($foundProjectFiles)) {
  756. $sql = "select p.`ID`
  757. , p.`L_APPOITMENT_USER`
  758. , p.`A_ADM_COMPANY`
  759. , p.`A_CLASSIFIED`
  760. , pp.`L_APPOITMENT_USER` as PARENT_L_APPOITMENT_USER
  761. from IN7_MK_BAZA_DYSTRYBUCJI as p
  762. left join IN7_MK_BAZA_DYSTRYBUCJI as pp on (pp.ID=p.P_ID)
  763. where p.`ID` in (" . implode(',', array_keys($foundProjectFiles)) . ")
  764. ";
  765. $res = $db->query($sql);
  766. while ($r = $db->fetch($res)) {
  767. $requirePermsExt = self::getRequiredPermsExtByRecord($r);
  768. foreach ($foundProjectFiles[$r->ID] as $vFile) {
  769. $cmdList = self::fixFilePerms($vFile, $requirePermsExt, "{$PROJ_mount_point}/{$vFile->projectFolder}", $r);
  770. if (!empty($cmdList)) {
  771. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  772. foreach ($cmdList as $vCmd) {
  773. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Exec-cmdList-P('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vCmd);echo'</pre>';}
  774. exec($vCmd, $out, $outValue);
  775. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Done-cmdList-P('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($outValue, $out));echo'</pre>';}
  776. if ($outValue != 0) {
  777. trigger_error("Error-cmd: {$vCmd}", E_USER_NOTICE);
  778. }
  779. }
  780. } else {
  781. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList is empty P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("empty");echo'</pre>';}
  782. }
  783. }
  784. }
  785. }
  786. }
  787. public static function fixProjectDruki() {
  788. if ($project->CRM_LISTA_ZASOBOW_ID <= 0) {
  789. return false;
  790. }
  791. $db = DB::getDB();
  792. if (!$db) {
  793. die("DB Error: No DB!");
  794. }
  795. }
  796. public static function fixProjectKoresp($project, $folderPismaPath) {
  797. $db = DB::getDB();
  798. if (!$db) {
  799. die("DB Error: No DB!");
  800. }
  801. $PISMA_mount_point = FoldersConfig::get('IN7_DZIENNIK_KORESP_COLUMN', 'mount_point');
  802. $PISMA_mount_point = rtrim($PISMA_mount_point, '/');
  803. $pismaList = array();
  804. // $PISMA_mount_point / {TYP_KORESP} / {ID} . *
  805. $sql = "select k.`ID`
  806. , k.`K_TYP_KORESP`
  807. from `IN7_DZIENNIK_KORESP` as k
  808. where k.`ID_PROJECT`={$project->ID}
  809. order by k.`ID` DESC
  810. limit 100
  811. ";
  812. $res = $db->query($sql);
  813. while ($r = $db->fetch($res)) {
  814. $pismaList[$r->ID] = $r->K_TYP_KORESP;// TODO: K_TYP_KORESP not used
  815. }
  816. if (empty($pismaList)) {
  817. return false;
  818. }
  819. $lsCmd = array();
  820. $lsCmd[] = "0.*/";// if only one folder then it doesnt show folder name, only files
  821. foreach ($pismaList as $kID => $vTyp) {
  822. $lsCmd[] = "{$kID}.*/";
  823. }
  824. if (empty($lsCmd)) {
  825. return false;
  826. }
  827. $lsCmd = 'ls -le ' . implode($lsCmd, ' ') . ' 2>>/dev/null ';
  828. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Koreps lsCmd (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($lsCmd);echo'</pre>';}
  829. exec("cd {$PISMA_mount_point}; {$lsCmd} ", $filesWithPerms);
  830. $filesWithPermsTree = array();
  831. if (!empty($filesWithPerms)) {
  832. $lastName = '';
  833. $folderParent = '';
  834. foreach ($filesWithPerms as $line) {
  835. if (substr($line, 0, 1) == '-') {// file name
  836. $fileParts = array();
  837. $filePartsArr = explode(' ', $line);
  838. $lastInd = 0;
  839. foreach ($filePartsArr as $vPart) {
  840. if ($lastInd > 7) {// file name
  841. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  842. $lastInd++;
  843. }
  844. else if (!empty($vPart) || $vPart === '0') {
  845. $fileParts[] = $vPart;
  846. $lastInd++;
  847. }
  848. }
  849. $file = new stdClass();
  850. if (!isset($fileParts[8])) {
  851. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
  852. //continue;
  853. }
  854. $file->name = end($fileParts);
  855. $file->path = array();
  856. if ($folderParent) $file->path[] = $folderParent;
  857. $file->path[] = end($fileParts);
  858. $file->path = implode('/', $file->path);
  859. //$file->owner = $fileParts[2];
  860. //$file->group = $fileParts[3];
  861. //$file->perms = $fileParts[0];
  862. $file->isDir = (substr($line, 0, 1) == 'd');
  863. $file->permsExt = array();
  864. $filesWithPermsTree[$file->name] = $file;
  865. $lastName = $file->name;
  866. }
  867. else if (substr($line, 0, 1) == ' ') {// extended perm line
  868. if ($lastName == '..') {
  869. continue;
  870. }
  871. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  872. }
  873. else if (substr($line, -1) == ':') {// folder
  874. $folderParent = trim(substr($line, 0, -1), '/');
  875. }
  876. else if (substr($line, 0, 5) == 'total') {
  877. continue;
  878. }
  879. else if (empty($line)) {
  880. $folderParent = '';
  881. continue;
  882. }
  883. else {// parse error
  884. $lastName = '..';
  885. }
  886. }
  887. }
  888. if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">filesWithPerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PISMA_mount_point}\n";print_r($filesWithPerms);echo'</pre>';}
  889. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">filesWithPermsTree (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PISMA_mount_point}\n";print_r($filesWithPermsTree);echo'</pre>';}
  890. $cmdList = array();
  891. $requirePermsExt = self::getRequiredPermsExtByRecord($project);
  892. foreach ($filesWithPermsTree as $kFileName => $vFile) {
  893. $cmdFile = self::fixFilePerms($vFile, $requirePermsExt, "{$PISMA_mount_point}", $project);
  894. if (!empty($cmdFile)) {
  895. foreach ($cmdFile as $vCmd) {
  896. $cmdList[] = $vCmd;
  897. }
  898. }
  899. // if folder _PISMA not exists then create
  900. $fname = end(explode('/', $vFile->path));
  901. $cmdList []= "if [ ! -f '{$folderPismaPath}/{$fname}' ] ; then ln '{$PISMA_mount_point}/{$vFile->path}' '{$folderPismaPath}'/; fi; ";
  902. }
  903. return $cmdList;
  904. }
  905. /*
  906. * Not used.
  907. */
  908. public static function preloadFixProject(&$task, $mainFolder, $PROJ_mount_point) {
  909. if ($task->ID_PROJECT == 1695) {// TODO: biall-net - 8853 pliki w katalog - stary HANDLOWY
  910. if (isset($task->A_SYNC_RESULT->total)) {
  911. exec("cd '{$PROJ_mount_point}/{$mainFolder}' && find . -type f | wc -l ", $filesTotal);
  912. if (!empty($filesTotal)) {
  913. $filesTotal = reset($filesTotal);
  914. $filesTotal = intval(trim($filesTotal));
  915. $task->A_SYNC_RESULT->total = $filesTotal;
  916. self::saveTask($task->ID_PROJECT, 0, $task->A_SYNC_RESULT);
  917. }
  918. }
  919. }
  920. }
  921. public static function fixProject($r, $mainFolder, $PROJ_mount_point, &$task) {
  922. $time = time();
  923. if ($r->ID == 1695) {// TODO: biall-net - 8853 pliki w katalog - stary HANDLOWY
  924. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">TODO: pomin - za du‘«o plikƈw ('.$r->ID.'/'.$mainFolder.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($r);echo'</pre>';}
  925. //return false;
  926. }
  927. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">r('.$r->ID.'/'.$mainFolder.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($r);echo'</pre>';}
  928. $requirePermsExt = self::getRequiredPermsExtByRecord($r);
  929. $filesWithPerms = array();
  930. $cmd = " ls -Rlea . ";
  931. if (false) {//$r->ID == 1695) {// TODO: biall-net - 8853 pliki w katalog - stary HANDLOWY
  932. if (isset($task->A_SYNC_RESULT->total)) {
  933. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">A_SYNC_RESULT (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("A_SYNC_RESULT[total]={$task->A_SYNC_RESULT->total}");echo'</pre>';}
  934. if ($task->A_SYNC_RESULT->total > 1000) {
  935. $lastDone = V::get('lastDone', 0, $task->A_SYNC_RESULT, 'int');
  936. if ($lastDone > 0) {
  937. $task->A_SYNC_RESULT->lastDone = $lastDone + 1000;
  938. $cmd = " find . -type f | head -" . ($lastDone + 1000) . " | tail -1000 | xargs ls -le ";
  939. } else {
  940. $task->A_SYNC_RESULT->lastDone = 1000;
  941. $cmd = " find . -type f | head -1000 | xargs ls -le ";
  942. }
  943. }
  944. }
  945. }
  946. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">cmd (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("cd '{$PROJ_mount_point}/{$mainFolder}' && {$cmd} ");echo'</pre>';}
  947. exec("cd '{$PROJ_mount_point}/{$mainFolder}' && {$cmd} ", $filesWithPerms);
  948. if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPerms);echo'</pre>';}
  949. $filesWithPermsTree = array();
  950. $lastName = '';
  951. $folderParent = '';
  952. foreach ($filesWithPerms as $line) {
  953. if (substr($line, 0, 1) == '-' || substr($line, 0, 1) == 'd') {// file name
  954. $fileParts = array();
  955. $filePartsArr = explode(' ', $line);
  956. $lastInd = 0;
  957. foreach ($filePartsArr as $vPart) {
  958. if ($lastInd > 7) {// file name
  959. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  960. $lastInd++;
  961. }
  962. else if (!empty($vPart) || $vPart === '0') {
  963. $fileParts[] = $vPart;
  964. $lastInd++;
  965. }
  966. }
  967. if (end($fileParts) == '..' || (end($fileParts) == '.' && $folderParent)) {
  968. $lastName = '..';
  969. continue;
  970. }
  971. $file = new stdClass();
  972. if (!isset($fileParts[8])) {
  973. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
  974. //continue;
  975. }
  976. $file->name = end($fileParts);
  977. $file->path = array();
  978. if ($folderParent) $file->path[] = $folderParent;
  979. $file->path[] = end($fileParts);
  980. $file->path = implode('/', $file->path);
  981. //$file->owner = $fileParts[2];
  982. //$file->group = $fileParts[3];
  983. //$file->perms = $fileParts[0];
  984. $file->isDir = (substr($line, 0, 1) == 'd');
  985. $file->permsExt = array();
  986. $filesWithPermsTree[$file->name] = $file;
  987. $lastName = $file;
  988. }
  989. else if (substr($line, 0, 1) == ' ') {// extended perm line
  990. if ($lastName == '..') {
  991. continue;
  992. }
  993. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  994. }
  995. else if (substr($line, 0, 2) == './' && substr($line, -1) == ':') {// folder
  996. $folderParent = substr($line, 2, -1);
  997. }
  998. else if (substr($line, 0, 5) == 'total') {
  999. continue;
  1000. }
  1001. else if (empty($line)) {
  1002. $folderParent = '';
  1003. continue;
  1004. }
  1005. }
  1006. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPermsTree (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPermsTree);echo'</pre>';}
  1007. // check perms
  1008. /*
  1009. files:
  1010. W read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown
  1011. W read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity
  1012. R read, execute, readattr, readextattr, readsecurity
  1013. dir:
  1014. W list,add_file,search,add_subdirectory,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown,file_inherit,directory_inherit
  1015. W list,add_file,search,add_subdirectory,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity, file_inherit,directory_inherit
  1016. R list, search, readattr, readextattr, readsecurity, file_inherit,directory_inherit
  1017. */
  1018. $cmdList = array();
  1019. foreach ($filesWithPermsTree as $kFileName => $vFile) {
  1020. if (false) {
  1021. // TODO: $kFileName == '_PISMA' - readonly
  1022. // TODO: $vFile->path => _PISMA/...
  1023. }
  1024. else {
  1025. $cmdFile = self::fixFilePerms($vFile, $requirePermsExt, "{$PROJ_mount_point}/{$mainFolder}", $r);
  1026. if (!empty($cmdFile)) {
  1027. foreach ($cmdFile as $vCmd) {
  1028. $cmdList[] = $vCmd;
  1029. }
  1030. }
  1031. }
  1032. }
  1033. return $cmdList;
  1034. }
  1035. public static function fixFilePerms($vFile, $requirePermsExt, $mainPath, $r) {
  1036. //trigger_error("fixFilePerms: " . json_encode($vFile), E_USER_NOTICE);
  1037. $cmdList = array();
  1038. $vReqPermsExt = array();
  1039. foreach ($requirePermsExt as $kPermObj => $vPerms) {
  1040. $vReqPermsExt[$kPermObj] = array();
  1041. foreach ($vPerms as $vPerm) {
  1042. if ($vFile->isDir) {
  1043. if ($vPerm == 'read') {
  1044. $vReqPermsExt[$kPermObj]['list'] = 0;
  1045. $vReqPermsExt[$kPermObj]['search'] = 0;
  1046. $vReqPermsExt[$kPermObj]['readattr'] = 0;
  1047. $vReqPermsExt[$kPermObj]['readextattr'] = 0;
  1048. $vReqPermsExt[$kPermObj]['readsecurity'] = 0;
  1049. $vReqPermsExt[$kPermObj]['file_inherit'] = 0;
  1050. $vReqPermsExt[$kPermObj]['directory_inherit'] = 0;
  1051. }
  1052. else if ($vPerm == 'write') {
  1053. $vReqPermsExt[$kPermObj]['add_file'] = 0;
  1054. $vReqPermsExt[$kPermObj]['add_subdirectory'] = 0;
  1055. $vReqPermsExt[$kPermObj]['delete_child'] = 0;
  1056. $vReqPermsExt[$kPermObj]['writeattr'] = 0;
  1057. $vReqPermsExt[$kPermObj]['writeextattr'] = 0;
  1058. $vReqPermsExt[$kPermObj]['writesecurity'] = 0;
  1059. $vReqPermsExt[$kPermObj]['chown'] = 0;
  1060. }
  1061. }
  1062. else {
  1063. if ($vPerm == 'read') {
  1064. $vReqPermsExt[$kPermObj]['read'] = 0;
  1065. $vReqPermsExt[$kPermObj]['execute'] = 0;
  1066. $vReqPermsExt[$kPermObj]['readattr'] = 0;
  1067. $vReqPermsExt[$kPermObj]['readextattr'] = 0;
  1068. $vReqPermsExt[$kPermObj]['readsecurity'] = 0;
  1069. }
  1070. else if ($vPerm == 'write') {
  1071. $vReqPermsExt[$kPermObj]['write'] = 0;
  1072. $vReqPermsExt[$kPermObj]['append'] = 0;
  1073. $vReqPermsExt[$kPermObj]['writeattr'] = 0;
  1074. $vReqPermsExt[$kPermObj]['writeextattr'] = 0;
  1075. $vReqPermsExt[$kPermObj]['writesecurity'] = 0;
  1076. $vReqPermsExt[$kPermObj]['chown'] = 0;
  1077. }
  1078. }
  1079. }
  1080. }
  1081. $permsToRemove = array();
  1082. foreach ($vFile->permsExt as $vPermExtLine) {
  1083. $vPermExtArr = explode(' ', $vPermExtLine);
  1084. $vPermExt = new stdClass();
  1085. $vPermExt->nr = trim($vPermExtArr[0], ' :');
  1086. $vPermExt->permObj = $vPermExtArr[1];
  1087. $vPermExt->perms = '';
  1088. if (count($vPermExtArr) == 4) {
  1089. $vPermExt->perms = explode(',', $vPermExtArr[3]);
  1090. }
  1091. else if (count($vPermExtArr) == 5 && $vPermExtArr[2] == 'inherited') {
  1092. $vPermExt->perms = explode(',', $vPermExtArr[4]);
  1093. }
  1094. else {
  1095. echo "Error: Perm Ext Line format! ({$vPermExtLine})";
  1096. continue;
  1097. }
  1098. $permFound = false;
  1099. foreach ($vReqPermsExt as $kPermObj => $vPerms) {
  1100. if (false !== strpos($vPermExtLine, $kPermObj)) {
  1101. foreach ($vPerms as $kPerm => $vPermChecked) {
  1102. if (in_array($kPerm, $vPermExt->perms)) {
  1103. $vReqPermsExt[$kPermObj][$kPerm] = 1;
  1104. $permFound = true;
  1105. }
  1106. }
  1107. }
  1108. }
  1109. if (!$permFound) {
  1110. $permsToRemove[] = $vPermExt->nr;
  1111. }
  1112. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$vReqPermsExt('.$vFile->name.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vReqPermsExt);echo'</pre>';
  1113. }
  1114. if (!empty($permsToRemove)) {
  1115. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:300px;overflow:auto;border:1px solid red;text-align:left;">TO-rm('.$r->ID.'): $permsToRemove('.$vFile->name.') isDir('.$vFile->isDir.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('permsToRemove'=>$permsToRemove, 'vFile->permsExt'=>$vFile->permsExt, 'r'=>$r));echo'</pre>';}
  1116. $permsToRemove = array_reverse($permsToRemove);
  1117. foreach ($permsToRemove as $vPermInd) {
  1118. $cmdList []= "chmod -a# {$vPermInd} '{$mainPath}/{$vFile->path}' ";
  1119. }
  1120. }
  1121. $permsToAdd = array();
  1122. foreach ($vReqPermsExt as $kPermObj => $vPerms) {
  1123. foreach ($vPerms as $kPerm => $vPermChecked) {
  1124. if (!$vPermChecked) {
  1125. $permsToAdd[$kPermObj][$kPerm] = 1;
  1126. }
  1127. }
  1128. }
  1129. if (!empty($permsToAdd)) {
  1130. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:300px;overflow:auto;border:1px solid red;text-align:left;">TO-add('.$r->ID.'): $permsToAdd('.$vFile->name.') isDir('.$vFile->isDir.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('permsToAdd'=>$permsToAdd, 'vFile->permsExt'=>$vFile->permsExt, 'r'=>$r));echo'</pre>';}
  1131. foreach ($permsToAdd as $kPermObj => $vPerms) {
  1132. $cmdList []= "chmod +a \"{$kPermObj} allow " . implode(',', array_keys($vPerms)) . "\" '{$mainPath}/{$vFile->path}' ";
  1133. }
  1134. }
  1135. return $cmdList;
  1136. }
  1137. /**
  1138. * @returns array - last modified project ids.
  1139. */
  1140. public static function fixLastModifiedByFiles() {// TODO: RMME
  1141. $db = DB::getDB();
  1142. if (!$db) {
  1143. die("DB Error: No DB!");
  1144. }
  1145. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fixLastModifiedByFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("fixLastModifiedByFiles");echo'</pre>';}
  1146. /*
  1147. * $ man find:
  1148. -newer file
  1149. True if the current file has a more recent last modification time than file.
  1150. -newerXY file
  1151. True if the current file has a more recent last access time (X=a), inode creation time (X=B), change time (X=c),
  1152. or modification time (X=m) than the last access time (Y=a), inode creation time (Y=B), change time (Y=c), or mod-
  1153. ification time (Y=m) of file. In addition, if Y=t, then file is instead interpreted as a direct date specifica-
  1154. tion of the form understood by cvs(1). Note that -newermm is equivalent to -newer.
  1155. *
  1156. * $ man chmod:
  1157. -i Removes the 'inherited' bit from all entries in the named file(s) ACLs.
  1158. *
  1159. * chmod -a "admin allow write" file1 # remove line
  1160. * chmod -a# 1 file1 # remove line at position 1
  1161. *
  1162. * chmod +a nie zmienia modify date: find . -newermt '2013-10-07 ...'
  1163. */
  1164. // find /Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY -newermt '2013-10-07 16:20'
  1165. $PROJ_mount_point = FoldersConfig::get('IN7_MK_BAZA_DYSTRYBUCJI_COLUMN', 'mount_point');
  1166. $PISMA_mount_point = FoldersConfig::get('IN7_DZIENNIK_KORESP_COLUMN', 'mount_point');
  1167. $foundProjectIds = array();
  1168. $lastRunDate = self::getLastRunDate();
  1169. exec("cd {$PROJ_mount_point}; find . -newermt '{$lastRunDate}' ", $foundPaths);
  1170. if (!empty($foundPaths)) {
  1171. foreach ($foundPaths as $path) {
  1172. $path = ltrim($path, './');
  1173. $folder = explode('/', $path);
  1174. $folder = reset($folder);
  1175. $projId = explode('.', $folder);
  1176. $projId = reset($projId);
  1177. if (is_numeric($projId)) {
  1178. $foundProjectIds[$projId] = $folder;
  1179. }
  1180. }
  1181. }
  1182. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">foundPaths (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PROJ_mount_point}\n";print_r($foundPaths);echo'</pre>';}
  1183. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">foundProjectIds (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PROJ_mount_point}\n";print_r($foundProjectIds);echo'</pre>';}
  1184. if (!empty($foundProjectIds)) {
  1185. $sql = "select p.`ID`
  1186. , p.`L_APPOITMENT_USER`
  1187. , p.`A_ADM_COMPANY`
  1188. , p.`A_CLASSIFIED`
  1189. , pp.`L_APPOITMENT_USER` as PARENT_L_APPOITMENT_USER
  1190. from IN7_MK_BAZA_DYSTRYBUCJI as p
  1191. left join IN7_MK_BAZA_DYSTRYBUCJI as pp on (pp.ID=p.P_ID)
  1192. where p.`ID` in (" . implode(',', array_keys($foundProjectIds)) . ")
  1193. ";
  1194. $res = $db->query($sql);
  1195. while ($r = $db->fetch($res)) {
  1196. $mainFolder = $foundProjectIds[$r->ID];
  1197. $cmdList = self::fixProject($r, $mainFolder, $PROJ_mount_point);
  1198. if (!empty($cmdList)) {
  1199. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  1200. } else {
  1201. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  1202. }
  1203. }
  1204. }
  1205. return array_keys($foundProjectIds);
  1206. }
  1207. public static function fixLastModifiedByDB($fixedProjIds) {// TODO: RMME
  1208. $db = DB::getDB();
  1209. if (!$db) {
  1210. die("DB Error: No DB!");
  1211. }
  1212. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fixLastModifiedByDB (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("fixLastModifiedByDB");echo'</pre>';}
  1213. $sqlWhereAdd = '';
  1214. if (!empty($fixedProjIds)) {
  1215. $sqlWhereAdd = " and p.`ID` not in (" . implode(',', $fixedProjIds) . ") ";
  1216. }
  1217. $projectList = array();
  1218. $lastRunDate = self::getLastRunDate();
  1219. $sql = "select p.`ID`
  1220. , p.`L_APPOITMENT_USER`
  1221. , p.`A_ADM_COMPANY`
  1222. , p.`A_CLASSIFIED`
  1223. , pp.`L_APPOITMENT_USER` as PARENT_L_APPOITMENT_USER
  1224. from IN7_MK_BAZA_DYSTRYBUCJI as p
  1225. left join IN7_MK_BAZA_DYSTRYBUCJI as pp on (pp.ID=p.P_ID)
  1226. where
  1227. ( p.`A_RECORD_UPDATE_DATE`>'{$lastRunDate}'
  1228. or p.`A_RECORD_CREATE_DATE`>'{$lastRunDate}'
  1229. )
  1230. {$sqlWhereAdd}
  1231. ";
  1232. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sql (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';}
  1233. $res = $db->query($sql);
  1234. while ($r = $db->fetch($res)) {
  1235. $projectList[$r->ID] = $r;
  1236. }
  1237. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">projectList (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($projectList);echo'</pre>';}
  1238. }
  1239. public static function getLastRunDate() {// TODO: RMME
  1240. if (($argFromDate = V::get('_fromDate', '', $_GET)) != '') {
  1241. // Format: 2013-10-07 23:46
  1242. if (strlen($argFromDate) == 16
  1243. && substr($argFromDate, 4, 1) == '-'
  1244. && substr($argFromDate, 7, 1) == '-'
  1245. && substr($argFromDate, 10, 1) == '-'
  1246. && substr($argFromDate, 13, 1) == ':'
  1247. && is_numeric(str_replace(array('-', ':'), '', $argFromDate))
  1248. ) {
  1249. $lastRunDate = mktime(substr($argFromDate, 11, 2), substr($argFromDate, 14, 2), 0, substr($argFromDate, 5, 2), substr($argFromDate, 8, 2), substr($argFromDate, 0, 4));
  1250. $lastRunDate = date("Y-m-d H:i", $lastRunDate);
  1251. }
  1252. }
  1253. if (!$lastRunDate) {
  1254. $lastRunDate = mktime(date("H") - 1, date("i"), date("s"), date("n"), date("j"), date("Y"));
  1255. $lastRunDate = date("Y-m-d H:i", $lastRunDate);
  1256. }
  1257. //$lastRunDate = '2013-09-01 01:00';
  1258. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">lastRunDate (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($lastRunDate);echo'</pre>';
  1259. return $lastRunDate;
  1260. }
  1261. public static function usersAction() {
  1262. $task = self::getTaskNewerUsers();
  1263. $users = self::getUsersNewerThen($task->A_LAST_SYNC);
  1264. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$users (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($users);echo'</pre>';
  1265. self::saveTask(-2);
  1266. }
  1267. public static function usersAllAction() {
  1268. /*
  1269. * DBU - DB User LDU - LDAP User
  1270. * DBG - DB Group LDG - LDAP Group
  1271. *
  1272. * DBU - ADMIN_USERS
  1273. * DBG - CRM_LISTA_ZASOBOW where TYPE in('STANOWISKO','PODMIOT','DZIAL')// TODO: GRUPA_PROJEKTOWA - ldap nested group?
  1274. *
  1275. * 1. fetch DB Users
  1276. * ? only active users (A_STATUS == 'NORMAL')
  1277. * 2. fetch LDAP Users
  1278. *
  1279. * DBU.ADM_ACCOUNT == LDU.uid
  1280. * DBG.A_LDAP_GID == LDG.gidNumber
  1281. *
  1282. * TODO: $group createLdapGroup()
  1283. *
  1284. */
  1285. Lib::loadClass('UsersHelper');
  1286. $users = self::getUsersAll();
  1287. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">users count('.count($users).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($users);echo'</pre>';
  1288. $allLdapUsers = UsersHelper::getLDAPUsersAll();
  1289. $ldapUsers = array();
  1290. foreach ($allLdapUsers as $vLdapUser) {
  1291. $ldapUsers[$vLdapUser->uid] = $vLdapUser;
  1292. }
  1293. unset($allLdapUsers);
  1294. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">ldapUsers count('.count($ldapUsers).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($ldapUsers);echo'</pre>';
  1295. foreach ($users as $kLogin => $vUser) {
  1296. if ($vUser->A_STATUS == 'NORMAL') {
  1297. if (array_key_exists($vUser->ADM_ACCOUNT, $ldapUsers)) {
  1298. echo '<div>'.$vUser->ADM_ACCOUNT.': OK? account exists in LDAP</div>';
  1299. }
  1300. else {
  1301. echo '<div>'.$vUser->ADM_ACCOUNT.': TODO: create account in LDAP</div>';
  1302. }
  1303. }
  1304. else if ($vUser->A_STATUS == 'DELETED') {
  1305. if (array_key_exists($vUser->ADM_ACCOUNT, $ldapUsers)) {
  1306. echo '<div>'.$vUser->ADM_ACCOUNT.': TODO: disable account</div>';
  1307. }
  1308. else {
  1309. //echo '<div>'.$vUser->ADM_ACCOUNT.': WARNING: account not exists in LDAP</div>';
  1310. }
  1311. }
  1312. }
  1313. }
  1314. public static function getUsersNewerThen($datetime) {
  1315. $users = array();
  1316. $db = DB::getDB();
  1317. if (!$db) {
  1318. die("DB Error: No DB!");
  1319. }
  1320. $sqlWhereAdd = "";
  1321. if ($datetime) {
  1322. $sqlWhereAdd = " and ( u.`A_RECORD_CREATE_DATE`>'{$datetime}' or u.`A_RECORD_UPDATE_DATE`>'{$datetime}' )";
  1323. } else {
  1324. // TODO: error datetime not set
  1325. }
  1326. $sql = "select u.ID
  1327. , u.`ADM_ACCOUNT`
  1328. , u.`ADM_NAME`
  1329. , u.`A_STATUS`
  1330. from `ADMIN_USERS` as u
  1331. where
  1332. u.`A_STATUS` in('NORMAL', 'DELETED')
  1333. ";
  1334. $res = $db->query($sql);
  1335. while ($r = $db->fetch($res)) {
  1336. $users[$r->ADM_ACCOUNT] = $r;
  1337. }
  1338. return $users;
  1339. }
  1340. public static function getUsersAll() {
  1341. $users = array();
  1342. $db = DB::getDB();
  1343. if (!$db) {
  1344. die("DB Error: No DB!");
  1345. }
  1346. $sql = "select u.ID
  1347. , u.`ADM_ACCOUNT`
  1348. , u.`ADM_NAME`
  1349. , u.`A_STATUS`
  1350. from `ADMIN_USERS` as u
  1351. where
  1352. u.`A_STATUS` in('NORMAL', 'DELETED')
  1353. ";
  1354. $res = $db->query($sql);
  1355. while ($r = $db->fetch($res)) {
  1356. $users[$r->ADM_ACCOUNT] = $r;
  1357. }
  1358. return $users;
  1359. }
  1360. }
  1361. //dodatkowo synchronizacja automatyczna uprawnien
  1362. //SEF('KIKE_MIGRACJA_KIKE_AUTH');
  1363. //if(strstr($_SESSION['SYSTEM_PROFILE_STRING'],'KIKE' )) KIKE_MIGRACJA_KIKE_AUTH($LAST_TIMESTAMP);
  1364. ?>